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