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