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