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