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