luci2: remove newline from generated view constructor code to make debugger line...
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2         LuCI2 - OpenWrt Web Interface
3
4         Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
6         Licensed under the Apache License, Version 2.0 (the "License");
7         you may not use this file except in compliance with the License.
8         You may obtain a copy of the License at
9
10                 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18         function esc(s, r) {
19                 for( var i = 0; i < r.length; i += 2 )
20                         s = s.replace(r[i], r[i+1]);
21                 return s;
22         }
23
24         var str = this;
25         var out = '';
26         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27         var a = b = [], numSubstitutions = 0, numMatches = 0;
28
29         while ((a = re.exec(str)) != null)
30         {
31                 var m = a[1];
32                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33                 var pPrecision = a[6], pType = a[7];
34
35                 numMatches++;
36
37                 if (pType == '%')
38                 {
39                         subst = '%';
40                 }
41                 else
42                 {
43                         if (numSubstitutions < arguments.length)
44                         {
45                                 var param = arguments[numSubstitutions++];
46
47                                 var pad = '';
48                                 if (pPad && pPad.substr(0,1) == "'")
49                                         pad = leftpart.substr(1,1);
50                                 else if (pPad)
51                                         pad = pPad;
52
53                                 var justifyRight = true;
54                                 if (pJustify && pJustify === "-")
55                                         justifyRight = false;
56
57                                 var minLength = -1;
58                                 if (pMinLength)
59                                         minLength = parseInt(pMinLength);
60
61                                 var precision = -1;
62                                 if (pPrecision && pType == 'f')
63                                         precision = parseInt(pPrecision.substring(1));
64
65                                 var subst = param;
66
67                                 switch(pType)
68                                 {
69                                         case 'b':
70                                                 subst = (parseInt(param) || 0).toString(2);
71                                                 break;
72
73                                         case 'c':
74                                                 subst = String.fromCharCode(parseInt(param) || 0);
75                                                 break;
76
77                                         case 'd':
78                                                 subst = (parseInt(param) || 0);
79                                                 break;
80
81                                         case 'u':
82                                                 subst = Math.abs(parseInt(param) || 0);
83                                                 break;
84
85                                         case 'f':
86                                                 subst = (precision > -1)
87                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
88                                                         : (parseFloat(param) || 0.0);
89                                                 break;
90
91                                         case 'o':
92                                                 subst = (parseInt(param) || 0).toString(8);
93                                                 break;
94
95                                         case 's':
96                                                 subst = param;
97                                                 break;
98
99                                         case 'x':
100                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101                                                 break;
102
103                                         case 'X':
104                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105                                                 break;
106
107                                         case 'h':
108                                                 subst = esc(param, html_esc);
109                                                 break;
110
111                                         case 'q':
112                                                 subst = esc(param, quot_esc);
113                                                 break;
114
115                                         case 'j':
116                                                 subst = String.serialize(param);
117                                                 break;
118
119                                         case 't':
120                                                 var td = 0;
121                                                 var th = 0;
122                                                 var tm = 0;
123                                                 var ts = (param || 0);
124
125                                                 if (ts > 60) {
126                                                         tm = Math.floor(ts / 60);
127                                                         ts = (ts % 60);
128                                                 }
129
130                                                 if (tm > 60) {
131                                                         th = Math.floor(tm / 60);
132                                                         tm = (tm % 60);
133                                                 }
134
135                                                 if (th > 24) {
136                                                         td = Math.floor(th / 24);
137                                                         th = (th % 24);
138                                                 }
139
140                                                 subst = (td > 0)
141                                                         ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142                                                         : '%dh %dm %ds'.format(th, tm, ts);
143
144                                                 break;
145
146                                         case 'm':
147                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150                                                 var i = 0;
151                                                 var val = parseFloat(param || 0);
152                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154                                                 for (i = 0; (i < units.length) && (val > mf); i++)
155                                                         val /= mf;
156
157                                                 subst = val.toFixed(pr) + ' ' + units[i];
158                                                 break;
159                                 }
160
161                                 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163                                 if (minLength > 0 && pad.length > 0)
164                                         for (var i = 0; i < (minLength - subst.length); i++)
165                                                 subst = justifyRight ? (pad + subst) : (subst + pad);
166                         }
167                 }
168
169                 out += leftpart + subst;
170                 str = str.substr(m.length);
171         }
172
173         return out + str;
174 }
175
176 function LuCI2()
177 {
178         var _luci2 = this;
179
180         var Class = function() { };
181
182         Class.extend = function(properties)
183         {
184                 Class.initializing = true;
185
186                 var prototype = new this();
187                 var superprot = this.prototype;
188
189                 Class.initializing = false;
190
191                 $.extend(prototype, properties, {
192                         callSuper: function() {
193                                 var args = [ ];
194                                 var meth = arguments[0];
195
196                                 if (typeof(superprot[meth]) != 'function')
197                                         return undefined;
198
199                                 for (var i = 1; i < arguments.length; i++)
200                                         args.push(arguments[i]);
201
202                                 return superprot[meth].apply(this, args);
203                         }
204                 });
205
206                 function _class()
207                 {
208                         this.options = arguments[0] || { };
209
210                         if (!Class.initializing && typeof(this.init) == 'function')
211                                 this.init.apply(this, arguments);
212                 }
213
214                 _class.prototype = prototype;
215                 _class.prototype.constructor = _class;
216
217                 _class.extend = arguments.callee;
218
219                 return _class;
220         };
221
222         this.defaults = function(obj, def)
223         {
224                 for (var key in def)
225                         if (typeof(obj[key]) == 'undefined')
226                                 obj[key] = def[key];
227
228                 return obj;
229         };
230
231         this.isDeferred = function(x)
232         {
233                 return (typeof(x) == 'object' &&
234                         typeof(x.then) == 'function' &&
235                         typeof(x.promise) == 'function');
236         };
237
238         this.deferrable = function()
239         {
240                 if (this.isDeferred(arguments[0]))
241                         return arguments[0];
242
243                 var d = $.Deferred();
244                     d.resolve.apply(d, arguments);
245
246                 return d.promise();
247         };
248
249         this.i18n = {
250
251                 loaded: false,
252                 catalog: { },
253                 plural:  function(n) { return 0 + (n != 1) },
254
255                 init: function() {
256                         if (_luci2.i18n.loaded)
257                                 return;
258
259                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262                         for (var i = 0; i < langs.length; i++)
263                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264                                         async:    false,
265                                         cache:    true,
266                                         dataType: 'json',
267                                         success:  function(data) {
268                                                 $.extend(_luci2.i18n.catalog, data);
269
270                                                 var pe = _luci2.i18n.catalog[''];
271                                                 if (pe)
272                                                 {
273                                                         delete _luci2.i18n.catalog[''];
274                                                         try {
275                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
276                                                                 _luci2.i18n.plural = pf;
277                                                         } catch (e) { };
278                                                 }
279                                         }
280                                 });
281
282                         _luci2.i18n.loaded = true;
283                 }
284
285         };
286
287         this.tr = function(msgid)
288         {
289                 _luci2.i18n.init();
290
291                 var msgstr = _luci2.i18n.catalog[msgid];
292
293                 if (typeof(msgstr) == 'undefined')
294                         return msgid;
295                 else if (typeof(msgstr) == 'string')
296                         return msgstr;
297                 else
298                         return msgstr[0];
299         };
300
301         this.trp = function(msgid, msgid_plural, count)
302         {
303                 _luci2.i18n.init();
304
305                 var msgstr = _luci2.i18n.catalog[msgid];
306
307                 if (typeof(msgstr) == 'undefined')
308                         return (count == 1) ? msgid : msgid_plural;
309                 else if (typeof(msgstr) == 'string')
310                         return msgstr;
311                 else
312                         return msgstr[_luci2.i18n.plural(count)];
313         };
314
315         this.trc = function(msgctx, msgid)
316         {
317                 _luci2.i18n.init();
318
319                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321                 if (typeof(msgstr) == 'undefined')
322                         return msgid;
323                 else if (typeof(msgstr) == 'string')
324                         return msgstr;
325                 else
326                         return msgstr[0];
327         };
328
329         this.trcp = function(msgctx, msgid, msgid_plural, count)
330         {
331                 _luci2.i18n.init();
332
333                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335                 if (typeof(msgstr) == 'undefined')
336                         return (count == 1) ? msgid : msgid_plural;
337                 else if (typeof(msgstr) == 'string')
338                         return msgstr;
339                 else
340                         return msgstr[_luci2.i18n.plural(count)];
341         };
342
343         this.setHash = function(key, value)
344         {
345                 var h = '';
346                 var data = this.getHash(undefined);
347
348                 if (typeof(value) == 'undefined')
349                         delete data[key];
350                 else
351                         data[key] = value;
352
353                 var keys = [ ];
354                 for (var k in data)
355                         keys.push(k);
356
357                 keys.sort();
358
359                 for (var i = 0; i < keys.length; i++)
360                 {
361                         if (i > 0)
362                                 h += ',';
363
364                         h += keys[i] + ':' + data[keys[i]];
365                 }
366
367                 if (h)
368                         location.hash = '#' + h;
369         };
370
371         this.getHash = function(key)
372         {
373                 var data = { };
374                 var tuples = (location.hash || '#').substring(1).split(/,/);
375
376                 for (var i = 0; i < tuples.length; i++)
377                 {
378                         var tuple = tuples[i].split(/:/);
379                         if (tuple.length == 2)
380                                 data[tuple[0]] = tuple[1];
381                 }
382
383                 if (typeof(key) != 'undefined')
384                         return data[key];
385
386                 return data;
387         };
388
389         this.globals = {
390                 timeout:  3000,
391                 resource: '/luci2',
392                 sid:      '00000000000000000000000000000000'
393         };
394
395         this.rpc = {
396
397                 _id: 1,
398                 _batch: undefined,
399                 _requests: { },
400
401                 _call: function(req, cb)
402                 {
403                         return $.ajax('/ubus', {
404                                 cache:       false,
405                                 contentType: 'application/json',
406                                 data:        JSON.stringify(req),
407                                 dataType:    'json',
408                                 type:        'POST',
409                                 timeout:     _luci2.globals.timeout
410                         }).then(cb);
411                 },
412
413                 _list_cb: function(msg)
414                 {
415                         /* verify message frame */
416                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417                                 throw 'Invalid JSON response';
418
419                         return msg.result;
420                 },
421
422                 _call_cb: function(msg)
423                 {
424                         var data = [ ];
425                         var type = Object.prototype.toString;
426
427                         if (!$.isArray(msg))
428                                 msg = [ msg ];
429
430                         for (var i = 0; i < msg.length; i++)
431                         {
432                                 /* verify message frame */
433                                 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434                                         throw 'Invalid JSON response';
435
436                                 /* fetch related request info */
437                                 var req = _luci2.rpc._requests[msg[i].id];
438                                 if (typeof(req) != 'object')
439                                         throw 'No related request for JSON response';
440
441                                 /* fetch response attribute and verify returned type */
442                                 var ret = undefined;
443
444                                 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445                                         ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
446
447                                 if (req.expect)
448                                 {
449                                         for (var key in req.expect)
450                                         {
451                                                 if (typeof(ret) != 'undefined' && key != '')
452                                                         ret = ret[key];
453
454                                                 if (type.call(ret) != type.call(req.expect[key]))
455                                                         ret = req.expect[key];
456
457                                                 break;
458                                         }
459                                 }
460
461                                 /* apply filter */
462                                 if (typeof(req.filter) == 'function')
463                                 {
464                                         req.priv[0] = ret;
465                                         req.priv[1] = req.params;
466                                         ret = req.filter.apply(_luci2.rpc, req.priv);
467                                 }
468
469                                 /* store response data */
470                                 if (typeof(req.index) == 'number')
471                                         data[req.index] = ret;
472                                 else
473                                         data = ret;
474
475                                 /* delete request object */
476                                 delete _luci2.rpc._requests[msg[i].id];
477                         }
478
479                         return data;
480                 },
481
482                 list: function()
483                 {
484                         var params = [ ];
485                         for (var i = 0; i < arguments.length; i++)
486                                 params[i] = arguments[i];
487
488                         var msg = {
489                                 jsonrpc: '2.0',
490                                 id:      this._id++,
491                                 method:  'list',
492                                 params:  (params.length > 0) ? params : undefined
493                         };
494
495                         return this._call(msg, this._list_cb);
496                 },
497
498                 batch: function()
499                 {
500                         if (!$.isArray(this._batch))
501                                 this._batch = [ ];
502                 },
503
504                 flush: function()
505                 {
506                         if (!$.isArray(this._batch))
507                                 return _luci2.deferrable([ ]);
508
509                         var req = this._batch;
510                         delete this._batch;
511
512                         /* call rpc */
513                         return this._call(req, this._call_cb);
514                 },
515
516                 declare: function(options)
517                 {
518                         var _rpc = this;
519
520                         return function() {
521                                 /* build parameter object */
522                                 var p_off = 0;
523                                 var params = { };
524                                 if ($.isArray(options.params))
525                                         for (p_off = 0; p_off < options.params.length; p_off++)
526                                                 params[options.params[p_off]] = arguments[p_off];
527
528                                 /* all remaining arguments are private args */
529                                 var priv = [ undefined, undefined ];
530                                 for (; p_off < arguments.length; p_off++)
531                                         priv.push(arguments[p_off]);
532
533                                 /* store request info */
534                                 var req = _rpc._requests[_rpc._id] = {
535                                         expect: options.expect,
536                                         filter: options.filter,
537                                         params: params,
538                                         priv:   priv
539                                 };
540
541                                 /* build message object */
542                                 var msg = {
543                                         jsonrpc: '2.0',
544                                         id:      _rpc._id++,
545                                         method:  'call',
546                                         params:  [
547                                                 _luci2.globals.sid,
548                                                 options.object,
549                                                 options.method,
550                                                 params
551                                         ]
552                                 };
553
554                                 /* when a batch is in progress then store index in request data
555                                  * and push message object onto the stack */
556                                 if ($.isArray(_rpc._batch))
557                                 {
558                                         req.index = _rpc._batch.push(msg) - 1;
559                                         return _luci2.deferrable(msg);
560                                 }
561
562                                 /* call rpc */
563                                 return _rpc._call(msg, _rpc._call_cb);
564                         };
565                 }
566         };
567
568         this.uci = {
569
570                 writable: function()
571                 {
572                         return _luci2.session.access('ubus', 'uci', 'commit');
573                 },
574
575                 add: _luci2.rpc.declare({
576                         object: 'uci',
577                         method: 'add',
578                         params: [ 'config', 'type', 'name', 'values' ],
579                         expect: { section: '' }
580                 }),
581
582                 apply: function()
583                 {
584
585                 },
586
587                 configs: _luci2.rpc.declare({
588                         object: 'uci',
589                         method: 'configs',
590                         expect: { configs: [ ] }
591                 }),
592
593                 _changes: _luci2.rpc.declare({
594                         object: 'uci',
595                         method: 'changes',
596                         params: [ 'config' ],
597                         expect: { changes: [ ] }
598                 }),
599
600                 changes: function(config)
601                 {
602                         if (typeof(config) == 'string')
603                                 return this._changes(config);
604
605                         var configlist;
606                         return this.configs().then(function(configs) {
607                                 _luci2.rpc.batch();
608                                 configlist = configs;
609
610                                 for (var i = 0; i < configs.length; i++)
611                                         _luci2.uci._changes(configs[i]);
612
613                                 return _luci2.rpc.flush();
614                         }).then(function(changes) {
615                                 var rv = { };
616
617                                 for (var i = 0; i < configlist.length; i++)
618                                         if (changes[i].length)
619                                                 rv[configlist[i]] = changes[i];
620
621                                 return rv;
622                         });
623                 },
624
625                 commit: _luci2.rpc.declare({
626                         object: 'uci',
627                         method: 'commit',
628                         params: [ 'config' ]
629                 }),
630
631                 _delete_one: _luci2.rpc.declare({
632                         object: 'uci',
633                         method: 'delete',
634                         params: [ 'config', 'section', 'option' ]
635                 }),
636
637                 _delete_multiple: _luci2.rpc.declare({
638                         object: 'uci',
639                         method: 'delete',
640                         params: [ 'config', 'section', 'options' ]
641                 }),
642
643                 'delete': function(config, section, option)
644                 {
645                         if ($.isArray(option))
646                                 return this._delete_multiple(config, section, option);
647                         else
648                                 return this._delete_one(config, section, option);
649                 },
650
651                 delete_all: _luci2.rpc.declare({
652                         object: 'uci',
653                         method: 'delete',
654                         params: [ 'config', 'type', 'match' ]
655                 }),
656
657                 _foreach: _luci2.rpc.declare({
658                         object: 'uci',
659                         method: 'get',
660                         params: [ 'config', 'type' ],
661                         expect: { values: { } }
662                 }),
663
664                 foreach: function(config, type, cb)
665                 {
666                         return this._foreach(config, type).then(function(sections) {
667                                 for (var s in sections)
668                                         cb(sections[s]);
669                         });
670                 },
671
672                 get: _luci2.rpc.declare({
673                         object: 'uci',
674                         method: 'get',
675                         params: [ 'config', 'section', 'option' ],
676                         expect: { '': { } },
677                         filter: function(data, params) {
678                                 if (typeof(params.option) == 'undefined')
679                                         return data.values ? data.values['.type'] : undefined;
680                                 else
681                                         return data.value;
682                         }
683                 }),
684
685                 get_all: _luci2.rpc.declare({
686                         object: 'uci',
687                         method: 'get',
688                         params: [ 'config', 'section' ],
689                         expect: { values: { } },
690                         filter: function(data, params) {
691                                 if (typeof(params.section) == 'string')
692                                         data['.section'] = params.section;
693                                 else if (typeof(params.config) == 'string')
694                                         data['.package'] = params.config;
695                                 return data;
696                         }
697                 }),
698
699                 get_first: function(config, type, option)
700                 {
701                         return this._foreach(config, type).then(function(sections) {
702                                 for (var s in sections)
703                                 {
704                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
705
706                                         if (typeof(val) != 'undefined')
707                                                 return val;
708                                 }
709
710                                 return undefined;
711                         });
712                 },
713
714                 section: _luci2.rpc.declare({
715                         object: 'uci',
716                         method: 'add',
717                         params: [ 'config', 'type', 'name', 'values' ],
718                         expect: { section: '' }
719                 }),
720
721                 _set: _luci2.rpc.declare({
722                         object: 'uci',
723                         method: 'set',
724                         params: [ 'config', 'section', 'values' ]
725                 }),
726
727                 set: function(config, section, option, value)
728                 {
729                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
730                                 return this.section(config, section, option); /* option -> type */
731                         else if ($.isPlainObject(option))
732                                 return this._set(config, section, option); /* option -> values */
733
734                         var values = { };
735                             values[option] = value;
736
737                         return this._set(config, section, values);
738                 },
739
740                 order: _luci2.rpc.declare({
741                         object: 'uci',
742                         method: 'order',
743                         params: [ 'config', 'sections' ]
744                 })
745         };
746
747         this.network = {
748                 listNetworkNames: function() {
749                         return _luci2.rpc.list('network.interface.*').then(function(list) {
750                                 var names = [ ];
751                                 for (var name in list)
752                                         if (name != 'network.interface.loopback')
753                                                 names.push(name.substring(18));
754                                 names.sort();
755                                 return names;
756                         });
757                 },
758
759                 listDeviceNames: _luci2.rpc.declare({
760                         object: 'network.device',
761                         method: 'status',
762                         expect: { '': { } },
763                         filter: function(data) {
764                                 var names = [ ];
765                                 for (var name in data)
766                                         if (name != 'lo')
767                                                 names.push(name);
768                                 names.sort();
769                                 return names;
770                         }
771                 }),
772
773                 getNetworkStatus: function()
774                 {
775                         var nets = [ ];
776                         var devs = { };
777
778                         return this.listNetworkNames().then(function(names) {
779                                 _luci2.rpc.batch();
780
781                                 for (var i = 0; i < names.length; i++)
782                                         _luci2.network.getInterfaceStatus(names[i]);
783
784                                 return _luci2.rpc.flush();
785                         }).then(function(networks) {
786                                 for (var i = 0; i < networks.length; i++)
787                                 {
788                                         var net = nets[i] = networks[i];
789                                         var dev = net.l3_device || net.l2_device;
790                                         if (dev)
791                                                 net.device = devs[dev] || (devs[dev] = { });
792                                 }
793
794                                 _luci2.rpc.batch();
795
796                                 for (var dev in devs)
797                                         _luci2.network.getDeviceStatus(dev);
798
799                                 return _luci2.rpc.flush();
800                         }).then(function(devices) {
801                                 _luci2.rpc.batch();
802
803                                 for (var i = 0; i < devices.length; i++)
804                                 {
805                                         var brm = devices[i]['bridge-members'];
806                                         delete devices[i]['bridge-members'];
807
808                                         $.extend(devs[devices[i]['device']], devices[i]);
809
810                                         if (!brm)
811                                                 continue;
812
813                                         devs[devices[i]['device']].subdevices = [ ];
814
815                                         for (var j = 0; j < brm.length; j++)
816                                         {
817                                                 if (!devs[brm[j]])
818                                                 {
819                                                         devs[brm[j]] = { };
820                                                         _luci2.network.getDeviceStatus(brm[j]);
821                                                 }
822
823                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
824                                         }
825                                 }
826
827                                 return _luci2.rpc.flush();
828                         }).then(function(subdevices) {
829                                 for (var i = 0; i < subdevices.length; i++)
830                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
831
832                                 _luci2.rpc.batch();
833
834                                 for (var dev in devs)
835                                         _luci2.wireless.getDeviceStatus(dev);
836
837                                 return _luci2.rpc.flush();
838                         }).then(function(wifidevices) {
839                                 for (var i = 0; i < wifidevices.length; i++)
840                                         if (wifidevices[i])
841                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
842
843                                 nets.sort(function(a, b) {
844                                         if (a['interface'] < b['interface'])
845                                                 return -1;
846                                         else if (a['interface'] > b['interface'])
847                                                 return 1;
848                                         else
849                                                 return 0;
850                                 });
851
852                                 return nets;
853                         });
854                 },
855
856                 findWanInterfaces: function(cb)
857                 {
858                         return this.listNetworkNames().then(function(names) {
859                                 _luci2.rpc.batch();
860
861                                 for (var i = 0; i < names.length; i++)
862                                         _luci2.network.getInterfaceStatus(names[i]);
863
864                                 return _luci2.rpc.flush();
865                         }).then(function(interfaces) {
866                                 var rv = [ undefined, undefined ];
867
868                                 for (var i = 0; i < interfaces.length; i++)
869                                 {
870                                         if (!interfaces[i].route)
871                                                 continue;
872
873                                         for (var j = 0; j < interfaces[i].route.length; j++)
874                                         {
875                                                 var rt = interfaces[i].route[j];
876
877                                                 if (typeof(rt.table) != 'undefined')
878                                                         continue;
879
880                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
881                                                         rv[0] = interfaces[i];
882                                                 else if (rt.target == '::' && rt.mask == 0)
883                                                         rv[1] = interfaces[i];
884                                         }
885                                 }
886
887                                 return rv;
888                         });
889                 },
890
891                 getDHCPLeases: _luci2.rpc.declare({
892                         object: 'luci2.network',
893                         method: 'dhcp_leases',
894                         expect: { leases: [ ] }
895                 }),
896
897                 getDHCPv6Leases: _luci2.rpc.declare({
898                         object: 'luci2.network',
899                         method: 'dhcp6_leases',
900                         expect: { leases: [ ] }
901                 }),
902
903                 getRoutes: _luci2.rpc.declare({
904                         object: 'luci2.network',
905                         method: 'routes',
906                         expect: { routes: [ ] }
907                 }),
908
909                 getIPv6Routes: _luci2.rpc.declare({
910                         object: 'luci2.network',
911                         method: 'routes',
912                         expect: { routes: [ ] }
913                 }),
914
915                 getARPTable: _luci2.rpc.declare({
916                         object: 'luci2.network',
917                         method: 'arp_table',
918                         expect: { entries: [ ] }
919                 }),
920
921                 getInterfaceStatus: _luci2.rpc.declare({
922                         object: 'network.interface',
923                         method: 'status',
924                         params: [ 'interface' ],
925                         expect: { '': { } },
926                         filter: function(data, params) {
927                                 data['interface'] = params['interface'];
928                                 data['l2_device'] = data['device'];
929                                 delete data['device'];
930                                 return data;
931                         }
932                 }),
933
934                 getDeviceStatus: _luci2.rpc.declare({
935                         object: 'network.device',
936                         method: 'status',
937                         params: [ 'name' ],
938                         expect: { '': { } },
939                         filter: function(data, params) {
940                                 data['device'] = params['name'];
941                                 return data;
942                         }
943                 }),
944
945                 getConntrackCount: _luci2.rpc.declare({
946                         object: 'luci2.network',
947                         method: 'conntrack_count',
948                         expect: { '': { count: 0, limit: 0 } }
949                 })
950         };
951
952         this.wireless = {
953                 listDeviceNames: _luci2.rpc.declare({
954                         object: 'iwinfo',
955                         method: 'devices',
956                         expect: { 'devices': [ ] },
957                         filter: function(data) {
958                                 data.sort();
959                                 return data;
960                         }
961                 }),
962
963                 getDeviceStatus: _luci2.rpc.declare({
964                         object: 'iwinfo',
965                         method: 'info',
966                         params: [ 'device' ],
967                         expect: { '': { } },
968                         filter: function(data, params) {
969                                 if (!$.isEmptyObject(data))
970                                 {
971                                         data['device'] = params['device'];
972                                         return data;
973                                 }
974                                 return undefined;
975                         }
976                 }),
977
978                 getAssocList: _luci2.rpc.declare({
979                         object: 'iwinfo',
980                         method: 'assoclist',
981                         params: [ 'device' ],
982                         expect: { results: [ ] },
983                         filter: function(data, params) {
984                                 for (var i = 0; i < data.length; i++)
985                                         data[i]['device'] = params['device'];
986
987                                 data.sort(function(a, b) {
988                                         if (a.bssid < b.bssid)
989                                                 return -1;
990                                         else if (a.bssid > b.bssid)
991                                                 return 1;
992                                         else
993                                                 return 0;
994                                 });
995
996                                 return data;
997                         }
998                 }),
999
1000                 getWirelessStatus: function() {
1001                         return this.listDeviceNames().then(function(names) {
1002                                 _luci2.rpc.batch();
1003
1004                                 for (var i = 0; i < names.length; i++)
1005                                         _luci2.wireless.getDeviceStatus(names[i]);
1006
1007                                 return _luci2.rpc.flush();
1008                         }).then(function(networks) {
1009                                 var rv = { };
1010
1011                                 var phy_attrs = [
1012                                         'country', 'channel', 'frequency', 'frequency_offset',
1013                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1014                                 ];
1015
1016                                 var net_attrs = [
1017                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1018                                         'signal', 'noise', 'bitrate', 'encryption'
1019                                 ];
1020
1021                                 for (var i = 0; i < networks.length; i++)
1022                                 {
1023                                         var phy = rv[networks[i].phy] || (
1024                                                 rv[networks[i].phy] = { networks: [ ] }
1025                                         );
1026
1027                                         var net = {
1028                                                 device: networks[i].device
1029                                         };
1030
1031                                         for (var j = 0; j < phy_attrs.length; j++)
1032                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1033
1034                                         for (var j = 0; j < net_attrs.length; j++)
1035                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1036
1037                                         phy.networks.push(net);
1038                                 }
1039
1040                                 return rv;
1041                         });
1042                 },
1043
1044                 getAssocLists: function()
1045                 {
1046                         return this.listDeviceNames().then(function(names) {
1047                                 _luci2.rpc.batch();
1048
1049                                 for (var i = 0; i < names.length; i++)
1050                                         _luci2.wireless.getAssocList(names[i]);
1051
1052                                 return _luci2.rpc.flush();
1053                         }).then(function(assoclists) {
1054                                 var rv = [ ];
1055
1056                                 for (var i = 0; i < assoclists.length; i++)
1057                                         for (var j = 0; j < assoclists[i].length; j++)
1058                                                 rv.push(assoclists[i][j]);
1059
1060                                 return rv;
1061                         });
1062                 },
1063
1064                 formatEncryption: function(enc)
1065                 {
1066                         var format_list = function(l, s)
1067                         {
1068                                 var rv = [ ];
1069                                 for (var i = 0; i < l.length; i++)
1070                                         rv.push(l[i].toUpperCase());
1071                                 return rv.join(s ? s : ', ');
1072                         }
1073
1074                         if (!enc || !enc.enabled)
1075                                 return _luci2.tr('None');
1076
1077                         if (enc.wep)
1078                         {
1079                                 if (enc.wep.length == 2)
1080                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1081                                 else if (enc.wep[0] == 'shared')
1082                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1083                                 else
1084                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1085                         }
1086                         else if (enc.wpa)
1087                         {
1088                                 if (enc.wpa.length == 2)
1089                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1090                                                 format_list(enc.authentication, '/'),
1091                                                 format_list(enc.ciphers, ', ')
1092                                         );
1093                                 else if (enc.wpa[0] == 2)
1094                                         return 'WPA2 %s (%s)'.format(
1095                                                 format_list(enc.authentication, '/'),
1096                                                 format_list(enc.ciphers, ', ')
1097                                         );
1098                                 else
1099                                         return 'WPA %s (%s)'.format(
1100                                                 format_list(enc.authentication, '/'),
1101                                                 format_list(enc.ciphers, ', ')
1102                                         );
1103                         }
1104
1105                         return _luci2.tr('Unknown');
1106                 }
1107         };
1108
1109         this.system = {
1110                 getSystemInfo: _luci2.rpc.declare({
1111                         object: 'system',
1112                         method: 'info',
1113                         expect: { '': { } }
1114                 }),
1115
1116                 getBoardInfo: _luci2.rpc.declare({
1117                         object: 'system',
1118                         method: 'board',
1119                         expect: { '': { } }
1120                 }),
1121
1122                 getDiskInfo: _luci2.rpc.declare({
1123                         object: 'luci2.system',
1124                         method: 'diskfree',
1125                         expect: { '': { } }
1126                 }),
1127
1128                 getInfo: function(cb)
1129                 {
1130                         _luci2.rpc.batch();
1131
1132                         this.getSystemInfo();
1133                         this.getBoardInfo();
1134                         this.getDiskInfo();
1135
1136                         return _luci2.rpc.flush().then(function(info) {
1137                                 var rv = { };
1138
1139                                 $.extend(rv, info[0]);
1140                                 $.extend(rv, info[1]);
1141                                 $.extend(rv, info[2]);
1142
1143                                 return rv;
1144                         });
1145                 },
1146
1147                 getProcessList: _luci2.rpc.declare({
1148                         object: 'luci2.system',
1149                         method: 'process_list',
1150                         expect: { processes: [ ] },
1151                         filter: function(data) {
1152                                 data.sort(function(a, b) { return a.pid - b.pid });
1153                                 return data;
1154                         }
1155                 }),
1156
1157                 getSystemLog: _luci2.rpc.declare({
1158                         object: 'luci2.system',
1159                         method: 'syslog',
1160                         expect: { log: '' }
1161                 }),
1162
1163                 getKernelLog: _luci2.rpc.declare({
1164                         object: 'luci2.system',
1165                         method: 'dmesg',
1166                         expect: { log: '' }
1167                 }),
1168
1169                 getZoneInfo: function(cb)
1170                 {
1171                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1172                 },
1173
1174                 sendSignal: _luci2.rpc.declare({
1175                         object: 'luci2.system',
1176                         method: 'process_signal',
1177                         params: [ 'pid', 'signal' ],
1178                         filter: function(data) {
1179                                 return (data == 0);
1180                         }
1181                 }),
1182
1183                 initList: _luci2.rpc.declare({
1184                         object: 'luci2.system',
1185                         method: 'init_list',
1186                         expect: { initscripts: [ ] },
1187                         filter: function(data) {
1188                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1189                                 return data;
1190                         }
1191                 }),
1192
1193                 initEnabled: function(init, cb)
1194                 {
1195                         return this.initList().then(function(list) {
1196                                 for (var i = 0; i < list.length; i++)
1197                                         if (list[i].name == init)
1198                                                 return !!list[i].enabled;
1199
1200                                 return false;
1201                         });
1202                 },
1203
1204                 initRun: _luci2.rpc.declare({
1205                         object: 'luci2.system',
1206                         method: 'init_action',
1207                         params: [ 'name', 'action' ],
1208                         filter: function(data) {
1209                                 return (data == 0);
1210                         }
1211                 }),
1212
1213                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1214                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1215                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1216                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1217                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1218                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1219
1220
1221                 getRcLocal: _luci2.rpc.declare({
1222                         object: 'luci2.system',
1223                         method: 'rclocal_get',
1224                         expect: { data: '' }
1225                 }),
1226
1227                 setRcLocal: _luci2.rpc.declare({
1228                         object: 'luci2.system',
1229                         method: 'rclocal_set',
1230                         params: [ 'data' ]
1231                 }),
1232
1233
1234                 getCrontab: _luci2.rpc.declare({
1235                         object: 'luci2.system',
1236                         method: 'crontab_get',
1237                         expect: { data: '' }
1238                 }),
1239
1240                 setCrontab: _luci2.rpc.declare({
1241                         object: 'luci2.system',
1242                         method: 'crontab_set',
1243                         params: [ 'data' ]
1244                 }),
1245
1246
1247                 getSSHKeys: _luci2.rpc.declare({
1248                         object: 'luci2.system',
1249                         method: 'sshkeys_get',
1250                         expect: { keys: [ ] }
1251                 }),
1252
1253                 setSSHKeys: _luci2.rpc.declare({
1254                         object: 'luci2.system',
1255                         method: 'sshkeys_set',
1256                         params: [ 'keys' ]
1257                 }),
1258
1259
1260                 setPassword: _luci2.rpc.declare({
1261                         object: 'luci2.system',
1262                         method: 'password_set',
1263                         params: [ 'user', 'password' ]
1264                 }),
1265
1266
1267                 listLEDs: _luci2.rpc.declare({
1268                         object: 'luci2.system',
1269                         method: 'led_list',
1270                         expect: { leds: [ ] }
1271                 }),
1272
1273                 listUSBDevices: _luci2.rpc.declare({
1274                         object: 'luci2.system',
1275                         method: 'usb_list',
1276                         expect: { devices: [ ] }
1277                 }),
1278
1279
1280                 testUpgrade: _luci2.rpc.declare({
1281                         object: 'luci2.system',
1282                         method: 'upgrade_test',
1283                         expect: { '': { } }
1284                 }),
1285
1286                 startUpgrade: _luci2.rpc.declare({
1287                         object: 'luci2.system',
1288                         method: 'upgrade_start',
1289                         params: [ 'keep' ]
1290                 }),
1291
1292                 cleanUpgrade: _luci2.rpc.declare({
1293                         object: 'luci2.system',
1294                         method: 'upgrade_clean'
1295                 }),
1296
1297
1298                 restoreBackup: _luci2.rpc.declare({
1299                         object: 'luci2.system',
1300                         method: 'backup_restore'
1301                 }),
1302
1303                 cleanBackup: _luci2.rpc.declare({
1304                         object: 'luci2.system',
1305                         method: 'backup_clean'
1306                 }),
1307
1308
1309                 getBackupConfig: _luci2.rpc.declare({
1310                         object: 'luci2.system',
1311                         method: 'backup_config_get',
1312                         expect: { config: '' }
1313                 }),
1314
1315                 setBackupConfig: _luci2.rpc.declare({
1316                         object: 'luci2.system',
1317                         method: 'backup_config_set',
1318                         params: [ 'data' ]
1319                 }),
1320
1321
1322                 listBackup: _luci2.rpc.declare({
1323                         object: 'luci2.system',
1324                         method: 'backup_list',
1325                         expect: { files: [ ] }
1326                 }),
1327
1328
1329                 testReset: _luci2.rpc.declare({
1330                         object: 'luci2.system',
1331                         method: 'reset_test',
1332                         expect: { supported: false }
1333                 }),
1334
1335                 startReset: _luci2.rpc.declare({
1336                         object: 'luci2.system',
1337                         method: 'reset_start'
1338                 }),
1339
1340
1341                 performReboot: _luci2.rpc.declare({
1342                         object: 'luci2.system',
1343                         method: 'reboot'
1344                 })
1345         };
1346
1347         this.opkg = {
1348                 updateLists: _luci2.rpc.declare({
1349                         object: 'luci2.opkg',
1350                         method: 'update',
1351                         expect: { '': { } }
1352                 }),
1353
1354                 _allPackages: _luci2.rpc.declare({
1355                         object: 'luci2.opkg',
1356                         method: 'list',
1357                         params: [ 'offset', 'limit', 'pattern' ],
1358                         expect: { '': { } }
1359                 }),
1360
1361                 _installedPackages: _luci2.rpc.declare({
1362                         object: 'luci2.opkg',
1363                         method: 'list_installed',
1364                         params: [ 'offset', 'limit', 'pattern' ],
1365                         expect: { '': { } }
1366                 }),
1367
1368                 _findPackages: _luci2.rpc.declare({
1369                         object: 'luci2.opkg',
1370                         method: 'find',
1371                         params: [ 'offset', 'limit', 'pattern' ],
1372                         expect: { '': { } }
1373                 }),
1374
1375                 _fetchPackages: function(action, offset, limit, pattern)
1376                 {
1377                         var packages = [ ];
1378
1379                         return action(offset, limit, pattern).then(function(list) {
1380                                 if (!list.total || !list.packages)
1381                                         return { length: 0, total: 0 };
1382
1383                                 packages.push.apply(packages, list.packages);
1384                                 packages.total = list.total;
1385
1386                                 if (limit <= 0)
1387                                         limit = list.total;
1388
1389                                 if (packages.length >= limit)
1390                                         return packages;
1391
1392                                 _luci2.rpc.batch();
1393
1394                                 for (var i = offset + packages.length; i < limit; i += 100)
1395                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1396
1397                                 return _luci2.rpc.flush();
1398                         }).then(function(lists) {
1399                                 for (var i = 0; i < lists.length; i++)
1400                                 {
1401                                         if (!lists[i].total || !lists[i].packages)
1402                                                 continue;
1403
1404                                         packages.push.apply(packages, lists[i].packages);
1405                                         packages.total = lists[i].total;
1406                                 }
1407
1408                                 return packages;
1409                         });
1410                 },
1411
1412                 listPackages: function(offset, limit, pattern)
1413                 {
1414                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1415                 },
1416
1417                 installedPackages: function(offset, limit, pattern)
1418                 {
1419                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1420                 },
1421
1422                 findPackages: function(offset, limit, pattern)
1423                 {
1424                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1425                 },
1426
1427                 installPackage: _luci2.rpc.declare({
1428                         object: 'luci2.opkg',
1429                         method: 'install',
1430                         params: [ 'package' ],
1431                         expect: { '': { } }
1432                 }),
1433
1434                 removePackage: _luci2.rpc.declare({
1435                         object: 'luci2.opkg',
1436                         method: 'remove',
1437                         params: [ 'package' ],
1438                         expect: { '': { } }
1439                 }),
1440
1441                 getConfig: _luci2.rpc.declare({
1442                         object: 'luci2.opkg',
1443                         method: 'config_get',
1444                         expect: { config: '' }
1445                 }),
1446
1447                 setConfig: _luci2.rpc.declare({
1448                         object: 'luci2.opkg',
1449                         method: 'config_set',
1450                         params: [ 'data' ]
1451                 })
1452         };
1453
1454         this.session = {
1455
1456                 login: _luci2.rpc.declare({
1457                         object: 'session',
1458                         method: 'login',
1459                         params: [ 'username', 'password' ],
1460                         expect: { '': { } }
1461                 }),
1462
1463                 access: _luci2.rpc.declare({
1464                         object: 'session',
1465                         method: 'access',
1466                         params: [ 'scope', 'object', 'function' ],
1467                         expect: { access: false }
1468                 }),
1469
1470                 isAlive: function()
1471                 {
1472                         return _luci2.session.access('ubus', 'session', 'access');
1473                 },
1474
1475                 startHeartbeat: function()
1476                 {
1477                         this._hearbeatInterval = window.setInterval(function() {
1478                                 _luci2.session.isAlive().then(function(alive) {
1479                                         if (!alive)
1480                                         {
1481                                                 _luci2.session.stopHeartbeat();
1482                                                 _luci2.ui.login(true);
1483                                         }
1484
1485                                 });
1486                         }, _luci2.globals.timeout * 2);
1487                 },
1488
1489                 stopHeartbeat: function()
1490                 {
1491                         if (typeof(this._hearbeatInterval) != 'undefined')
1492                         {
1493                                 window.clearInterval(this._hearbeatInterval);
1494                                 delete this._hearbeatInterval;
1495                         }
1496                 }
1497         };
1498
1499         this.ui = {
1500
1501                 saveScrollTop: function()
1502                 {
1503                         this._scroll_top = $(document).scrollTop();
1504                 },
1505
1506                 restoreScrollTop: function()
1507                 {
1508                         if (typeof(this._scroll_top) == 'undefined')
1509                                 return;
1510
1511                         $(document).scrollTop(this._scroll_top);
1512
1513                         delete this._scroll_top;
1514                 },
1515
1516                 loading: function(enable)
1517                 {
1518                         var win = $(window);
1519                         var body = $('body');
1520
1521                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1522                                 modal: $('<div />')
1523                                         .addClass('cbi-modal-loader')
1524                                         .append($('<div />').text(_luci2.tr('Loading data...')))
1525                                         .appendTo(body)
1526                         });
1527
1528                         if (enable)
1529                         {
1530                                 body.css('overflow', 'hidden');
1531                                 body.css('padding', 0);
1532                                 body.css('width', win.width());
1533                                 body.css('height', win.height());
1534                                 state.modal.css('width', win.width());
1535                                 state.modal.css('height', win.height());
1536                                 state.modal.show();
1537                         }
1538                         else
1539                         {
1540                                 state.modal.hide();
1541                                 body.css('overflow', '');
1542                                 body.css('padding', '');
1543                                 body.css('width', '');
1544                                 body.css('height', '');
1545                         }
1546                 },
1547
1548                 dialog: function(title, content, options)
1549                 {
1550                         var win = $(window);
1551                         var body = $('body');
1552
1553                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1554                                 dialog: $('<div />')
1555                                         .addClass('cbi-modal-dialog')
1556                                         .append($('<div />')
1557                                                 .append($('<div />')
1558                                                         .addClass('cbi-modal-dialog-header'))
1559                                                 .append($('<div />')
1560                                                         .addClass('cbi-modal-dialog-body'))
1561                                                 .append($('<div />')
1562                                                         .addClass('cbi-modal-dialog-footer')
1563                                                         .append($('<button />')
1564                                                                 .addClass('cbi-button')
1565                                                                 .text(_luci2.tr('Close'))
1566                                                                 .click(function() {
1567                                                                         $('body')
1568                                                                                 .css('overflow', '')
1569                                                                                 .css('padding', '')
1570                                                                                 .css('width', '')
1571                                                                                 .css('height', '');
1572
1573                                                                         $(this).parent().parent().parent().hide();
1574                                                                 }))))
1575                                         .appendTo(body)
1576                         });
1577
1578                         if (typeof(options) != 'object')
1579                                 options = { };
1580
1581                         if (title === false)
1582                         {
1583                                 body
1584                                         .css('overflow', '')
1585                                         .css('padding', '')
1586                                         .css('width', '')
1587                                         .css('height', '');
1588
1589                                 state.dialog.hide();
1590
1591                                 return;
1592                         }
1593
1594                         var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1595                         var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1596
1597                         ftr.empty();
1598
1599                         if (options.style == 'confirm')
1600                         {
1601                                 ftr.append($('<button />')
1602                                         .addClass('cbi-button')
1603                                         .text(_luci2.tr('Ok'))
1604                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1605
1606                                 ftr.append($('<button />')
1607                                         .addClass('cbi-button')
1608                                         .text(_luci2.tr('Cancel'))
1609                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1610                         }
1611                         else if (options.style == 'close')
1612                         {
1613                                 ftr.append($('<button />')
1614                                         .addClass('cbi-button')
1615                                         .text(_luci2.tr('Close'))
1616                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1617                         }
1618                         else if (options.style == 'wait')
1619                         {
1620                                 ftr.append($('<button />')
1621                                         .addClass('cbi-button')
1622                                         .text(_luci2.tr('Close'))
1623                                         .attr('disabled', true));
1624                         }
1625
1626                         state.dialog.find('div.cbi-modal-dialog-header').text(title);
1627                         state.dialog.show();
1628
1629                         cnt
1630                                 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1631                                 .empty()
1632                                 .append(content);
1633
1634                         state.dialog.children()
1635                                 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1636
1637                         body.css('overflow', 'hidden');
1638                         body.css('padding', 0);
1639                         body.css('width', win.width());
1640                         body.css('height', win.height());
1641                         state.dialog.css('width', win.width());
1642                         state.dialog.css('height', win.height());
1643                 },
1644
1645                 upload: function(title, content, options)
1646                 {
1647                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1648                                 form: $('<form />')
1649                                         .attr('method', 'post')
1650                                         .attr('action', '/cgi-bin/luci-upload')
1651                                         .attr('enctype', 'multipart/form-data')
1652                                         .attr('target', 'cbi-fileupload-frame')
1653                                         .append($('<p />'))
1654                                         .append($('<input />')
1655                                                 .attr('type', 'hidden')
1656                                                 .attr('name', 'sessionid'))
1657                                         .append($('<input />')
1658                                                 .attr('type', 'hidden')
1659                                                 .attr('name', 'filename'))
1660                                         .append($('<input />')
1661                                                 .attr('type', 'file')
1662                                                 .attr('name', 'filedata')
1663                                                 .addClass('cbi-input-file'))
1664                                         .append($('<div />')
1665                                                 .css('width', '100%')
1666                                                 .addClass('progressbar')
1667                                                 .addClass('intermediate')
1668                                                 .append($('<div />')
1669                                                         .css('width', '100%')))
1670                                         .append($('<iframe />')
1671                                                 .attr('name', 'cbi-fileupload-frame')
1672                                                 .css('width', '1px')
1673                                                 .css('height', '1px')
1674                                                 .css('visibility', 'hidden')),
1675
1676                                 finish_cb: function(ev) {
1677                                         $(this).off('load');
1678
1679                                         var body = (this.contentDocument || this.contentWindow.document).body;
1680                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1681                                                 body = body.firstChild;
1682
1683                                         var json;
1684                                         try {
1685                                                 json = $.parseJSON(body.innerHTML);
1686                                         } catch(e) {
1687                                                 json = {
1688                                                         message: _luci2.tr('Invalid server response received'),
1689                                                         error: [ -1, _luci2.tr('Invalid data') ]
1690                                                 };
1691                                         };
1692
1693                                         if (json.error)
1694                                         {
1695                                                 L.ui.dialog(L.tr('File upload'), [
1696                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1697                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1698                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1699                                                 ], { style: 'close' });
1700                                         }
1701                                         else if (typeof(state.success_cb) == 'function')
1702                                         {
1703                                                 state.success_cb(json);
1704                                         }
1705                                 },
1706
1707                                 confirm_cb: function() {
1708                                         var f = state.form.find('.cbi-input-file');
1709                                         var b = state.form.find('.progressbar');
1710                                         var p = state.form.find('p');
1711
1712                                         if (!f.val())
1713                                                 return;
1714
1715                                         state.form.find('iframe').on('load', state.finish_cb);
1716                                         state.form.submit();
1717
1718                                         f.hide();
1719                                         b.show();
1720                                         p.text(_luci2.tr('File upload in progress â€¦'));
1721
1722                                         state.form.parent().parent().find('button').prop('disabled', true);
1723                                 }
1724                         });
1725
1726                         state.form.find('.progressbar').hide();
1727                         state.form.find('.cbi-input-file').val('').show();
1728                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1729
1730                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1731                         state.form.find('[name=filename]').val(options.filename);
1732
1733                         state.success_cb = options.success;
1734
1735                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1736                                 style: 'confirm',
1737                                 confirm: state.confirm_cb
1738                         });
1739                 },
1740
1741                 reconnect: function()
1742                 {
1743                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1744                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1745                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1746                         var images    = $();
1747                         var interval, timeout;
1748
1749                         _luci2.ui.dialog(
1750                                 _luci2.tr('Waiting for device'), [
1751                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring â€¦')),
1752                                         $('<div />')
1753                                                 .css('width', '100%')
1754                                                 .addClass('progressbar')
1755                                                 .addClass('intermediate')
1756                                                 .append($('<div />')
1757                                                         .css('width', '100%'))
1758                                 ], { style: 'wait' }
1759                         );
1760
1761                         for (var i = 0; i < protocols.length; i++)
1762                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1763
1764                         //_luci2.network.getNetworkStatus(function(s) {
1765                         //      for (var i = 0; i < protocols.length; i++)
1766                         //      {
1767                         //              for (var j = 0; j < s.length; j++)
1768                         //              {
1769                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1770                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1771                         //
1772                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1773                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1774                         //              }
1775                         //      }
1776                         //}).then(function() {
1777                                 images.on('load', function() {
1778                                         var url = this.getAttribute('url');
1779                                         _luci2.session.isAlive().then(function(access) {
1780                                                 if (access)
1781                                                 {
1782                                                         window.clearTimeout(timeout);
1783                                                         window.clearInterval(interval);
1784                                                         _luci2.ui.dialog(false);
1785                                                         images = null;
1786                                                 }
1787                                                 else
1788                                                 {
1789                                                         location.href = url;
1790                                                 }
1791                                         });
1792                                 });
1793
1794                                 interval = window.setInterval(function() {
1795                                         images.each(function() {
1796                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1797                                         });
1798                                 }, 5000);
1799
1800                                 timeout = window.setTimeout(function() {
1801                                         window.clearInterval(interval);
1802                                         images.off('load');
1803
1804                                         _luci2.ui.dialog(
1805                                                 _luci2.tr('Device not responding'),
1806                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1807                                                 { style: 'close' }
1808                                         );
1809                                 }, 180000);
1810                         //});
1811                 },
1812
1813                 login: function(invalid)
1814                 {
1815                         var state = _luci2.ui._login || (_luci2.ui._login = {
1816                                 form: $('<form />')
1817                                         .attr('target', '')
1818                                         .attr('method', 'post')
1819                                         .append($('<p />')
1820                                                 .addClass('alert-message')
1821                                                 .text(_luci2.tr('Wrong username or password given!')))
1822                                         .append($('<p />')
1823                                                 .append($('<label />')
1824                                                         .text(_luci2.tr('Username'))
1825                                                         .append($('<br />'))
1826                                                         .append($('<input />')
1827                                                                 .attr('type', 'text')
1828                                                                 .attr('name', 'username')
1829                                                                 .attr('value', 'root')
1830                                                                 .addClass('cbi-input-text')
1831                                                                 .keypress(function(ev) {
1832                                                                         if (ev.which == 10 || ev.which == 13)
1833                                                                                 state.confirm_cb();
1834                                                                 }))))
1835                                         .append($('<p />')
1836                                                 .append($('<label />')
1837                                                         .text(_luci2.tr('Password'))
1838                                                         .append($('<br />'))
1839                                                         .append($('<input />')
1840                                                                 .attr('type', 'password')
1841                                                                 .attr('name', 'password')
1842                                                                 .addClass('cbi-input-password')
1843                                                                 .keypress(function(ev) {
1844                                                                         if (ev.which == 10 || ev.which == 13)
1845                                                                                 state.confirm_cb();
1846                                                                 }))))
1847                                         .append($('<p />')
1848                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1849
1850                                 response_cb: function(response) {
1851                                         if (!response.ubus_rpc_session)
1852                                         {
1853                                                 _luci2.ui.login(true);
1854                                         }
1855                                         else
1856                                         {
1857                                                 _luci2.globals.sid = response.ubus_rpc_session;
1858                                                 _luci2.setHash('id', _luci2.globals.sid);
1859                                                 _luci2.session.startHeartbeat();
1860                                                 _luci2.ui.dialog(false);
1861                                                 state.deferred.resolve();
1862                                         }
1863                                 },
1864
1865                                 confirm_cb: function() {
1866                                         var u = state.form.find('[name=username]').val();
1867                                         var p = state.form.find('[name=password]').val();
1868
1869                                         if (!u)
1870                                                 return;
1871
1872                                         _luci2.ui.dialog(
1873                                                 _luci2.tr('Logging in'), [
1874                                                         $('<p />').text(_luci2.tr('Log in in progress â€¦')),
1875                                                         $('<div />')
1876                                                                 .css('width', '100%')
1877                                                                 .addClass('progressbar')
1878                                                                 .addClass('intermediate')
1879                                                                 .append($('<div />')
1880                                                                         .css('width', '100%'))
1881                                                 ], { style: 'wait' }
1882                                         );
1883
1884                                         _luci2.globals.sid = '00000000000000000000000000000000';
1885                                         _luci2.session.login(u, p).then(state.response_cb);
1886                                 }
1887                         });
1888
1889                         if (!state.deferred || state.deferred.state() != 'pending')
1890                                 state.deferred = $.Deferred();
1891
1892                         /* try to find sid from hash */
1893                         var sid = _luci2.getHash('id');
1894                         if (sid && sid.match(/^[a-f0-9]{32}$/))
1895                         {
1896                                 _luci2.globals.sid = sid;
1897                                 _luci2.session.isAlive().then(function(access) {
1898                                         if (access)
1899                                         {
1900                                                 _luci2.session.startHeartbeat();
1901                                                 state.deferred.resolve();
1902                                         }
1903                                         else
1904                                         {
1905                                                 _luci2.setHash('id', undefined);
1906                                                 _luci2.ui.login();
1907                                         }
1908                                 });
1909
1910                                 return state.deferred;
1911                         }
1912
1913                         if (invalid)
1914                                 state.form.find('.alert-message').show();
1915                         else
1916                                 state.form.find('.alert-message').hide();
1917
1918                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1919                                 style: 'confirm',
1920                                 confirm: state.confirm_cb
1921                         });
1922
1923                         state.form.find('[name=password]').focus();
1924
1925                         return state.deferred;
1926                 },
1927
1928                 cryptPassword: _luci2.rpc.declare({
1929                         object: 'luci2.ui',
1930                         method: 'crypt',
1931                         params: [ 'data' ],
1932                         expect: { crypt: '' }
1933                 }),
1934
1935
1936                 _acl_merge_scope: function(acl_scope, scope)
1937                 {
1938                         if ($.isArray(scope))
1939                         {
1940                                 for (var i = 0; i < scope.length; i++)
1941                                         acl_scope[scope[i]] = true;
1942                         }
1943                         else if ($.isPlainObject(scope))
1944                         {
1945                                 for (var object_name in scope)
1946                                 {
1947                                         if (!$.isArray(scope[object_name]))
1948                                                 continue;
1949
1950                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
1951
1952                                         for (var i = 0; i < scope[object_name].length; i++)
1953                                                 acl_object[scope[object_name][i]] = true;
1954                                 }
1955                         }
1956                 },
1957
1958                 _acl_merge_permission: function(acl_perm, perm)
1959                 {
1960                         if ($.isPlainObject(perm))
1961                         {
1962                                 for (var scope_name in perm)
1963                                 {
1964                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
1965                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
1966                                 }
1967                         }
1968                 },
1969
1970                 _acl_merge_group: function(acl_group, group)
1971                 {
1972                         if ($.isPlainObject(group))
1973                         {
1974                                 if (!acl_group.description)
1975                                         acl_group.description = group.description;
1976
1977                                 if (group.read)
1978                                 {
1979                                         var acl_perm = acl_group.read || (acl_group.read = { });
1980                                         this._acl_merge_permission(acl_perm, group.read);
1981                                 }
1982
1983                                 if (group.write)
1984                                 {
1985                                         var acl_perm = acl_group.write || (acl_group.write = { });
1986                                         this._acl_merge_permission(acl_perm, group.write);
1987                                 }
1988                         }
1989                 },
1990
1991                 _acl_merge_tree: function(acl_tree, tree)
1992                 {
1993                         if ($.isPlainObject(tree))
1994                         {
1995                                 for (var group_name in tree)
1996                                 {
1997                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
1998                                         this._acl_merge_group(acl_group, tree[group_name]);
1999                                 }
2000                         }
2001                 },
2002
2003                 listAvailableACLs: _luci2.rpc.declare({
2004                         object: 'luci2.ui',
2005                         method: 'acls',
2006                         expect: { acls: [ ] },
2007                         filter: function(trees) {
2008                                 var acl_tree = { };
2009                                 for (var i = 0; i < trees.length; i++)
2010                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2011                                 return acl_tree;
2012                         }
2013                 }),
2014
2015                 renderMainMenu: _luci2.rpc.declare({
2016                         object: 'luci2.ui',
2017                         method: 'menu',
2018                         expect: { menu: { } },
2019                         filter: function(entries) {
2020                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2021                                 _luci2.globals.mainMenu.entries(entries);
2022
2023                                 $('#mainmenu')
2024                                         .empty()
2025                                         .append(_luci2.globals.mainMenu.render(0, 1));
2026                         }
2027                 }),
2028
2029                 renderViewMenu: function()
2030                 {
2031                         $('#viewmenu')
2032                                 .empty()
2033                                 .append(_luci2.globals.mainMenu.render(2, 900));
2034                 },
2035
2036                 renderView: function(node)
2037                 {
2038                         var name = node.view.split(/\//).join('.');
2039
2040                         _luci2.ui.renderViewMenu();
2041
2042                         if (!_luci2._views)
2043                                 _luci2._views = { };
2044
2045                         _luci2.setHash('view', node.view);
2046
2047                         if (_luci2._views[name] instanceof _luci2.ui.view)
2048                                 return _luci2._views[name].render();
2049
2050                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2051
2052                         return $.ajax(url, {
2053                                 method: 'GET',
2054                                 cache: true,
2055                                 dataType: 'text'
2056                         }).then(function(data) {
2057                                 try {
2058                                         var viewConstructorSource = (
2059                                                 '(function(L, $) { ' +
2060                                                         'return %s' +
2061                                                 '})(_luci2, $);\n\n' +
2062                                                 '//@ sourceURL=%s'
2063                                         ).format(data, url);
2064
2065                                         var viewConstructor = eval(viewConstructorSource);
2066
2067                                         _luci2._views[name] = new viewConstructor({
2068                                                 name: name,
2069                                                 acls: node.write || { }
2070                                         });
2071
2072                                         return _luci2._views[name].render();
2073                                 }
2074                                 catch(e) {
2075                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2076                                 };
2077
2078                                 return $.Deferred().resolve();
2079                         });
2080                 },
2081
2082                 updateHostname: function()
2083                 {
2084                         return _luci2.system.getBoardInfo().then(function(info) {
2085                                 if (info.hostname)
2086                                         $('#hostname').text(info.hostname);
2087                         });
2088                 },
2089
2090                 updateChanges: function()
2091                 {
2092                         return _luci2.uci.changes().then(function(changes) {
2093                                 var n = 0;
2094                                 var html = '';
2095
2096                                 for (var config in changes)
2097                                 {
2098                                         var log = [ ];
2099
2100                                         for (var i = 0; i < changes[config].length; i++)
2101                                         {
2102                                                 var c = changes[config][i];
2103
2104                                                 switch (c[0])
2105                                                 {
2106                                                 case 'order':
2107                                                         break;
2108
2109                                                 case 'remove':
2110                                                         if (c.length < 3)
2111                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2112                                                         else
2113                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2114                                                         break;
2115
2116                                                 case 'rename':
2117                                                         if (c.length < 4)
2118                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2119                                                         else
2120                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2121                                                         break;
2122
2123                                                 case 'add':
2124                                                         log.push('uci add %s (= <ins><strong>%s</strong></ins>)'.format(config, c[1]));
2125                                                         break;
2126
2127                                                 case 'list-add':
2128                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2129                                                         break;
2130
2131                                                 case 'list-del':
2132                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2133                                                         break;
2134
2135                                                 case 'set':
2136                                                         if (c.length < 4)
2137                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2138                                                         else
2139                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2140                                                         break;
2141                                                 }
2142                                         }
2143
2144                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2145                                         n += changes[config].length;
2146                                 }
2147
2148                                 if (n > 0)
2149                                         $('#changes')
2150                                                 .empty()
2151                                                 .show()
2152                                                 .append($('<a />')
2153                                                         .attr('href', '#')
2154                                                         .addClass('label')
2155                                                         .addClass('notice')
2156                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2157                                                         .click(function(ev) {
2158                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2159                                                                 ev.preventDefault();
2160                                                         }));
2161                                 else
2162                                         $('#changes')
2163                                                 .hide();
2164                         });
2165                 },
2166
2167                 init: function()
2168                 {
2169                         _luci2.ui.loading(true);
2170
2171                         $.when(
2172                                 _luci2.ui.updateHostname(),
2173                                 _luci2.ui.updateChanges(),
2174                                 _luci2.ui.renderMainMenu()
2175                         ).then(function() {
2176                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2177                                         _luci2.ui.loading(false);
2178                                 })
2179                         });
2180                 }
2181         };
2182
2183         var AbstractWidget = Class.extend({
2184                 i18n: function(text) {
2185                         return text;
2186                 },
2187
2188                 toString: function() {
2189                         var x = document.createElement('div');
2190                                 x.appendChild(this.render());
2191
2192                         return x.innerHTML;
2193                 },
2194
2195                 insertInto: function(id) {
2196                         return $(id).empty().append(this.render());
2197                 }
2198         });
2199
2200         this.ui.view = AbstractWidget.extend({
2201                 _fetch_template: function()
2202                 {
2203                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2204                                 method: 'GET',
2205                                 cache: true,
2206                                 dataType: 'text',
2207                                 success: function(data) {
2208                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2209                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2210                                                 switch (p1)
2211                                                 {
2212                                                 case '#':
2213                                                         return '';
2214
2215                                                 case ':':
2216                                                         return _luci2.tr(p2);
2217
2218                                                 case '=':
2219                                                         return _luci2.globals[p2] || '';
2220
2221                                                 default:
2222                                                         return '(?' + match + ')';
2223                                                 }
2224                                         });
2225
2226                                         $('#maincontent').append(data);
2227                                 }
2228                         });
2229                 },
2230
2231                 execute: function()
2232                 {
2233                         throw "Not implemented";
2234                 },
2235
2236                 render: function()
2237                 {
2238                         var container = $('#maincontent');
2239
2240                         container.empty();
2241
2242                         if (this.title)
2243                                 container.append($('<h2 />').append(this.title));
2244
2245                         if (this.description)
2246                                 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2247
2248                         var self = this;
2249                         return this._fetch_template().then(function() {
2250                                 return _luci2.deferrable(self.execute());
2251                         });
2252                 }
2253         });
2254
2255         this.ui.menu = AbstractWidget.extend({
2256                 init: function() {
2257                         this._nodes = { };
2258                 },
2259
2260                 entries: function(entries)
2261                 {
2262                         for (var entry in entries)
2263                         {
2264                                 var path = entry.split(/\//);
2265                                 var node = this._nodes;
2266
2267                                 for (i = 0; i < path.length; i++)
2268                                 {
2269                                         if (!node.childs)
2270                                                 node.childs = { };
2271
2272                                         if (!node.childs[path[i]])
2273                                                 node.childs[path[i]] = { };
2274
2275                                         node = node.childs[path[i]];
2276                                 }
2277
2278                                 $.extend(node, entries[entry]);
2279                         }
2280                 },
2281
2282                 _indexcmp: function(a, b)
2283                 {
2284                         var x = a.index || 0;
2285                         var y = b.index || 0;
2286                         return (x - y);
2287                 },
2288
2289                 firstChildView: function(node)
2290                 {
2291                         if (node.view)
2292                                 return node;
2293
2294                         var nodes = [ ];
2295                         for (var child in (node.childs || { }))
2296                                 nodes.push(node.childs[child]);
2297
2298                         nodes.sort(this._indexcmp);
2299
2300                         for (var i = 0; i < nodes.length; i++)
2301                         {
2302                                 var child = this.firstChildView(nodes[i]);
2303                                 if (child)
2304                                 {
2305                                         $.extend(node, child);
2306                                         return node;
2307                                 }
2308                         }
2309
2310                         return undefined;
2311                 },
2312
2313                 _onclick: function(ev)
2314                 {
2315                         _luci2.ui.loading(true);
2316                         _luci2.ui.renderView(ev.data).then(function() {
2317                                 _luci2.ui.loading(false);
2318                         });
2319
2320                         ev.preventDefault();
2321                         this.blur();
2322                 },
2323
2324                 _render: function(childs, level, min, max)
2325                 {
2326                         var nodes = [ ];
2327                         for (var node in childs)
2328                         {
2329                                 var child = this.firstChildView(childs[node]);
2330                                 if (child)
2331                                         nodes.push(childs[node]);
2332                         }
2333
2334                         nodes.sort(this._indexcmp);
2335
2336                         var list = $('<ul />');
2337
2338                         if (level == 0)
2339                                 list.addClass('nav');
2340                         else if (level == 1)
2341                                 list.addClass('dropdown-menu');
2342
2343                         for (var i = 0; i < nodes.length; i++)
2344                         {
2345                                 if (!_luci2.globals.defaultNode)
2346                                 {
2347                                         var v = _luci2.getHash('view');
2348                                         if (!v || v == nodes[i].view)
2349                                                 _luci2.globals.defaultNode = nodes[i];
2350                                 }
2351
2352                                 var item = $('<li />')
2353                                         .append($('<a />')
2354                                                 .attr('href', '#')
2355                                                 .text(_luci2.tr(nodes[i].title))
2356                                                 .click(nodes[i], this._onclick))
2357                                         .appendTo(list);
2358
2359                                 if (nodes[i].childs && level < max)
2360                                 {
2361                                         item.addClass('dropdown');
2362                                         item.find('a').addClass('menu');
2363                                         item.append(this._render(nodes[i].childs, level + 1));
2364                                 }
2365                         }
2366
2367                         return list.get(0);
2368                 },
2369
2370                 render: function(min, max)
2371                 {
2372                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2373                         return this._render(top.childs, 0, min, max);
2374                 },
2375
2376                 getNode: function(path, max)
2377                 {
2378                         var p = path.split(/\//);
2379                         var n = this._nodes;
2380
2381                         if (typeof(max) == 'undefined')
2382                                 max = p.length;
2383
2384                         for (var i = 0; i < max; i++)
2385                         {
2386                                 if (!n.childs[p[i]])
2387                                         return undefined;
2388
2389                                 n = n.childs[p[i]];
2390                         }
2391
2392                         return n;
2393                 }
2394         });
2395
2396         this.ui.table = AbstractWidget.extend({
2397                 init: function()
2398                 {
2399                         this._rows = [ ];
2400                 },
2401
2402                 row: function(values)
2403                 {
2404                         if ($.isArray(values))
2405                         {
2406                                 this._rows.push(values);
2407                         }
2408                         else if ($.isPlainObject(values))
2409                         {
2410                                 var v = [ ];
2411                                 for (var i = 0; i < this.options.columns.length; i++)
2412                                 {
2413                                         var col = this.options.columns[i];
2414
2415                                         if (typeof col.key == 'string')
2416                                                 v.push(values[col.key]);
2417                                         else
2418                                                 v.push(null);
2419                                 }
2420                                 this._rows.push(v);
2421                         }
2422                 },
2423
2424                 rows: function(rows)
2425                 {
2426                         for (var i = 0; i < rows.length; i++)
2427                                 this.row(rows[i]);
2428                 },
2429
2430                 render: function(id)
2431                 {
2432                         var fieldset = document.createElement('fieldset');
2433                                 fieldset.className = 'cbi-section';
2434
2435                         if (this.options.caption)
2436                         {
2437                                 var legend = document.createElement('legend');
2438                                 $(legend).append(this.options.caption);
2439                                 fieldset.appendChild(legend);
2440                         }
2441
2442                         var table = document.createElement('table');
2443                                 table.className = 'cbi-section-table';
2444
2445                         var has_caption = false;
2446                         var has_description = false;
2447
2448                         for (var i = 0; i < this.options.columns.length; i++)
2449                                 if (this.options.columns[i].caption)
2450                                 {
2451                                         has_caption = true;
2452                                         break;
2453                                 }
2454                                 else if (this.options.columns[i].description)
2455                                 {
2456                                         has_description = true;
2457                                         break;
2458                                 }
2459
2460                         if (has_caption)
2461                         {
2462                                 var tr = table.insertRow(-1);
2463                                         tr.className = 'cbi-section-table-titles';
2464
2465                                 for (var i = 0; i < this.options.columns.length; i++)
2466                                 {
2467                                         var col = this.options.columns[i];
2468                                         var th = document.createElement('th');
2469                                                 th.className = 'cbi-section-table-cell';
2470
2471                                         tr.appendChild(th);
2472
2473                                         if (col.width)
2474                                                 th.style.width = col.width;
2475
2476                                         if (col.align)
2477                                                 th.style.textAlign = col.align;
2478
2479                                         if (col.caption)
2480                                                 $(th).append(col.caption);
2481                                 }
2482                         }
2483
2484                         if (has_description)
2485                         {
2486                                 var tr = table.insertRow(-1);
2487                                         tr.className = 'cbi-section-table-descr';
2488
2489                                 for (var i = 0; i < this.options.columns.length; i++)
2490                                 {
2491                                         var col = this.options.columns[i];
2492                                         var th = document.createElement('th');
2493                                                 th.className = 'cbi-section-table-cell';
2494
2495                                         tr.appendChild(th);
2496
2497                                         if (col.width)
2498                                                 th.style.width = col.width;
2499
2500                                         if (col.align)
2501                                                 th.style.textAlign = col.align;
2502
2503                                         if (col.description)
2504                                                 $(th).append(col.description);
2505                                 }
2506                         }
2507
2508                         if (this._rows.length == 0)
2509                         {
2510                                 if (this.options.placeholder)
2511                                 {
2512                                         var tr = table.insertRow(-1);
2513                                         var td = tr.insertCell(-1);
2514                                                 td.className = 'cbi-section-table-cell';
2515
2516                                         td.colSpan = this.options.columns.length;
2517                                         $(td).append(this.options.placeholder);
2518                                 }
2519                         }
2520                         else
2521                         {
2522                                 for (var i = 0; i < this._rows.length; i++)
2523                                 {
2524                                         var tr = table.insertRow(-1);
2525
2526                                         for (var j = 0; j < this.options.columns.length; j++)
2527                                         {
2528                                                 var col = this.options.columns[j];
2529                                                 var td = tr.insertCell(-1);
2530
2531                                                 var val = this._rows[i][j];
2532
2533                                                 if (typeof(val) == 'undefined')
2534                                                         val = col.placeholder;
2535
2536                                                 if (typeof(val) == 'undefined')
2537                                                         val = '';
2538
2539                                                 if (col.width)
2540                                                         td.style.width = col.width;
2541
2542                                                 if (col.align)
2543                                                         td.style.textAlign = col.align;
2544
2545                                                 if (typeof col.format == 'string')
2546                                                         $(td).append(col.format.format(val));
2547                                                 else if (typeof col.format == 'function')
2548                                                         $(td).append(col.format(val, i));
2549                                                 else
2550                                                         $(td).append(val);
2551                                         }
2552                                 }
2553                         }
2554
2555                         this._rows = [ ];
2556                         fieldset.appendChild(table);
2557
2558                         return fieldset;
2559                 }
2560         });
2561
2562         this.ui.progress = AbstractWidget.extend({
2563                 render: function()
2564                 {
2565                         var vn = parseInt(this.options.value) || 0;
2566                         var mn = parseInt(this.options.max) || 100;
2567                         var pc = Math.floor((100 / mn) * vn);
2568
2569                         var bar = document.createElement('div');
2570                                 bar.className = 'progressbar';
2571
2572                         bar.appendChild(document.createElement('div'));
2573                         bar.lastChild.appendChild(document.createElement('div'));
2574                         bar.lastChild.style.width = pc + '%';
2575
2576                         if (typeof(this.options.format) == 'string')
2577                                 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2578                         else if (typeof(this.options.format) == 'function')
2579                                 $(bar.lastChild.lastChild).append(this.options.format(pc));
2580                         else
2581                                 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2582
2583                         return bar;
2584                 }
2585         });
2586
2587         this.ui.devicebadge = AbstractWidget.extend({
2588                 render: function()
2589                 {
2590                         var dev = this.options.l3_device || this.options.device || '?';
2591
2592                         var span = document.createElement('span');
2593                                 span.className = 'ifacebadge';
2594
2595                         if (typeof(this.options.signal) == 'number' ||
2596                                 typeof(this.options.noise) == 'number')
2597                         {
2598                                 var r = 'none';
2599                                 if (typeof(this.options.signal) != 'undefined' &&
2600                                         typeof(this.options.noise) != 'undefined')
2601                                 {
2602                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2603                                         if (q < 1)
2604                                                 r = '0';
2605                                         else if (q < 2)
2606                                                 r = '0-25';
2607                                         else if (q < 3)
2608                                                 r = '25-50';
2609                                         else if (q < 4)
2610                                                 r = '50-75';
2611                                         else
2612                                                 r = '75-100';
2613                                 }
2614
2615                                 span.appendChild(document.createElement('img'));
2616                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2617
2618                                 if (r == 'none')
2619                                         span.title = _luci2.tr('No signal');
2620                                 else
2621                                         span.title = '%s: %d %s / %s: %d %s'.format(
2622                                                 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2623                                                 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2624                                         );
2625                         }
2626                         else
2627                         {
2628                                 var type = 'ethernet';
2629                                 var desc = _luci2.tr('Ethernet device');
2630
2631                                 if (this.options.l3_device != this.options.device)
2632                                 {
2633                                         type = 'tunnel';
2634                                         desc = _luci2.tr('Tunnel interface');
2635                                 }
2636                                 else if (dev.indexOf('br-') == 0)
2637                                 {
2638                                         type = 'bridge';
2639                                         desc = _luci2.tr('Bridge');
2640                                 }
2641                                 else if (dev.indexOf('.') > 0)
2642                                 {
2643                                         type = 'vlan';
2644                                         desc = _luci2.tr('VLAN interface');
2645                                 }
2646                                 else if (dev.indexOf('wlan') == 0 ||
2647                                                  dev.indexOf('ath') == 0 ||
2648                                                  dev.indexOf('wl') == 0)
2649                                 {
2650                                         type = 'wifi';
2651                                         desc = _luci2.tr('Wireless Network');
2652                                 }
2653
2654                                 span.appendChild(document.createElement('img'));
2655                                 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2656                                 span.title = desc;
2657                         }
2658
2659                         $(span).append(' ');
2660                         $(span).append(dev);
2661
2662                         return span;
2663                 }
2664         });
2665
2666         var type = function(f, l)
2667         {
2668                 f.message = l;
2669                 return f;
2670         };
2671
2672         this.cbi = {
2673                 validation: {
2674                         i18n: function(msg)
2675                         {
2676                                 _luci2.cbi.validation.message = _luci2.tr(msg);
2677                         },
2678
2679                         compile: function(code)
2680                         {
2681                                 var pos = 0;
2682                                 var esc = false;
2683                                 var depth = 0;
2684                                 var types = _luci2.cbi.validation.types;
2685                                 var stack = [ ];
2686
2687                                 code += ',';
2688
2689                                 for (var i = 0; i < code.length; i++)
2690                                 {
2691                                         if (esc)
2692                                         {
2693                                                 esc = false;
2694                                                 continue;
2695                                         }
2696
2697                                         switch (code.charCodeAt(i))
2698                                         {
2699                                         case 92:
2700                                                 esc = true;
2701                                                 break;
2702
2703                                         case 40:
2704                                         case 44:
2705                                                 if (depth <= 0)
2706                                                 {
2707                                                         if (pos < i)
2708                                                         {
2709                                                                 var label = code.substring(pos, i);
2710                                                                         label = label.replace(/\\(.)/g, '$1');
2711                                                                         label = label.replace(/^[ \t]+/g, '');
2712                                                                         label = label.replace(/[ \t]+$/g, '');
2713
2714                                                                 if (label && !isNaN(label))
2715                                                                 {
2716                                                                         stack.push(parseFloat(label));
2717                                                                 }
2718                                                                 else if (label.match(/^(['"]).*\1$/))
2719                                                                 {
2720                                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2721                                                                 }
2722                                                                 else if (typeof types[label] == 'function')
2723                                                                 {
2724                                                                         stack.push(types[label]);
2725                                                                         stack.push(null);
2726                                                                 }
2727                                                                 else
2728                                                                 {
2729                                                                         throw "Syntax error, unhandled token '"+label+"'";
2730                                                                 }
2731                                                         }
2732                                                         pos = i+1;
2733                                                 }
2734                                                 depth += (code.charCodeAt(i) == 40);
2735                                                 break;
2736
2737                                         case 41:
2738                                                 if (--depth <= 0)
2739                                                 {
2740                                                         if (typeof stack[stack.length-2] != 'function')
2741                                                                 throw "Syntax error, argument list follows non-function";
2742
2743                                                         stack[stack.length-1] =
2744                                                                 arguments.callee(code.substring(pos, i));
2745
2746                                                         pos = i+1;
2747                                                 }
2748                                                 break;
2749                                         }
2750                                 }
2751
2752                                 return stack;
2753                         }
2754                 }
2755         };
2756
2757         var validation = this.cbi.validation;
2758
2759         validation.types = {
2760                 'integer': function()
2761                 {
2762                         if (this.match(/^-?[0-9]+$/) != null)
2763                                 return true;
2764
2765                         validation.i18n('Must be a valid integer');
2766                         return false;
2767                 },
2768
2769                 'uinteger': function()
2770                 {
2771                         if (validation.types['integer'].apply(this) && (this >= 0))
2772                                 return true;
2773
2774                         validation.i18n('Must be a positive integer');
2775                         return false;
2776                 },
2777
2778                 'float': function()
2779                 {
2780                         if (!isNaN(parseFloat(this)))
2781                                 return true;
2782
2783                         validation.i18n('Must be a valid number');
2784                         return false;
2785                 },
2786
2787                 'ufloat': function()
2788                 {
2789                         if (validation.types['float'].apply(this) && (this >= 0))
2790                                 return true;
2791
2792                         validation.i18n('Must be a positive number');
2793                         return false;
2794                 },
2795
2796                 'ipaddr': function()
2797                 {
2798                         if (validation.types['ip4addr'].apply(this) ||
2799                                 validation.types['ip6addr'].apply(this))
2800                                 return true;
2801
2802                         validation.i18n('Must be a valid IP address');
2803                         return false;
2804                 },
2805
2806                 'ip4addr': function()
2807                 {
2808                         if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2809                         {
2810                                 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2811                                     (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2812                                     (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2813                                     (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2814                                     ((RegExp.$6.indexOf('.') < 0)
2815                                       ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2816                                       : (validation.types['ip4addr'].apply(RegExp.$6))))
2817                                         return true;
2818                         }
2819
2820                         validation.i18n('Must be a valid IPv4 address');
2821                         return false;
2822                 },
2823
2824                 'ip6addr': function()
2825                 {
2826                         if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2827                         {
2828                                 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2829                                 {
2830                                         var addr = RegExp.$1;
2831
2832                                         if (addr == '::')
2833                                         {
2834                                                 return true;
2835                                         }
2836
2837                                         if (addr.indexOf('.') > 0)
2838                                         {
2839                                                 var off = addr.lastIndexOf(':');
2840
2841                                                 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2842                                                 {
2843                                                         validation.i18n('Must be a valid IPv6 address');
2844                                                         return false;
2845                                                 }
2846
2847                                                 addr = addr.substr(0, off) + ':0:0';
2848                                         }
2849
2850                                         if (addr.indexOf('::') >= 0)
2851                                         {
2852                                                 var colons = 0;
2853                                                 var fill = '0';
2854
2855                                                 for (var i = 1; i < (addr.length-1); i++)
2856                                                         if (addr.charAt(i) == ':')
2857                                                                 colons++;
2858
2859                                                 if (colons > 7)
2860                                                 {
2861                                                         validation.i18n('Must be a valid IPv6 address');
2862                                                         return false;
2863                                                 }
2864
2865                                                 for (var i = 0; i < (7 - colons); i++)
2866                                                         fill += ':0';
2867
2868                                                 if (addr.match(/^(.*?)::(.*?)$/))
2869                                                         addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2870                                                                    (RegExp.$2 ? ':' + RegExp.$2 : '');
2871                                         }
2872
2873                                         if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2874                                                 return true;
2875
2876                                         validation.i18n('Must be a valid IPv6 address');
2877                                         return false;
2878                                 }
2879                         }
2880
2881                         return false;
2882                 },
2883
2884                 'port': function()
2885                 {
2886                         if (validation.types['integer'].apply(this) &&
2887                                 (this >= 0) && (this <= 65535))
2888                                 return true;
2889
2890                         validation.i18n('Must be a valid port number');
2891                         return false;
2892                 },
2893
2894                 'portrange': function()
2895                 {
2896                         if (this.match(/^(\d+)-(\d+)$/))
2897                         {
2898                                 var p1 = RegExp.$1;
2899                                 var p2 = RegExp.$2;
2900
2901                                 if (validation.types['port'].apply(p1) &&
2902                                     validation.types['port'].apply(p2) &&
2903                                     (parseInt(p1) <= parseInt(p2)))
2904                                         return true;
2905                         }
2906                         else if (validation.types['port'].apply(this))
2907                         {
2908                                 return true;
2909                         }
2910
2911                         validation.i18n('Must be a valid port range');
2912                         return false;
2913                 },
2914
2915                 'macaddr': function()
2916                 {
2917                         if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2918                                 return true;
2919
2920                         validation.i18n('Must be a valid MAC address');
2921                         return false;
2922                 },
2923
2924                 'host': function()
2925                 {
2926                         if (validation.types['hostname'].apply(this) ||
2927                             validation.types['ipaddr'].apply(this))
2928                                 return true;
2929
2930                         validation.i18n('Must be a valid hostname or IP address');
2931                         return false;
2932                 },
2933
2934                 'hostname': function()
2935                 {
2936                         if ((this.length <= 253) &&
2937                             ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2938                              (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2939                               this.match(/[^0-9.]/)))))
2940                                 return true;
2941
2942                         validation.i18n('Must be a valid host name');
2943                         return false;
2944                 },
2945
2946                 'network': function()
2947                 {
2948                         if (validation.types['uciname'].apply(this) ||
2949                             validation.types['host'].apply(this))
2950                                 return true;
2951
2952                         validation.i18n('Must be a valid network name');
2953                         return false;
2954                 },
2955
2956                 'wpakey': function()
2957                 {
2958                         var v = this;
2959
2960                         if ((v.length == 64)
2961                               ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2962                                   : ((v.length >= 8) && (v.length <= 63)))
2963                                 return true;
2964
2965                         validation.i18n('Must be a valid WPA key');
2966                         return false;
2967                 },
2968
2969                 'wepkey': function()
2970                 {
2971                         var v = this;
2972
2973                         if (v.substr(0,2) == 's:')
2974                                 v = v.substr(2);
2975
2976                         if (((v.length == 10) || (v.length == 26))
2977                               ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2978                               : ((v.length == 5) || (v.length == 13)))
2979                                 return true;
2980
2981                         validation.i18n('Must be a valid WEP key');
2982                         return false;
2983                 },
2984
2985                 'uciname': function()
2986                 {
2987                         if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2988                                 return true;
2989
2990                         validation.i18n('Must be a valid UCI identifier');
2991                         return false;
2992                 },
2993
2994                 'range': function(min, max)
2995                 {
2996                         var val = parseFloat(this);
2997
2998                         if (validation.types['integer'].apply(this) &&
2999                             !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
3000                                 return true;
3001
3002                         validation.i18n('Must be a number between %d and %d');
3003                         return false;
3004                 },
3005
3006                 'min': function(min)
3007                 {
3008                         var val = parseFloat(this);
3009
3010                         if (validation.types['integer'].apply(this) &&
3011                             !isNaN(min) && !isNaN(val) && (val >= min))
3012                                 return true;
3013
3014                         validation.i18n('Must be a number greater or equal to %d');
3015                         return false;
3016                 },
3017
3018                 'max': function(max)
3019                 {
3020                         var val = parseFloat(this);
3021
3022                         if (validation.types['integer'].apply(this) &&
3023                             !isNaN(max) && !isNaN(val) && (val <= max))
3024                                 return true;
3025
3026                         validation.i18n('Must be a number lower or equal to %d');
3027                         return false;
3028                 },
3029
3030                 'rangelength': function(min, max)
3031                 {
3032                         var val = '' + this;
3033
3034                         if (!isNaN(min) && !isNaN(max) &&
3035                             (val.length >= min) && (val.length <= max))
3036                                 return true;
3037
3038                         validation.i18n('Must be between %d and %d characters');
3039                         return false;
3040                 },
3041
3042                 'minlength': function(min)
3043                 {
3044                         var val = '' + this;
3045
3046                         if (!isNaN(min) && (val.length >= min))
3047                                 return true;
3048
3049                         validation.i18n('Must be at least %d characters');
3050                         return false;
3051                 },
3052
3053                 'maxlength': function(max)
3054                 {
3055                         var val = '' + this;
3056
3057                         if (!isNaN(max) && (val.length <= max))
3058                                 return true;
3059
3060                         validation.i18n('Must be at most %d characters');
3061                         return false;
3062                 },
3063
3064                 'or': function()
3065                 {
3066                         var msgs = [ ];
3067
3068                         for (var i = 0; i < arguments.length; i += 2)
3069                         {
3070                                 delete validation.message;
3071
3072                                 if (typeof(arguments[i]) != 'function')
3073                                 {
3074                                         if (arguments[i] == this)
3075                                                 return true;
3076                                         i--;
3077                                 }
3078                                 else if (arguments[i].apply(this, arguments[i+1]))
3079                                 {
3080                                         return true;
3081                                 }
3082
3083                                 if (validation.message)
3084                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3085                         }
3086
3087                         validation.message = msgs.join( _luci2.tr(' - or - '));
3088                         return false;
3089                 },
3090
3091                 'and': function()
3092                 {
3093                         var msgs = [ ];
3094
3095                         for (var i = 0; i < arguments.length; i += 2)
3096                         {
3097                                 delete validation.message;
3098
3099                                 if (typeof arguments[i] != 'function')
3100                                 {
3101                                         if (arguments[i] != this)
3102                                                 return false;
3103                                         i--;
3104                                 }
3105                                 else if (!arguments[i].apply(this, arguments[i+1]))
3106                                 {
3107                                         return false;
3108                                 }
3109
3110                                 if (validation.message)
3111                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
3112                         }
3113
3114                         validation.message = msgs.join(', ');
3115                         return true;
3116                 },
3117
3118                 'neg': function()
3119                 {
3120                         return validation.types['or'].apply(
3121                                 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
3122                 },
3123
3124                 'list': function(subvalidator, subargs)
3125                 {
3126                         if (typeof subvalidator != 'function')
3127                                 return false;
3128
3129                         var tokens = this.match(/[^ \t]+/g);
3130                         for (var i = 0; i < tokens.length; i++)
3131                                 if (!subvalidator.apply(tokens[i], subargs))
3132                                         return false;
3133
3134                         return true;
3135                 },
3136
3137                 'phonedigit': function()
3138                 {
3139                         if (this.match(/^[0-9\*#!\.]+$/) != null)
3140                                 return true;
3141
3142                         validation.i18n('Must be a valid phone number digit');
3143                         return false;
3144                 },
3145
3146                 'string': function()
3147                 {
3148                         return true;
3149                 }
3150         };
3151
3152
3153         this.cbi.AbstractValue = AbstractWidget.extend({
3154                 init: function(name, options)
3155                 {
3156                         this.name = name;
3157                         this.instance = { };
3158                         this.dependencies = [ ];
3159                         this.rdependency = { };
3160
3161                         this.options = _luci2.defaults(options, {
3162                                 placeholder: '',
3163                                 datatype: 'string',
3164                                 optional: false,
3165                                 keep: true
3166                         });
3167                 },
3168
3169                 id: function(sid)
3170                 {
3171                         return this.section.id('field', sid || '__unknown__', this.name);
3172                 },
3173
3174                 render: function(sid)
3175                 {
3176                         var i = this.instance[sid] = { };
3177
3178                         i.top = $('<div />').addClass('cbi-value');
3179
3180                         if (typeof(this.options.caption) == 'string')
3181                                 $('<label />')
3182                                         .addClass('cbi-value-title')
3183                                         .attr('for', this.id(sid))
3184                                         .text(this.options.caption)
3185                                         .appendTo(i.top);
3186
3187                         i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
3188                         i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
3189
3190                         if (typeof(this.options.description) == 'string')
3191                                 $('<div />')
3192                                         .addClass('cbi-value-description')
3193                                         .text(this.options.description)
3194                                         .appendTo(i.top);
3195
3196                         return i.top;
3197                 },
3198
3199                 ucipath: function(sid)
3200                 {
3201                         return {
3202                                 config:  (this.options.uci_package || this.map.uci_package),
3203                                 section: (this.options.uci_section || sid),
3204                                 option:  (this.options.uci_option  || this.name)
3205                         };
3206                 },
3207
3208                 ucivalue: function(sid)
3209                 {
3210                         var uci = this.ucipath(sid);
3211                         var val = this.map.get(uci.config, uci.section, uci.option);
3212
3213                         if (typeof(val) == 'undefined')
3214                                 return this.options.initial;
3215
3216                         return val;
3217                 },
3218
3219                 formvalue: function(sid)
3220                 {
3221                         var v = $('#' + this.id(sid)).val();
3222                         return (v === '') ? undefined : v;
3223                 },
3224
3225                 textvalue: function(sid)
3226                 {
3227                         var v = this.formvalue(sid);
3228
3229                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3230                                 v = this.ucivalue(sid);
3231
3232                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
3233                                 v = this.options.placeholder;
3234
3235                         if (typeof(v) == 'undefined' || v === '')
3236                                 return undefined;
3237
3238                         if (typeof(v) == 'string' && $.isArray(this.choices))
3239                         {
3240                                 for (var i = 0; i < this.choices.length; i++)
3241                                         if (v === this.choices[i][0])
3242                                                 return this.choices[i][1];
3243                         }
3244                         else if (v === true)
3245                                 return _luci2.tr('yes');
3246                         else if (v === false)
3247                                 return _luci2.tr('no');
3248                         else if ($.isArray(v))
3249                                 return v.join(', ');
3250
3251                         return v;
3252                 },
3253
3254                 changed: function(sid)
3255                 {
3256                         var a = this.ucivalue(sid);
3257                         var b = this.formvalue(sid);
3258
3259                         if (typeof(a) != typeof(b))
3260                                 return true;
3261
3262                         if (typeof(a) == 'object')
3263                         {
3264                                 if (a.length != b.length)
3265                                         return true;
3266
3267                                 for (var i = 0; i < a.length; i++)
3268                                         if (a[i] != b[i])
3269                                                 return true;
3270
3271                                 return false;
3272                         }
3273
3274                         return (a != b);
3275                 },
3276
3277                 save: function(sid)
3278                 {
3279                         var uci = this.ucipath(sid);
3280
3281                         if (this.instance[sid].disabled)
3282                         {
3283                                 if (!this.options.keep)
3284                                         return this.map.set(uci.config, uci.section, uci.option, undefined);
3285
3286                                 return false;
3287                         }
3288
3289                         var chg = this.changed(sid);
3290                         var val = this.formvalue(sid);
3291
3292                         if (chg)
3293                                 this.map.set(uci.config, uci.section, uci.option, val);
3294
3295                         return chg;
3296                 },
3297
3298                 validator: function(sid, elem, multi)
3299                 {
3300                         if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
3301                                 return elem;
3302
3303                         var vstack;
3304                         if (typeof(this.options.datatype) == 'string')
3305                         {
3306                                 try {
3307                                         vstack = _luci2.cbi.validation.compile(this.options.datatype);
3308                                 } catch(e) { };
3309                         }
3310                         else if (typeof(this.options.datatype) == 'function')
3311                         {
3312                                 var vfunc = this.options.datatype;
3313                                 vstack = [ function(elem) {
3314                                         var rv = vfunc(this, elem);
3315                                         if (rv !== true)
3316                                                 validation.message = rv;
3317                                         return (rv === true);
3318                                 }, [ elem ] ];
3319                         }
3320
3321                         var evdata = {
3322                                 self:  this,
3323                                 sid:   sid,
3324                                 elem:  elem,
3325                                 multi: multi,
3326                                 inst:  this.instance[sid],
3327                                 opt:   this.options.optional
3328                         };
3329
3330                         var validator = function(ev)
3331                         {
3332                                 var d = ev.data;
3333                                 var rv = true;
3334                                 var val = d.elem.val();
3335
3336                                 if (vstack && typeof(vstack[0]) == 'function')
3337                                 {
3338                                         delete validation.message;
3339
3340                                         if ((val.length == 0 && !d.opt))
3341                                         {
3342                                                 d.elem.addClass('error');
3343                                                 d.inst.top.addClass('error');
3344                                                 d.inst.error.text(_luci2.tr('Field must not be empty'));
3345                                                 rv = false;
3346                                         }
3347                                         else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
3348                                         {
3349                                                 d.elem.addClass('error');
3350                                                 d.inst.top.addClass('error');
3351                                                 d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
3352                                                 rv = false;
3353                                         }
3354                                         else
3355                                         {
3356                                                 d.elem.removeClass('error');
3357
3358                                                 if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
3359                                                 {
3360                                                         rv = false;
3361                                                 }
3362                                                 else
3363                                                 {
3364                                                         d.inst.top.removeClass('error');
3365                                                         d.inst.error.text('');
3366                                                 }
3367                                         }
3368                                 }
3369
3370                                 if (rv)
3371                                 {
3372                                         for (var field in d.self.rdependency)
3373                                                 d.self.rdependency[field].toggle(d.sid);
3374                                 }
3375
3376                                 return rv;
3377                         };
3378
3379                         if (elem.prop('tagName') == 'SELECT')
3380                         {
3381                                 elem.change(evdata, validator);
3382                         }
3383                         else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
3384                         {
3385                                 elem.click(evdata, validator);
3386                                 elem.blur(evdata, validator);
3387                         }
3388                         else
3389                         {
3390                                 elem.keyup(evdata, validator);
3391                                 elem.blur(evdata, validator);
3392                         }
3393
3394                         elem.attr('cbi-validate', true).on('validate', evdata, validator);
3395
3396                         return elem;
3397                 },
3398
3399                 validate: function(sid)
3400                 {
3401                         var i = this.instance[sid];
3402
3403                         i.widget.find('[cbi-validate]').trigger('validate');
3404
3405                         return (i.disabled || i.error.text() == '');
3406                 },
3407
3408                 depends: function(d, v)
3409                 {
3410                         var dep;
3411
3412                         if ($.isArray(d))
3413                         {
3414                                 dep = { };
3415                                 for (var i = 0; i < d.length; i++)
3416                                 {
3417                                         if (typeof(d[i]) == 'string')
3418                                                 dep[d[i]] = true;
3419                                         else if (d[i] instanceof _luci2.cbi.AbstractValue)
3420                                                 dep[d[i].name] = true;
3421                                 }
3422                         }
3423                         else if (d instanceof _luci2.cbi.AbstractValue)
3424                         {
3425                                 dep = { };
3426                                 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
3427                         }
3428                         else if (typeof(d) == 'object')
3429                         {
3430                                 dep = d;
3431                         }
3432                         else if (typeof(d) == 'string')
3433                         {
3434                                 dep = { };
3435                                 dep[d] = (typeof(v) == 'undefined') ? true : v;
3436                         }
3437
3438                         if (!dep || $.isEmptyObject(dep))
3439                                 return this;
3440
3441                         for (var field in dep)
3442                         {
3443                                 var f = this.section.fields[field];
3444                                 if (f)
3445                                         f.rdependency[this.name] = this;
3446                                 else
3447                                         delete dep[field];
3448                         }
3449
3450                         if ($.isEmptyObject(dep))
3451                                 return this;
3452
3453                         this.dependencies.push(dep);
3454
3455                         return this;
3456                 },
3457
3458                 toggle: function(sid)
3459                 {
3460                         var d = this.dependencies;
3461                         var i = this.instance[sid];
3462
3463                         if (!d.length)
3464                                 return true;
3465
3466                         for (var n = 0; n < d.length; n++)
3467                         {
3468                                 var rv = true;
3469
3470                                 for (var field in d[n])
3471                                 {
3472                                         var val = this.section.fields[field].formvalue(sid);
3473                                         var cmp = d[n][field];
3474
3475                                         if (typeof(cmp) == 'boolean')
3476                                         {
3477                                                 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
3478                                                 {
3479                                                         rv = false;
3480                                                         break;
3481                                                 }
3482                                         }
3483                                         else if (typeof(cmp) == 'string')
3484                                         {
3485                                                 if (val != cmp)
3486                                                 {
3487                                                         rv = false;
3488                                                         break;
3489                                                 }
3490                                         }
3491                                         else if (typeof(cmp) == 'function')
3492                                         {
3493                                                 if (!cmp(val))
3494                                                 {
3495                                                         rv = false;
3496                                                         break;
3497                                                 }
3498                                         }
3499                                         else if (cmp instanceof RegExp)
3500                                         {
3501                                                 if (!cmp.test(val))
3502                                                 {
3503                                                         rv = false;
3504                                                         break;
3505                                                 }
3506                                         }
3507                                 }
3508
3509                                 if (rv)
3510                                 {
3511                                         if (i.disabled)
3512                                         {
3513                                                 i.disabled = false;
3514                                                 i.top.fadeIn();
3515                                         }
3516
3517                                         return true;
3518                                 }
3519                         }
3520
3521                         if (!i.disabled)
3522                         {
3523                                 i.disabled = true;
3524                                 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
3525                         }
3526
3527                         return false;
3528                 }
3529         });
3530
3531         this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
3532                 widget: function(sid)
3533                 {
3534                         var o = this.options;
3535
3536                         if (typeof(o.enabled)  == 'undefined') o.enabled  = '1';
3537                         if (typeof(o.disabled) == 'undefined') o.disabled = '0';
3538
3539                         var i = $('<input />')
3540                                 .attr('id', this.id(sid))
3541                                 .attr('type', 'checkbox')
3542                                 .prop('checked', this.ucivalue(sid));
3543
3544                         return this.validator(sid, i);
3545                 },
3546
3547                 ucivalue: function(sid)
3548                 {
3549                         var v = this.callSuper('ucivalue', sid);
3550
3551                         if (typeof(v) == 'boolean')
3552                                 return v;
3553
3554                         return (v == this.options.enabled);
3555                 },
3556
3557                 formvalue: function(sid)
3558                 {
3559                         var v = $('#' + this.id(sid)).prop('checked');
3560
3561                         if (typeof(v) == 'undefined')
3562                                 return !!this.options.initial;
3563
3564                         return v;
3565                 },
3566
3567                 save: function(sid)
3568                 {
3569                         var uci = this.ucipath(sid);
3570
3571                         if (this.instance[sid].disabled)
3572                         {
3573                                 if (!this.options.keep)
3574                                         return this.map.set(uci.config, uci.section, uci.option, undefined);
3575
3576                                 return false;
3577                         }
3578
3579                         var chg = this.changed(sid);
3580                         var val = this.formvalue(sid);
3581
3582                         if (chg)
3583                         {
3584                                 val = val ? this.options.enabled : this.options.disabled;
3585
3586                                 if (this.options.optional && val == this.options.initial)
3587                                         this.map.set(uci.config, uci.section, uci.option, undefined);
3588                                 else
3589                                         this.map.set(uci.config, uci.section, uci.option, val);
3590                         }
3591
3592                         return chg;
3593                 }
3594         });
3595
3596         this.cbi.InputValue = this.cbi.AbstractValue.extend({
3597                 widget: function(sid)
3598                 {
3599                         var i = $('<input />')
3600                                 .attr('id', this.id(sid))
3601                                 .attr('type', 'text')
3602                                 .attr('placeholder', this.options.placeholder)
3603                                 .val(this.ucivalue(sid));
3604
3605                         return this.validator(sid, i);
3606                 }
3607         });
3608
3609         this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
3610                 widget: function(sid)
3611                 {
3612                         var i = $('<input />')
3613                                 .attr('id', this.id(sid))
3614                                 .attr('type', 'password')
3615                                 .attr('placeholder', this.options.placeholder)
3616                                 .val(this.ucivalue(sid));
3617
3618                         var t = $('<img />')
3619                                 .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
3620                                 .attr('title', _luci2.tr('Reveal or hide password'))
3621                                 .addClass('cbi-button')
3622                                 .click(function(ev) {
3623                                         var i = $(this).prev();
3624                                         var t = i.attr('type');
3625                                         i.attr('type', (t == 'password') ? 'text' : 'password');
3626                                         i = t = null;
3627                                 });
3628
3629                         this.validator(sid, i);
3630
3631                         return $('<div />')
3632                                 .addClass('cbi-input-password')
3633                                 .append(i)
3634                                 .append(t);
3635                 }
3636         });
3637
3638         this.cbi.ListValue = this.cbi.AbstractValue.extend({
3639                 widget: function(sid)
3640                 {
3641                         var s = $('<select />');
3642
3643                         if (this.options.optional)
3644                                 $('<option />')
3645                                         .attr('value', '')
3646                                         .text(_luci2.tr('-- Please choose --'))
3647                                         .appendTo(s);
3648
3649                         if (this.choices)
3650                                 for (var i = 0; i < this.choices.length; i++)
3651                                         $('<option />')
3652                                                 .attr('value', this.choices[i][0])
3653                                                 .text(this.choices[i][1])
3654                                                 .appendTo(s);
3655
3656                         s.attr('id', this.id(sid)).val(this.ucivalue(sid));
3657
3658                         return this.validator(sid, s);
3659                 },
3660
3661                 value: function(k, v)
3662                 {
3663                         if (!this.choices)
3664                                 this.choices = [ ];
3665
3666                         this.choices.push([k, v || k]);
3667                         return this;
3668                 }
3669         });
3670
3671         this.cbi.MultiValue = this.cbi.ListValue.extend({
3672                 widget: function(sid)
3673                 {
3674                         var v = this.ucivalue(sid);
3675                         var t = $('<div />').attr('id', this.id(sid));
3676
3677                         if (!$.isArray(v))
3678                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
3679
3680                         var s = { };
3681                         for (var i = 0; i < v.length; i++)
3682                                 s[v[i]] = true;
3683
3684                         if (this.choices)
3685                                 for (var i = 0; i < this.choices.length; i++)
3686                                 {
3687                                         $('<label />')
3688                                                 .append($('<input />')
3689                                                         .addClass('cbi-input-checkbox')
3690                                                         .attr('type', 'checkbox')
3691                                                         .attr('value', this.choices[i][0])
3692                                                         .prop('checked', s[this.choices[i][0]]))
3693                                                 .append(this.choices[i][1])
3694                                                 .appendTo(t);
3695
3696                                         $('<br />')
3697                                                 .appendTo(t);
3698                                 }
3699
3700                         return t;
3701                 },
3702
3703                 formvalue: function(sid)
3704                 {
3705                         var rv = [ ];
3706                         var fields = $('#' + this.id(sid) + ' > label > input');
3707
3708                         for (var i = 0; i < fields.length; i++)
3709                                 if (fields[i].checked)
3710                                         rv.push(fields[i].getAttribute('value'));
3711
3712                         return rv;
3713                 },
3714
3715                 textvalue: function(sid)
3716                 {
3717                         var v = this.formvalue(sid);
3718                         var c = { };
3719
3720                         if (this.choices)
3721                                 for (var i = 0; i < this.choices.length; i++)
3722                                         c[this.choices[i][0]] = this.choices[i][1];
3723
3724                         var t = [ ];
3725
3726                         for (var i = 0; i < v.length; i++)
3727                                 t.push(c[v[i]] || v[i]);
3728
3729                         return t.join(', ');
3730                 }
3731         });
3732
3733         this.cbi.ComboBox = this.cbi.AbstractValue.extend({
3734                 _change: function(ev)
3735                 {
3736                         var s = ev.target;
3737                         var self = ev.data.self;
3738
3739                         if (s.selectedIndex == (s.options.length - 1))
3740                         {
3741                                 ev.data.select.hide();
3742                                 ev.data.input.show().focus();
3743
3744                                 var v = ev.data.input.val();
3745                                 ev.data.input.val(' ');
3746                                 ev.data.input.val(v);
3747                         }
3748                         else if (self.options.optional && s.selectedIndex == 0)
3749                         {
3750                                 ev.data.input.val('');
3751                         }
3752                         else
3753                         {
3754                                 ev.data.input.val(ev.data.select.val());
3755                         }
3756                 },
3757
3758                 _blur: function(ev)
3759                 {
3760                         var seen = false;
3761                         var val = this.value;
3762                         var self = ev.data.self;
3763
3764                         ev.data.select.empty();
3765
3766                         if (self.options.optional)
3767                                 $('<option />')
3768                                         .attr('value', '')
3769                                         .text(_luci2.tr('-- please choose --'))
3770                                         .appendTo(ev.data.select);
3771
3772                         if (self.choices)
3773                                 for (var i = 0; i < self.choices.length; i++)
3774                                 {
3775                                         if (self.choices[i][0] == val)
3776                                                 seen = true;
3777
3778                                         $('<option />')
3779                                                 .attr('value', self.choices[i][0])
3780                                                 .text(self.choices[i][1])
3781                                                 .appendTo(ev.data.select);
3782                                 }
3783
3784                         if (!seen && val != '')
3785                                 $('<option />')
3786                                         .attr('value', val)
3787                                         .text(val)
3788                                         .appendTo(ev.data.select);
3789
3790                         $('<option />')
3791                                 .attr('value', ' ')
3792                                 .text(_luci2.tr('-- custom --'))
3793                                 .appendTo(ev.data.select);
3794
3795                         ev.data.input.hide();
3796                         ev.data.select.val(val).show().focus();
3797                 },
3798
3799                 _enter: function(ev)
3800                 {
3801                         if (ev.which != 13)
3802                                 return true;
3803
3804                         ev.preventDefault();
3805                         ev.data.self._blur(ev);
3806                         return false;
3807                 },
3808
3809                 widget: function(sid)
3810                 {
3811                         var d = $('<div />')
3812                                 .attr('id', this.id(sid));
3813
3814                         var t = $('<input />')
3815                                 .attr('type', 'text')
3816                                 .hide()
3817                                 .appendTo(d);
3818
3819                         var s = $('<select />')
3820                                 .appendTo(d);
3821
3822                         var evdata = {
3823                                 self: this,
3824                                 input: this.validator(sid, t),
3825                                 select: this.validator(sid, s)
3826                         };
3827
3828                         s.change(evdata, this._change);
3829                         t.blur(evdata, this._blur);
3830                         t.keydown(evdata, this._enter);
3831
3832                         t.val(this.ucivalue(sid));
3833                         t.blur();
3834
3835                         return d;
3836                 },
3837
3838                 value: function(k, v)
3839                 {
3840                         if (!this.choices)
3841                                 this.choices = [ ];
3842
3843                         this.choices.push([k, v || k]);
3844                         return this;
3845                 },
3846
3847                 formvalue: function(sid)
3848                 {
3849                         var v = $('#' + this.id(sid)).children('input').val();
3850                         return (v == '') ? undefined : v;
3851                 }
3852         });
3853
3854         this.cbi.DynamicList = this.cbi.ComboBox.extend({
3855                 _redraw: function(focus, add, del, s)
3856                 {
3857                         var v = s.values || [ ];
3858                         delete s.values;
3859
3860                         $(s.parent).children('input').each(function(i) {
3861                                 if (i != del)
3862                                         v.push(this.value || '');
3863                         });
3864
3865                         $(s.parent).empty();
3866
3867                         if (add >= 0)
3868                         {
3869                                 focus = add + 1;
3870                                 v.splice(focus, 0, '');
3871                         }
3872                         else if (v.length == 0)
3873                         {
3874                                 focus = 0;
3875                                 v.push('');
3876                         }
3877
3878                         for (var i = 0; i < v.length; i++)
3879                         {
3880                                 var evdata = {
3881                                         sid: s.sid,
3882                                         self: s.self,
3883                                         parent: s.parent,
3884                                         index: i
3885                                 };
3886
3887                                 if (this.choices)
3888                                 {
3889                                         var txt = $('<input />')
3890                                                 .attr('type', 'text')
3891                                                 .hide()
3892                                                 .appendTo(s.parent);
3893
3894                                         var sel = $('<select />')
3895                                                 .appendTo(s.parent);
3896
3897                                         evdata.input = this.validator(s.sid, txt, true);
3898                                         evdata.select = this.validator(s.sid, sel, true);
3899
3900                                         sel.change(evdata, this._change);
3901                                         txt.blur(evdata, this._blur);
3902                                         txt.keydown(evdata, this._keydown);
3903
3904                                         txt.val(v[i]);
3905                                         txt.blur();
3906
3907                                         if (i == focus || -(i+1) == focus)
3908                                                 sel.focus();
3909
3910                                         sel = txt = null;
3911                                 }
3912                                 else
3913                                 {
3914                                         var f = $('<input />')
3915                                                 .attr('type', 'text')
3916                                                 .attr('index', i)
3917                                                 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
3918                                                 .addClass('cbi-input-text')
3919                                                 .keydown(evdata, this._keydown)
3920                                                 .keypress(evdata, this._keypress)
3921                                                 .val(v[i]);
3922
3923                                         f.appendTo(s.parent);
3924
3925                                         if (i == focus)
3926                                         {
3927                                                 f.focus();
3928                                         }
3929                                         else if (-(i+1) == focus)
3930                                         {
3931                                                 f.focus();
3932
3933                                                 /* force cursor to end */
3934                                                 var val = f.val();
3935                                                 f.val(' ');
3936                                                 f.val(val);
3937                                         }
3938
3939                                         evdata.input = this.validator(s.sid, f, true);
3940
3941                                         f = null;
3942                                 }
3943
3944                                 $('<img />')
3945                                         .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
3946                                         .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
3947                                         .addClass('cbi-button')
3948                                         .click(evdata, this._btnclick)
3949                                         .appendTo(s.parent);
3950
3951                                 $('<br />')
3952                                         .appendTo(s.parent);
3953
3954                                 evdata = null;
3955                         }
3956
3957                         s = null;
3958                 },
3959
3960                 _keypress: function(ev)
3961                 {
3962                         switch (ev.which)
3963                         {
3964                                 /* backspace, delete */
3965                                 case 8:
3966                                 case 46:
3967                                         if (ev.data.input.val() == '')
3968                                         {
3969                                                 ev.preventDefault();
3970                                                 return false;
3971                                         }
3972
3973                                         return true;
3974
3975                                 /* enter, arrow up, arrow down */
3976                                 case 13:
3977                                 case 38:
3978                                 case 40:
3979                                         ev.preventDefault();
3980                                         return false;
3981                         }
3982
3983                         return true;
3984                 },
3985
3986                 _keydown: function(ev)
3987                 {
3988                         var input = ev.data.input;
3989
3990                         switch (ev.which)
3991                         {
3992                                 /* backspace, delete */
3993                                 case 8:
3994                                 case 46:
3995                                         if (input.val().length == 0)
3996                                         {
3997                                                 ev.preventDefault();
3998
3999                                                 var index = ev.data.index;
4000                                                 var focus = index;
4001
4002                                                 if (ev.which == 8)
4003                                                         focus = -focus;
4004
4005                                                 ev.data.self._redraw(focus, -1, index, ev.data);
4006                                                 return false;
4007                                         }
4008
4009                                         break;
4010
4011                                 /* enter */
4012                                 case 13:
4013                                         ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4014                                         break;
4015
4016                                 /* arrow up */
4017                                 case 38:
4018                                         var prev = input.prevAll('input:first');
4019                                         if (prev.is(':visible'))
4020                                                 prev.focus();
4021                                         else
4022                                                 prev.next('select').focus();
4023                                         break;
4024
4025                                 /* arrow down */
4026                                 case 40:
4027                                         var next = input.nextAll('input:first');
4028                                         if (next.is(':visible'))
4029                                                 next.focus();
4030                                         else
4031                                                 next.next('select').focus();
4032                                         break;
4033                         }
4034
4035                         return true;
4036                 },
4037
4038                 _btnclick: function(ev)
4039                 {
4040                         if (!this.getAttribute('disabled'))
4041                         {
4042                                 if (ev.target.src.indexOf('remove') > -1)
4043                                 {
4044                                         var index = ev.data.index;
4045                                         ev.data.self._redraw(-index, -1, index, ev.data);
4046                                 }
4047                                 else
4048                                 {
4049                                         ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
4050                                 }
4051                         }
4052
4053                         return false;
4054                 },
4055
4056                 widget: function(sid)
4057                 {
4058                         this.options.optional = true;
4059
4060                         var v = this.ucivalue(sid);
4061
4062                         if (!$.isArray(v))
4063                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4064
4065                         var d = $('<div />')
4066                                 .attr('id', this.id(sid))
4067                                 .addClass('cbi-input-dynlist');
4068
4069                         this._redraw(NaN, -1, -1, {
4070                                 self:      this,
4071                                 parent:    d[0],
4072                                 values:    v,
4073                                 sid:       sid
4074                         });
4075
4076                         return d;
4077                 },
4078
4079                 ucivalue: function(sid)
4080                 {
4081                         var v = this.callSuper('ucivalue', sid);
4082
4083                         if (!$.isArray(v))
4084                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
4085
4086                         return v;
4087                 },
4088
4089                 formvalue: function(sid)
4090                 {
4091                         var rv = [ ];
4092                         var fields = $('#' + this.id(sid) + ' > input');
4093
4094                         for (var i = 0; i < fields.length; i++)
4095                                 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
4096                                         rv.push(fields[i].value);
4097
4098                         return rv;
4099                 }
4100         });
4101
4102         this.cbi.DummyValue = this.cbi.AbstractValue.extend({
4103                 widget: function(sid)
4104                 {
4105                         return $('<div />')
4106                                 .addClass('cbi-value-dummy')
4107                                 .attr('id', this.id(sid))
4108                                 .html(this.ucivalue(sid));
4109                 },
4110
4111                 formvalue: function(sid)
4112                 {
4113                         return this.ucivalue(sid);
4114                 }
4115         });
4116
4117         this.cbi.NetworkList = this.cbi.AbstractValue.extend({
4118                 load: function(sid)
4119                 {
4120                         var self = this;
4121
4122                         if (!self.interfaces)
4123                         {
4124                                 self.interfaces = [ ];
4125                                 return _luci2.network.getNetworkStatus().then(function(ifaces) {
4126                                         self.interfaces = ifaces;
4127                                         self = null;
4128                                 });
4129                         }
4130
4131                         return undefined;
4132                 },
4133
4134                 _device_icon: function(dev)
4135                 {
4136                         var type = 'ethernet';
4137                         var desc = _luci2.tr('Ethernet device');
4138
4139                         if (dev.type == 'IP tunnel')
4140                         {
4141                                 type = 'tunnel';
4142                                 desc = _luci2.tr('Tunnel interface');
4143                         }
4144                         else if (dev['bridge-members'])
4145                         {
4146                                 type = 'bridge';
4147                                 desc = _luci2.tr('Bridge');
4148                         }
4149                         else if (dev.wireless)
4150                         {
4151                                 type = 'wifi';
4152                                 desc = _luci2.tr('Wireless Network');
4153                         }
4154                         else if (dev.device.indexOf('.') > 0)
4155                         {
4156                                 type = 'vlan';
4157                                 desc = _luci2.tr('VLAN interface');
4158                         }
4159
4160                         return $('<img />')
4161                                 .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
4162                                 .attr('title', '%s (%s)'.format(desc, dev.device));
4163                 },
4164
4165                 widget: function(sid)
4166                 {
4167                         var id = this.id(sid);
4168                         var ul = $('<ul />')
4169                                 .attr('id', id)
4170                                 .addClass('cbi-input-networks');
4171
4172                         var itype = this.options.multiple ? 'checkbox' : 'radio';
4173                         var value = this.ucivalue(sid);
4174                         var check = { };
4175
4176                         if (!this.options.multiple)
4177                                 check[value] = true;
4178                         else
4179                                 for (var i = 0; i < value.length; i++)
4180                                         check[value[i]] = true;
4181
4182                         if (this.interfaces)
4183                         {
4184                                 for (var i = 0; i < this.interfaces.length; i++)
4185                                 {
4186                                         var iface = this.interfaces[i];
4187                                         var badge = $('<span />')
4188                                                 .addClass('ifacebadge')
4189                                                 .text('%s: '.format(iface['interface']));
4190
4191                                         if (iface.device && iface.device.subdevices)
4192                                                 for (var j = 0; j < iface.device.subdevices.length; j++)
4193                                                         badge.append(this._device_icon(iface.device.subdevices[j]));
4194                                         else if (iface.device)
4195                                                 badge.append(this._device_icon(iface.device));
4196                                         else
4197                                                 badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
4198
4199                                         $('<li />')
4200                                                 .append($('<label />')
4201                                                         .append($('<input />')
4202                                                                 .attr('name', itype + id)
4203                                                                 .attr('type', itype)
4204                                                                 .attr('value', iface['interface'])
4205                                                                 .prop('checked', !!check[iface['interface']])
4206                                                                 .addClass('cbi-input-' + itype))
4207                                                         .append(badge))
4208                                                 .appendTo(ul);
4209                                 }
4210                         }
4211
4212                         if (!this.options.multiple)
4213                         {
4214                                 $('<li />')
4215                                         .append($('<label />')
4216                                                 .append($('<input />')
4217                                                         .attr('name', itype + id)
4218                                                         .attr('type', itype)
4219                                                         .attr('value', '')
4220                                                         .prop('checked', !value)
4221                                                         .addClass('cbi-input-' + itype))
4222                                                 .append(_luci2.tr('unspecified')))
4223                                         .appendTo(ul);
4224                         }
4225
4226                         return ul;
4227                 },
4228
4229                 ucivalue: function(sid)
4230                 {
4231                         var v = this.callSuper('ucivalue', sid);
4232
4233                         if (!this.options.multiple)
4234                         {
4235                                 if ($.isArray(v))
4236                                 {
4237                                         return v[0];
4238                                 }
4239                                 else if (typeof(v) == 'string')
4240                                 {
4241                                         v = v.match(/\S+/);
4242                                         return v ? v[0] : undefined;
4243                                 }
4244
4245                                 return v;
4246                         }
4247                         else
4248                         {
4249                                 if (typeof(v) == 'string')
4250                                         v = v.match(/\S+/g);
4251
4252                                 return v || [ ];
4253                         }
4254                 },
4255
4256                 formvalue: function(sid)
4257                 {
4258                         var inputs = $('#' + this.id(sid) + ' input');
4259
4260                         if (!this.options.multiple)
4261                         {
4262                                 for (var i = 0; i < inputs.length; i++)
4263                                         if (inputs[i].checked && inputs[i].value !== '')
4264                                                 return inputs[i].value;
4265
4266                                 return undefined;
4267                         }
4268
4269                         var rv = [ ];
4270
4271                         for (var i = 0; i < inputs.length; i++)
4272                                 if (inputs[i].checked)
4273                                         rv.push(inputs[i].value);
4274
4275                         return rv.length ? rv : undefined;
4276                 }
4277         });
4278
4279
4280         this.cbi.AbstractSection = AbstractWidget.extend({
4281                 id: function()
4282                 {
4283                         var s = [ arguments[0], this.map.uci_package, this.uci_type ];
4284
4285                         for (var i = 1; i < arguments.length; i++)
4286                                 s.push(arguments[i].replace(/\./g, '_'));
4287
4288                         return s.join('_');
4289                 },
4290
4291                 option: function(widget, name, options)
4292                 {
4293                         if (this.tabs.length == 0)
4294                                 this.tab({ id: '__default__', selected: true });
4295
4296                         return this.taboption('__default__', widget, name, options);
4297                 },
4298
4299                 tab: function(options)
4300                 {
4301                         if (options.selected)
4302                                 this.tabs.selected = this.tabs.length;
4303
4304                         this.tabs.push({
4305                                 id:          options.id,
4306                                 caption:     options.caption,
4307                                 description: options.description,
4308                                 fields:      [ ],
4309                                 li:          { }
4310                         });
4311                 },
4312
4313                 taboption: function(tabid, widget, name, options)
4314                 {
4315                         var tab;
4316                         for (var i = 0; i < this.tabs.length; i++)
4317                         {
4318                                 if (this.tabs[i].id == tabid)
4319                                 {
4320                                         tab = this.tabs[i];
4321                                         break;
4322                                 }
4323                         }
4324
4325                         if (!tab)
4326                                 throw 'Cannot append to unknown tab ' + tabid;
4327
4328                         var w = widget ? new widget(name, options) : null;
4329
4330                         if (!(w instanceof _luci2.cbi.AbstractValue))
4331                                 throw 'Widget must be an instance of AbstractValue';
4332
4333                         w.section = this;
4334                         w.map     = this.map;
4335
4336                         this.fields[name] = w;
4337                         tab.fields.push(w);
4338
4339                         return w;
4340                 },
4341
4342                 ucipackages: function(pkg)
4343                 {
4344                         for (var i = 0; i < this.tabs.length; i++)
4345                                 for (var j = 0; j < this.tabs[i].fields.length; j++)
4346                                         if (this.tabs[i].fields[j].options.uci_package)
4347                                                 pkg[this.tabs[i].fields[j].options.uci_package] = true;
4348                 },
4349
4350                 formvalue: function()
4351                 {
4352                         var rv = { };
4353
4354                         this.sections(function(s) {
4355                                 var sid = s['.name'];
4356                                 var sv = rv[sid] || (rv[sid] = { });
4357
4358                                 for (var i = 0; i < this.tabs.length; i++)
4359                                         for (var j = 0; j < this.tabs[i].fields.length; j++)
4360                                         {
4361                                                 var val = this.tabs[i].fields[j].formvalue(sid);
4362                                                 sv[this.tabs[i].fields[j].name] = val;
4363                                         }
4364                         });
4365
4366                         return rv;
4367                 },
4368
4369                 validate: function(sid)
4370                 {
4371                         var rv = true;
4372
4373                         if (!sid)
4374                         {
4375                                 var as = this.sections();
4376                                 for (var i = 0; i < as.length; i++)
4377                                         if (!this.validate(as[i]['.name']))
4378                                                 rv = false;
4379                                 return rv;
4380                         }
4381
4382                         var inst = this.instance[sid];
4383                         var sv = rv[sid] || (rv[sid] = { });
4384
4385                         var invals = 0;
4386                         var legend = $('#' + this.id('sort', sid)).find('legend:first');
4387
4388                         legend.children('span').detach();
4389
4390                         for (var i = 0; i < this.tabs.length; i++)
4391                         {
4392                                 var inval = 0;
4393                                 var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
4394
4395                                 tab.children('span').detach();
4396
4397                                 for (var j = 0; j < this.tabs[i].fields.length; j++)
4398                                         if (!this.tabs[i].fields[j].validate(sid))
4399                                                 inval++;
4400
4401                                 if (inval > 0)
4402                                 {
4403                                         $('<span />')
4404                                                 .addClass('badge')
4405                                                 .attr('title', _luci2.tr('%d Errors'.format(inval)))
4406                                                 .text(inval)
4407                                                 .appendTo(tab);
4408
4409                                         invals += inval;
4410                                         tab = null;
4411                                         rv = false;
4412                                 }
4413                         }
4414
4415                         if (invals > 0)
4416                                 $('<span />')
4417                                         .addClass('badge')
4418                                         .attr('title', _luci2.tr('%d Errors'.format(invals)))
4419                                         .text(invals)
4420                                         .appendTo(legend);
4421
4422                         return rv;
4423                 }
4424         });
4425
4426         this.cbi.TypedSection = this.cbi.AbstractSection.extend({
4427                 init: function(uci_type, options)
4428                 {
4429                         this.uci_type = uci_type;
4430                         this.options  = options;
4431                         this.tabs     = [ ];
4432                         this.fields   = { };
4433                         this.active_panel = 0;
4434                         this.active_tab   = { };
4435                 },
4436
4437                 filter: function(section)
4438                 {
4439                         return true;
4440                 },
4441
4442                 sections: function(cb)
4443                 {
4444                         var s1 = this.map.ucisections(this.map.uci_package);
4445                         var s2 = [ ];
4446
4447                         for (var i = 0; i < s1.length; i++)
4448                                 if (s1[i]['.type'] == this.uci_type)
4449                                         if (this.filter(s1[i]))
4450                                                 s2.push(s1[i]);
4451
4452                         if (typeof(cb) == 'function')
4453                                 for (var i = 0; i < s2.length; i++)
4454                                         cb.apply(this, [ s2[i] ]);
4455
4456                         return s2;
4457                 },
4458
4459                 add: function(name)
4460                 {
4461                         this.map.add(this.map.uci_package, this.uci_type, name);
4462                 },
4463
4464                 remove: function(sid)
4465                 {
4466                         this.map.remove(this.map.uci_package, sid);
4467                 },
4468
4469                 _add: function(ev)
4470                 {
4471                         var addb = $(this);
4472                         var name = undefined;
4473                         var self = ev.data.self;
4474
4475                         if (addb.prev().prop('nodeName') == 'INPUT')
4476                                 name = addb.prev().val();
4477
4478                         if (addb.prop('disabled') || name === '')
4479                                 return;
4480
4481                         _luci2.ui.saveScrollTop();
4482
4483                         self.active_panel = -1;
4484                         self.map.save();
4485                         self.add(name);
4486                         self.map.redraw();
4487
4488                         _luci2.ui.restoreScrollTop();
4489                 },
4490
4491                 _remove: function(ev)
4492                 {
4493                         var self = ev.data.self;
4494                         var sid  = ev.data.sid;
4495
4496                         if (ev.data.index == (self.sections().length - 1))
4497                                 self.active_panel = -1;
4498
4499                         _luci2.ui.saveScrollTop();
4500
4501                         self.map.save();
4502                         self.remove(sid);
4503                         self.map.redraw();
4504
4505                         _luci2.ui.restoreScrollTop();
4506
4507                         ev.stopPropagation();
4508                 },
4509
4510                 _sid: function(ev)
4511                 {
4512                         var self = ev.data.self;
4513                         var text = $(this);
4514                         var addb = text.next();
4515                         var errt = addb.next();
4516                         var name = text.val();
4517                         var used = false;
4518
4519                         if (!/^[a-zA-Z0-9_]*$/.test(name))
4520                         {
4521                                 errt.text(_luci2.tr('Invalid section name')).show();
4522                                 text.addClass('error');
4523                                 addb.prop('disabled', true);
4524                                 return false;
4525                         }
4526
4527                         for (var sid in self.map.uci.values[self.map.uci_package])
4528                                 if (sid == name)
4529                                 {
4530                                         used = true;
4531                                         break;
4532                                 }
4533
4534                         for (var sid in self.map.uci.creates[self.map.uci_package])
4535                                 if (sid == name)
4536                                 {
4537                                         used = true;
4538                                         break;
4539                                 }
4540
4541                         if (used)
4542                         {
4543                                 errt.text(_luci2.tr('Name already used')).show();
4544                                 text.addClass('error');
4545                                 addb.prop('disabled', true);
4546                                 return false;
4547                         }
4548
4549                         errt.text('').hide();
4550                         text.removeClass('error');
4551                         addb.prop('disabled', false);
4552                         return true;
4553                 },
4554
4555                 teaser: function(sid)
4556                 {
4557                         var tf = this.teaser_fields;
4558
4559                         if (!tf)
4560                         {
4561                                 tf = this.teaser_fields = [ ];
4562
4563                                 if ($.isArray(this.options.teasers))
4564                                 {
4565                                         for (var i = 0; i < this.options.teasers.length; i++)
4566                                         {
4567                                                 var f = this.options.teasers[i];
4568                                                 if (f instanceof _luci2.cbi.AbstractValue)
4569                                                         tf.push(f);
4570                                                 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
4571                                                         tf.push(this.fields[f]);
4572                                         }
4573                                 }
4574                                 else
4575                                 {
4576                                         for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
4577                                                 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
4578                                                         tf.push(this.tabs[i].fields[j]);
4579                                 }
4580                         }
4581
4582                         var t = '';
4583
4584                         for (var i = 0; i < tf.length; i++)
4585                         {
4586                                 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
4587                                         continue;
4588
4589                                 var n = tf[i].options.caption || tf[i].name;
4590                                 var v = tf[i].textvalue(sid);
4591
4592                                 if (typeof(v) == 'undefined')
4593                                         continue;
4594
4595                                 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
4596                         }
4597
4598                         return t;
4599                 },
4600
4601                 _render_add: function()
4602                 {
4603                         var text = _luci2.tr('Add section');
4604                         var ttip = _luci2.tr('Create new section...');
4605
4606                         if ($.isArray(this.options.add_caption))
4607                                 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
4608                         else if (typeof(this.options.add_caption) == 'string')
4609                                 text = this.options.add_caption, ttip = '';
4610
4611                         var add = $('<div />').addClass('cbi-section-add');
4612
4613                         if (this.options.anonymous === false)
4614                         {
4615                                 $('<input />')
4616                                         .addClass('cbi-input-text')
4617                                         .attr('type', 'text')
4618                                         .attr('placeholder', ttip)
4619                                         .blur({ self: this }, this._sid)
4620                                         .keyup({ self: this }, this._sid)
4621                                         .appendTo(add);
4622
4623                                 $('<img />')
4624                                         .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
4625                                         .attr('title', text)
4626                                         .addClass('cbi-button')
4627                                         .click({ self: this }, this._add)
4628                                         .appendTo(add);
4629
4630                                 $('<div />')
4631                                         .addClass('cbi-value-error')
4632                                         .hide()
4633                                         .appendTo(add);
4634                         }
4635                         else
4636                         {
4637                                 $('<input />')
4638                                         .attr('type', 'button')
4639                                         .addClass('cbi-button')
4640                                         .addClass('cbi-button-add')
4641                                         .val(text).attr('title', ttip)
4642                                         .click({ self: this }, this._add)
4643                                         .appendTo(add)
4644                         }
4645
4646                         return add;
4647                 },
4648
4649                 _render_remove: function(sid, index)
4650                 {
4651                         var text = _luci2.tr('Remove');
4652                         var ttip = _luci2.tr('Remove this section');
4653
4654                         if ($.isArray(this.options.remove_caption))
4655                                 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
4656                         else if (typeof(this.options.remove_caption) == 'string')
4657                                 text = this.options.remove_caption, ttip = '';
4658
4659                         return $('<input />')
4660                                 .attr('type', 'button')
4661                                 .addClass('cbi-button')
4662                                 .addClass('cbi-button-remove')
4663                                 .val(text).attr('title', ttip)
4664                                 .click({ self: this, sid: sid, index: index }, this._remove);
4665                 },
4666
4667                 _render_caption: function(sid)
4668                 {
4669                         if (typeof(this.options.caption) == 'string')
4670                         {
4671                                 return $('<legend />')
4672                                         .text(this.options.caption.format(sid));
4673                         }
4674                         else if (typeof(this.options.caption) == 'function')
4675                         {
4676                                 return $('<legend />')
4677                                         .text(this.options.caption.call(this, sid));
4678                         }
4679
4680                         return '';
4681                 },
4682
4683                 render: function()
4684                 {
4685                         var allsections = $();
4686                         var panel_index = 0;
4687
4688                         this.instance = { };
4689
4690                         var s = this.sections();
4691
4692                         if (s.length == 0)
4693                         {
4694                                 var fieldset = $('<fieldset />')
4695                                         .addClass('cbi-section');
4696
4697                                 var head = $('<div />')
4698                                         .addClass('cbi-section-head')
4699                                         .appendTo(fieldset);
4700
4701                                 head.append(this._render_caption(undefined));
4702
4703                                 if (typeof(this.options.description) == 'string')
4704                                 {
4705                                         $('<div />')
4706                                                 .addClass('cbi-section-descr')
4707                                                 .text(this.options.description)
4708                                                 .appendTo(head);
4709                                 }
4710
4711                                 allsections = allsections.add(fieldset);
4712                         }
4713
4714                         for (var i = 0; i < s.length; i++)
4715                         {
4716                                 var sid = s[i]['.name'];
4717                                 var inst = this.instance[sid] = { tabs: [ ] };
4718
4719                                 var fieldset = $('<fieldset />')
4720                                         .attr('id', this.id('sort', sid))
4721                                         .addClass('cbi-section');
4722
4723                                 var head = $('<div />')
4724                                         .addClass('cbi-section-head')
4725                                         .attr('cbi-section-num', this.index)
4726                                         .attr('cbi-section-id', sid);
4727
4728                                 head.append(this._render_caption(sid));
4729
4730                                 if (typeof(this.options.description) == 'string')
4731                                 {
4732                                         $('<div />')
4733                                                 .addClass('cbi-section-descr')
4734                                                 .text(this.options.description)
4735                                                 .appendTo(head);
4736                                 }
4737
4738                                 var teaser;
4739                                 if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
4740                                         teaser = $('<div />')
4741                                                 .addClass('cbi-section-teaser')
4742                                                 .appendTo(head);
4743
4744                                 if (this.options.addremove)
4745                                         $('<div />')
4746                                                 .addClass('cbi-section-remove')
4747                                                 .addClass('right')
4748                                                 .append(this._render_remove(sid, panel_index))
4749                                                 .appendTo(head);
4750
4751                                 var body = $('<div />')
4752                                         .attr('index', panel_index++);
4753
4754                                 var fields = $('<fieldset />')
4755                                         .addClass('cbi-section-node');
4756
4757                                 if (this.tabs.length > 1)
4758                                 {
4759                                         var menu = $('<ul />')
4760                                                 .addClass('cbi-tabmenu');
4761
4762                                         for (var j = 0; j < this.tabs.length; j++)
4763                                         {
4764                                                 var tabid = this.id('tab', sid, this.tabs[j].id);
4765                                                 var theadid = this.id('tabhead', sid, this.tabs[j].id);
4766
4767                                                 var tabc = $('<div />')
4768                                                         .addClass('cbi-tabcontainer')
4769                                                         .attr('id', tabid)
4770                                                         .attr('index', j);
4771
4772                                                 if (typeof(this.tabs[j].description) == 'string')
4773                                                 {
4774                                                         $('<div />')
4775                                                                 .addClass('cbi-tab-descr')
4776                                                                 .text(this.tabs[j].description)
4777                                                                 .appendTo(tabc);
4778                                                 }
4779
4780                                                 for (var k = 0; k < this.tabs[j].fields.length; k++)
4781                                                         this.tabs[j].fields[k].render(sid).appendTo(tabc);
4782
4783                                                 tabc.appendTo(fields);
4784                                                 tabc = null;
4785
4786                                                 $('<li />').attr('id', theadid).append(
4787                                                         $('<a />')
4788                                                                 .text(this.tabs[j].caption.format(this.tabs[j].id))
4789                                                                 .attr('href', '#' + tabid)
4790                                                 ).appendTo(menu);
4791                                         }
4792
4793                                         menu.appendTo(body);
4794                                         menu = null;
4795
4796                                         fields.appendTo(body);
4797                                         fields = null;
4798
4799                                         var t = body.tabs({ active: this.active_tab[sid] });
4800
4801                                         t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
4802                                                 var d = ev.data;
4803                                                 d.self.validate();
4804                                                 d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
4805                                         });
4806                                 }
4807                                 else
4808                                 {
4809                                         for (var j = 0; j < this.tabs[0].fields.length; j++)
4810                                                 this.tabs[0].fields[j].render(sid).appendTo(fields);
4811
4812                                         fields.appendTo(body);
4813                                         fields = null;
4814                                 }
4815
4816                                 head.appendTo(fieldset);
4817                                 head = null;
4818
4819                                 body.appendTo(fieldset);
4820                                 body = null;
4821
4822                                 allsections = allsections.add(fieldset);
4823                                 fieldset = null;
4824
4825                                 //this.validate(sid);
4826                                 //
4827                                 //if (teaser)
4828                                 //      teaser.append(this.teaser(sid));
4829                         }
4830
4831                         if (this.options.collabsible && s.length > 1)
4832                         {
4833                                 var a = $('<div />').append(allsections).accordion({
4834                                         header: '> fieldset > div.cbi-section-head',
4835                                         heightStyle: 'content',
4836                                         active: this.active_panel
4837                                 });
4838
4839                                 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
4840                                         var h = ui.oldHeader;
4841                                         var s = ev.data.self;
4842                                         var i = h.attr('cbi-section-id');
4843
4844                                         h.children('.cbi-section-teaser').empty().append(s.teaser(i));
4845                                         s.validate();
4846                                 });
4847
4848                                 a.on('accordionactivate', { self: this }, function(ev, ui) {
4849                                         ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
4850                                 });
4851
4852                                 if (this.options.sortable)
4853                                 {
4854                                         var s = a.sortable({
4855                                                 axis: 'y',
4856                                                 handle: 'div.cbi-section-head'
4857                                         });
4858
4859                                         s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
4860                                                 var sections = [ ];
4861                                                 for (var i = 0; i < ev.data.ids.length; i++)
4862                                                         sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
4863                                                 _luci2.uci.order(ev.data.self.map.uci_package, sections);
4864                                         });
4865
4866                                         s.on('sortstop', function(ev, ui) {
4867                                                 ui.item.children('div.cbi-section-head').triggerHandler('focusout');
4868                                         });
4869                                 }
4870
4871                                 if (this.options.addremove)
4872                                         this._render_add().appendTo(a);
4873
4874                                 return a;
4875                         }
4876
4877                         if (this.options.addremove)
4878                                 allsections = allsections.add(this._render_add());
4879
4880                         return allsections;
4881                 },
4882
4883                 finish: function()
4884                 {
4885                         var s = this.sections();
4886
4887                         for (var i = 0; i < s.length; i++)
4888                         {
4889                                 var sid = s[i]['.name'];
4890
4891                                 this.validate(sid);
4892
4893                                 $('#' + this.id('sort', sid))
4894                                         .children('.cbi-section-head')
4895                                         .children('.cbi-section-teaser')
4896                                         .append(this.teaser(sid));
4897                         }
4898                 }
4899         });
4900
4901         this.cbi.TableSection = this.cbi.TypedSection.extend({
4902                 render: function()
4903                 {
4904                         var allsections = $();
4905                         var panel_index = 0;
4906
4907                         this.instance = { };
4908
4909                         var s = this.sections();
4910
4911                         var fieldset = $('<fieldset />')
4912                                 .addClass('cbi-section');
4913
4914                         fieldset.append(this._render_caption(sid));
4915
4916                         if (typeof(this.options.description) == 'string')
4917                         {
4918                                 $('<div />')
4919                                         .addClass('cbi-section-descr')
4920                                         .text(this.options.description)
4921                                         .appendTo(fieldset);
4922                         }
4923
4924                         var fields = $('<div />')
4925                                 .addClass('cbi-section-node')
4926                                 .appendTo(fieldset);
4927
4928                         var table = $('<table />')
4929                                 .addClass('cbi-section-table')
4930                                 .appendTo(fields);
4931
4932                         var thead = $('<thead />')
4933                                 .append($('<tr />').addClass('cbi-section-table-titles'))
4934                                 .appendTo(table);
4935
4936                         for (var j = 0; j < this.tabs[0].fields.length; j++)
4937                                 $('<th />')
4938                                         .addClass('cbi-section-table-cell')
4939                                         .css('width', this.tabs[0].fields[j].options.width || '')
4940                                         .append(this.tabs[0].fields[j].options.caption)
4941                                         .appendTo(thead.children());
4942
4943                         if (this.options.sortable)
4944                                 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4945
4946                         if (this.options.addremove !== false)
4947                                 $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
4948
4949                         var tbody = $('<tbody />')
4950                                 .appendTo(table);
4951
4952                         if (s.length == 0)
4953                         {
4954                                 $('<tr />')
4955                                         .addClass('cbi-section-table-row')
4956                                         .append(
4957                                                 $('<td />')
4958                                                         .addClass('cbi-section-table-cell')
4959                                                         .addClass('cbi-section-table-placeholder')
4960                                                         .attr('colspan', thead.children().children().length)
4961                                                         .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
4962                                         .appendTo(tbody);
4963                         }
4964
4965                         for (var i = 0; i < s.length; i++)
4966                         {
4967                                 var sid = s[i]['.name'];
4968                                 var inst = this.instance[sid] = { tabs: [ ] };
4969
4970                                 var row = $('<tr />')
4971                                         .addClass('cbi-section-table-row')
4972                                         .appendTo(tbody);
4973
4974                                 for (var j = 0; j < this.tabs[0].fields.length; j++)
4975                                 {
4976                                         $('<td />')
4977                                                 .addClass('cbi-section-table-cell')
4978                                                 .css('width', this.tabs[0].fields[j].options.width || '')
4979                                                 .append(this.tabs[0].fields[j].render(sid, true))
4980                                                 .appendTo(row);
4981                                 }
4982
4983                                 if (this.options.sortable)
4984                                 {
4985                                         $('<td />')
4986                                                 .addClass('cbi-section-table-cell')
4987                                                 .addClass('cbi-section-table-sort')
4988                                                 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
4989                                                 .append($('<br />'))
4990                                                 .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
4991                                                 .appendTo(row);
4992                                 }
4993
4994                                 if (this.options.addremove !== false)
4995                                 {
4996                                         $('<td />')
4997                                                 .addClass('cbi-section-table-cell')
4998                                                 .append(this._render_remove(sid))
4999                                                 .appendTo(row);
5000                                 }
5001
5002                                 this.validate(sid);
5003
5004                                 row = null;
5005                         }
5006
5007                         if (this.options.sortable)
5008                         {
5009                                 var s = tbody.sortable({
5010                                         handle: 'td.cbi-section-table-sort'
5011                                 });
5012
5013                                 s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
5014                                         var sections = [ ];
5015                                         for (var i = 0; i < ev.data.ids.length; i++)
5016                                                 sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
5017                                         _luci2.uci.order(ev.data.self.map.uci_package, sections);
5018                                 });
5019
5020                                 s.on('sortstop', function(ev, ui) {
5021                                         ui.item.children('div.cbi-section-head').triggerHandler('focusout');
5022                                 });
5023                         }
5024
5025                         if (this.options.addremove)
5026                                 this._render_add().appendTo(fieldset);
5027
5028                         fields = table = thead = tbody = null;
5029
5030                         return fieldset;
5031                 }
5032         });
5033
5034         this.cbi.NamedSection = this.cbi.TypedSection.extend({
5035                 sections: function(cb)
5036                 {
5037                         var sa = [ ];
5038                         var pkg = this.map.uci.values[this.map.uci_package];
5039
5040                         for (var s in pkg)
5041                                 if (pkg[s]['.name'] == this.uci_type)
5042                                 {
5043                                         sa.push(pkg[s]);
5044                                         break;
5045                                 }
5046
5047                         if (typeof(cb) == 'function' && sa.length > 0)
5048                                 cb.apply(this, [ sa[0] ]);
5049
5050                         return sa;
5051                 }
5052         });
5053
5054         this.cbi.DummySection = this.cbi.TypedSection.extend({
5055                 sections: function(cb)
5056                 {
5057                         if (typeof(cb) == 'function')
5058                                 cb.apply(this, [ { '.name': this.uci_type } ]);
5059
5060                         return [ { '.name': this.uci_type } ];
5061                 }
5062         });
5063
5064         this.cbi.Map = AbstractWidget.extend({
5065                 init: function(uci_package, options)
5066                 {
5067                         var self = this;
5068
5069                         this.uci_package = uci_package;
5070                         this.sections = [ ];
5071                         this.options = _luci2.defaults(options, {
5072                                 save:    function() { },
5073                                 prepare: function() {
5074                                         return _luci2.uci.writable(function(writable) {
5075                                                 self.options.readonly = !writable;
5076                                         });
5077                                 }
5078                         });
5079                 },
5080
5081                 load: function()
5082                 {
5083                         this.uci = {
5084                                 newid:   0,
5085                                 values:  { },
5086                                 creates: { },
5087                                 changes: { },
5088                                 deletes: { }
5089                         };
5090
5091                         if (typeof(this.active_panel) == 'undefined')
5092                                 this.active_panel = 0;
5093
5094                         var packages = { };
5095
5096                         for (var i = 0; i < this.sections.length; i++)
5097                                 this.sections[i].ucipackages(packages);
5098
5099                         packages[this.uci_package] = true;
5100
5101                         var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
5102                                 for (var i = 0; i < packages.length; i++)
5103                                 {
5104                                         this.uci.values[packages[i]['.package']] = packages[i];
5105                                         delete packages[i]['.package'];
5106                                 }
5107
5108                                 var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
5109
5110                                 for (var i = 0; i < this.sections.length; i++)
5111                                 {
5112                                         for (var f in this.sections[i].fields)
5113                                         {
5114                                                 if (typeof(this.sections[i].fields[f].load) != 'function')
5115                                                         continue;
5116
5117                                                 var s = this.sections[i].sections();
5118                                                 for (var j = 0; j < s.length; j++)
5119                                                 {
5120                                                         var rv = this.sections[i].fields[f].load(s[j]['.name']);
5121                                                         if (_luci2.isDeferred(rv))
5122                                                                 deferreds.push(rv);
5123                                                 }
5124                                         }
5125                                 }
5126
5127                                 return $.when.apply($, deferreds);
5128                         }, this));
5129
5130                         _luci2.rpc.batch();
5131
5132                         for (var pkg in packages)
5133                                 _luci2.uci.get_all(pkg);
5134
5135                         return _luci2.rpc.flush().then(load_cb);
5136                 },
5137
5138                 render: function()
5139                 {
5140                         var map = $('<div />').addClass('cbi-map');
5141
5142                         if (typeof(this.options.caption) == 'string')
5143                                 $('<h2 />').text(this.options.caption).appendTo(map);
5144
5145                         if (typeof(this.options.description) == 'string')
5146                                 $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
5147
5148                         var sections = $('<div />').appendTo(map);
5149
5150                         for (var i = 0; i < this.sections.length; i++)
5151                         {
5152                                 var s = this.sections[i].render();
5153
5154                                 if (this.options.readonly || this.sections[i].options.readonly)
5155                                         s.find('input, select, button, img.cbi-button').attr('disabled', true);
5156
5157                                 s.appendTo(sections);
5158
5159                                 if (this.sections[i].options.active)
5160                                         this.active_panel = i;
5161                         }
5162
5163                         if (this.options.collabsible)
5164                         {
5165                                 var a = sections.accordion({
5166                                         header: '> fieldset > div.cbi-section-head',
5167                                         heightStyle: 'content',
5168                                         active: this.active_panel
5169                                 });
5170
5171                                 a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
5172                                         var h = ui.oldHeader;
5173                                         var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
5174                                         var i = h.attr('cbi-section-id');
5175
5176                                         h.children('.cbi-section-teaser').empty().append(s.teaser(i));
5177
5178                                         for (var i = 0; i < ev.data.self.sections.length; i++)
5179                                                 ev.data.self.sections[i].validate();
5180                                 });
5181
5182                                 a.on('accordionactivate', { self: this }, function(ev, ui) {
5183                                         ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
5184                                 });
5185                         }
5186
5187                         if (this.options.pageaction !== false)
5188                         {
5189                                 var a = $('<div />')
5190                                         .addClass('cbi-page-actions')
5191                                         .appendTo(map);
5192
5193                                 $('<input />')
5194                                         .addClass('cbi-button').addClass('cbi-button-apply')
5195                                         .attr('type', 'button')
5196                                         .val(_luci2.tr('Save & Apply'))
5197                                         .appendTo(a);
5198
5199                                 $('<input />')
5200                                         .addClass('cbi-button').addClass('cbi-button-save')
5201                                         .attr('type', 'button')
5202                                         .val(_luci2.tr('Save'))
5203                                         .click({ self: this }, function(ev) { ev.data.self.send(); })
5204                                         .appendTo(a);
5205
5206                                 $('<input />')
5207                                         .addClass('cbi-button').addClass('cbi-button-reset')
5208                                         .attr('type', 'button')
5209                                         .val(_luci2.tr('Reset'))
5210                                         .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
5211                                         .appendTo(a);
5212
5213                                 a = null;
5214                         }
5215
5216                         var top = $('<form />').append(map);
5217
5218                         map = null;
5219
5220                         return top;
5221                 },
5222
5223                 finish: function()
5224                 {
5225                         for (var i = 0; i < this.sections.length; i++)
5226                                 this.sections[i].finish();
5227
5228                         this.validate();
5229                 },
5230
5231                 redraw: function()
5232                 {
5233                         this.target.hide().empty().append(this.render());
5234                         this.finish();
5235                         this.target.show();
5236                 },
5237
5238                 section: function(widget, uci_type, options)
5239                 {
5240                         var w = widget ? new widget(uci_type, options) : null;
5241
5242                         if (!(w instanceof _luci2.cbi.AbstractSection))
5243                                 throw 'Widget must be an instance of AbstractSection';
5244
5245                         w.map = this;
5246                         w.index = this.sections.length;
5247
5248                         this.sections.push(w);
5249                         return w;
5250                 },
5251
5252                 formvalue: function()
5253                 {
5254                         var rv = { };
5255
5256                         for (var i = 0; i < this.sections.length; i++)
5257                         {
5258                                 var sids = this.sections[i].formvalue();
5259                                 for (var sid in sids)
5260                                 {
5261                                         var s = rv[sid] || (rv[sid] = { });
5262                                         $.extend(s, sids[sid]);
5263                                 }
5264                         }
5265
5266                         return rv;
5267                 },
5268
5269                 add: function(conf, type, name)
5270                 {
5271                         var c = this.uci.creates;
5272                         var s = '.new.%d'.format(this.uci.newid++);
5273
5274                         if (!c[conf])
5275                                 c[conf] = { };
5276
5277                         c[conf][s] = {
5278                                 '.type':      type,
5279                                 '.name':      s,
5280                                 '.create':    name,
5281                                 '.anonymous': !name
5282                         };
5283
5284                         return s;
5285                 },
5286
5287                 remove: function(conf, sid)
5288                 {
5289                         var n = this.uci.creates;
5290                         var c = this.uci.changes;
5291                         var d = this.uci.deletes;
5292
5293                         /* requested deletion of a just created section */
5294                         if (sid.indexOf('.new.') == 0)
5295                         {
5296                                 if (n[conf])
5297                                         delete n[conf][sid];
5298                         }
5299                         else
5300                         {
5301                                 if (c[conf])
5302                                         delete c[conf][sid];
5303
5304                                 if (!d[conf])
5305                                         d[conf] = { };
5306
5307                                 d[conf][sid] = true;
5308                         }
5309                 },
5310
5311                 ucisections: function(conf, cb)
5312                 {
5313                         var sa = [ ];
5314                         var pkg = this.uci.values[conf];
5315                         var crt = this.uci.creates[conf];
5316                         var del = this.uci.deletes[conf];
5317
5318                         if (!pkg)
5319                                 return sa;
5320
5321                         for (var s in pkg)
5322                                 if (!del || del[s] !== true)
5323                                         sa.push(pkg[s]);
5324
5325                         sa.sort(function(a, b) { return a['.index'] - b['.index'] });
5326
5327                         if (crt)
5328                                 for (var s in crt)
5329                                         sa.push(crt[s]);
5330
5331                         if (typeof(cb) == 'function')
5332                                 for (var i = 0; i < sa.length; i++)
5333                                         cb.apply(this, [ sa[i] ]);
5334
5335                         return sa;
5336                 },
5337
5338                 get: function(conf, sid, opt)
5339                 {
5340                         var v = this.uci.values;
5341                         var n = this.uci.creates;
5342                         var c = this.uci.changes;
5343                         var d = this.uci.deletes;
5344
5345                         /* requested option in a just created section */
5346                         if (sid.indexOf('.new.') == 0)
5347                         {
5348                                 if (!n[conf])
5349                                         return undefined;
5350
5351                                 if (typeof(opt) == 'undefined')
5352                                         return (n[conf][sid] || { });
5353
5354                                 return n[conf][sid][opt];
5355                         }
5356
5357                         /* requested an option value */
5358                         if (typeof(opt) != 'undefined')
5359                         {
5360                                 /* check whether option was deleted */
5361                                 if (d[conf] && d[conf][sid])
5362                                 {
5363                                         if (d[conf][sid] === true)
5364                                                 return undefined;
5365
5366                                         for (var i = 0; i < d[conf][sid].length; i++)
5367                                                 if (d[conf][sid][i] == opt)
5368                                                         return undefined;
5369                                 }
5370
5371                                 /* check whether option was changed */
5372                                 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
5373                                         return c[conf][sid][opt];
5374
5375                                 /* return base value */
5376                                 if (v[conf] && v[conf][sid])
5377                                         return v[conf][sid][opt];
5378
5379                                 return undefined;
5380                         }
5381
5382                         /* requested an entire section */
5383                         if (v[conf])
5384                                 return (v[conf][sid] || { });
5385
5386                         return undefined;
5387                 },
5388
5389                 set: function(conf, sid, opt, val)
5390                 {
5391                         var n = this.uci.creates;
5392                         var c = this.uci.changes;
5393                         var d = this.uci.deletes;
5394
5395                         if (sid.indexOf('.new.') == 0)
5396                         {
5397                                 if (n[conf] && n[conf][sid])
5398                                 {
5399                                         if (typeof(val) != 'undefined')
5400                                                 n[conf][sid][opt] = val;
5401                                         else
5402                                                 delete n[conf][sid][opt];
5403                                 }
5404                         }
5405                         else if (typeof(val) != 'undefined')
5406                         {
5407                                 if (!c[conf])
5408                                         c[conf] = { };
5409
5410                                 if (!c[conf][sid])
5411                                         c[conf][sid] = { };
5412
5413                                 c[conf][sid][opt] = val;
5414                         }
5415                         else
5416                         {
5417                                 if (!d[conf])
5418                                         d[conf] = { };
5419
5420                                 if (!d[conf][sid])
5421                                         d[conf][sid] = [ ];
5422
5423                                 d[conf][sid].push(opt);
5424                         }
5425                 },
5426
5427                 validate: function()
5428                 {
5429                         var rv = true;
5430
5431                         for (var i = 0; i < this.sections.length; i++)
5432                                 if (!this.sections[i].validate())
5433                                         rv = false;
5434
5435                         return rv;
5436                 },
5437
5438                 save: function()
5439                 {
5440                         if (this.options.readonly)
5441                                 return _luci2.deferrable();
5442
5443                         var deferreds = [ _luci2.deferrable(this.options.save()) ];
5444
5445                         for (var i = 0; i < this.sections.length; i++)
5446                         {
5447                                 if (this.sections[i].options.readonly)
5448                                         continue;
5449
5450                                 for (var f in this.sections[i].fields)
5451                                 {
5452                                         if (typeof(this.sections[i].fields[f].save) != 'function')
5453                                                 continue;
5454
5455                                         var s = this.sections[i].sections();
5456                                         for (var j = 0; j < s.length; j++)
5457                                         {
5458                                                 var rv = this.sections[i].fields[f].save(s[j]['.name']);
5459                                                 if (_luci2.isDeferred(rv))
5460                                                         deferreds.push(rv);
5461                                         }
5462                                 }
5463                         }
5464
5465                         return $.when.apply($, deferreds);
5466                 },
5467
5468                 send: function()
5469                 {
5470                         if (!this.validate())
5471                                 return _luci2.deferrable();
5472
5473                         var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
5474                                 _luci2.rpc.batch();
5475
5476                                 if (this.uci.creates)
5477                                         for (var c in this.uci.creates)
5478                                                 for (var s in this.uci.creates[c])
5479                                                 {
5480                                                         var r = {
5481                                                                 config: c,
5482                                                                 values: { }
5483                                                         };
5484
5485                                                         for (var k in this.uci.creates[c][s])
5486                                                         {
5487                                                                 if (k == '.type')
5488                                                                         r.type = this.uci.creates[c][s][k];
5489                                                                 else if (k == '.create')
5490                                                                         r.name = this.uci.creates[c][s][k];
5491                                                                 else if (k.charAt(0) != '.')
5492                                                                         r.values[k] = this.uci.creates[c][s][k];
5493                                                         }
5494
5495                                                         _luci2.uci.add(r.config, r.type, r.name, r.values);
5496                                                 }
5497
5498                                 if (this.uci.changes)
5499                                         for (var c in this.uci.changes)
5500                                                 for (var s in this.uci.changes[c])
5501                                                         _luci2.uci.set(c, s, this.uci.changes[c][s]);
5502
5503                                 if (this.uci.deletes)
5504                                         for (var c in this.uci.deletes)
5505                                                 for (var s in this.uci.deletes[c])
5506                                                 {
5507                                                         var o = this.uci.deletes[c][s];
5508                                                         _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
5509                                                 }
5510
5511                                 return _luci2.rpc.flush().then(function() {
5512                                         return _luci2.ui.updateChanges();
5513                                 });
5514                         }, this));
5515
5516                         var self = this;
5517
5518                         _luci2.ui.saveScrollTop();
5519                         _luci2.ui.loading(true);
5520
5521                         return this.save().then(send_cb).then(function() {
5522                                 return self.load();
5523                         }).then(function() {
5524                                 self.redraw();
5525                                 self = null;
5526
5527                                 _luci2.ui.loading(false);
5528                                 _luci2.ui.restoreScrollTop();
5529                         });
5530                 },
5531
5532                 dialog: function(id)
5533                 {
5534                         var d = $('<div />');
5535                         var p = $('<p />');
5536
5537                         $('<img />')
5538                                 .attr('src', _luci2.globals.resource + '/icons/loading.gif')
5539                                 .css('vertical-align', 'middle')
5540                                 .css('padding-right', '10px')
5541                                 .appendTo(p);
5542
5543                         p.append(_luci2.tr('Loading data...'));
5544
5545                         p.appendTo(d);
5546                         d.appendTo(id);
5547
5548                         return d.dialog({
5549                                 modal: true,
5550                                 draggable: false,
5551                                 resizable: false,
5552                                 height: 90,
5553                                 open: function() {
5554                                         $(this).parent().children('.ui-dialog-titlebar').hide();
5555                                 }
5556                         });
5557                 },
5558
5559                 insertInto: function(id)
5560                 {
5561                         var self = this;
5562                             self.target = $(id);
5563
5564                         _luci2.ui.loading(true);
5565                         self.target.hide();
5566
5567                         return self.load().then(function() {
5568                                 self.target.empty().append(self.render());
5569                                 self.finish();
5570                                 self.target.show();
5571                                 self = null;
5572                                 _luci2.ui.loading(false);
5573                         });
5574                 }
5575         });
5576 };