luci2: append markup for uci change indicator when rendering main menu
[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 = Class.extend;
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.length)
368                         location.hash = '#' + h;
369                 else
370                         location.hash = '';
371         };
372
373         this.getHash = function(key)
374         {
375                 var data = { };
376                 var tuples = (location.hash || '#').substring(1).split(/,/);
377
378                 for (var i = 0; i < tuples.length; i++)
379                 {
380                         var tuple = tuples[i].split(/:/);
381                         if (tuple.length == 2)
382                                 data[tuple[0]] = tuple[1];
383                 }
384
385                 if (typeof(key) != 'undefined')
386                         return data[key];
387
388                 return data;
389         };
390
391         this.toArray = function(x)
392         {
393                 switch (typeof(x))
394                 {
395                 case 'number':
396                 case 'boolean':
397                         return [ x ];
398
399                 case 'string':
400                         var r = [ ];
401                         var l = x.split(/\s+/);
402                         for (var i = 0; i < l.length; i++)
403                                 if (l[i].length > 0)
404                                         r.push(l[i]);
405                         return r;
406
407                 case 'object':
408                         if ($.isArray(x))
409                         {
410                                 var r = [ ];
411                                 for (var i = 0; i < x.length; i++)
412                                         r.push(x[i]);
413                                 return r;
414                         }
415                         else if ($.isPlainObject(x))
416                         {
417                                 var r = [ ];
418                                 for (var k in x)
419                                         if (x.hasOwnProperty(k))
420                                                 r.push(k);
421                                 return r.sort();
422                         }
423                 }
424
425                 return [ ];
426         };
427
428         this.toObject = function(x)
429         {
430                 switch (typeof(x))
431                 {
432                 case 'number':
433                 case 'boolean':
434                         return { x: true };
435
436                 case 'string':
437                         var r = { };
438                         var l = x.split(/\x+/);
439                         for (var i = 0; i < l.length; i++)
440                                 if (l[i].length > 0)
441                                         r[l[i]] = true;
442                         return r;
443
444                 case 'object':
445                         if ($.isArray(x))
446                         {
447                                 var r = { };
448                                 for (var i = 0; i < x.length; i++)
449                                         r[x[i]] = true;
450                                 return r;
451                         }
452                         else if ($.isPlainObject(x))
453                         {
454                                 return x;
455                         }
456                 }
457
458                 return { };
459         };
460
461         this.filterArray = function(array, item)
462         {
463                 if (!$.isArray(array))
464                         return [ ];
465
466                 for (var i = 0; i < array.length; i++)
467                         if (array[i] === item)
468                                 array.splice(i--, 1);
469
470                 return array;
471         };
472
473         this.toClassName = function(str, suffix)
474         {
475                 var n = '';
476                 var l = str.split(/[\/.]/);
477
478                 for (var i = 0; i < l.length; i++)
479                         if (l[i].length > 0)
480                                 n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
481
482                 if (typeof(suffix) == 'string')
483                         n += suffix;
484
485                 return n;
486         };
487
488         this.globals = {
489                 timeout:  15000,
490                 resource: '/luci2',
491                 sid:      '00000000000000000000000000000000'
492         };
493
494         this.rpc = {
495
496                 _id: 1,
497                 _batch: undefined,
498                 _requests: { },
499
500                 _call: function(req, cb)
501                 {
502                         return $.ajax('/ubus', {
503                                 cache:       false,
504                                 contentType: 'application/json',
505                                 data:        JSON.stringify(req),
506                                 dataType:    'json',
507                                 type:        'POST',
508                                 timeout:     _luci2.globals.timeout,
509                                 _rpc_req:   req
510                         }).then(cb, cb);
511                 },
512
513                 _list_cb: function(msg)
514                 {
515                         var list = msg.result;
516
517                         /* verify message frame */
518                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
519                                 list = [ ];
520
521                         return $.Deferred().resolveWith(this, [ list ]);
522                 },
523
524                 _call_cb: function(msg)
525                 {
526                         var data = [ ];
527                         var type = Object.prototype.toString;
528                         var reqs = this._rpc_req;
529
530                         if (!$.isArray(reqs))
531                         {
532                                 msg = [ msg ];
533                                 reqs = [ reqs ];
534                         }
535
536                         for (var i = 0; i < msg.length; i++)
537                         {
538                                 /* fetch related request info */
539                                 var req = _luci2.rpc._requests[reqs[i].id];
540                                 if (typeof(req) != 'object')
541                                         throw 'No related request for JSON response';
542
543                                 /* fetch response attribute and verify returned type */
544                                 var ret = undefined;
545
546                                 /* verify message frame */
547                                 if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
548                                         if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
549                                                 ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
550
551                                 if (req.expect)
552                                 {
553                                         for (var key in req.expect)
554                                         {
555                                                 if (typeof(ret) != 'undefined' && key != '')
556                                                         ret = ret[key];
557
558                                                 if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
559                                                         ret = req.expect[key];
560
561                                                 break;
562                                         }
563                                 }
564
565                                 /* apply filter */
566                                 if (typeof(req.filter) == 'function')
567                                 {
568                                         req.priv[0] = ret;
569                                         req.priv[1] = req.params;
570                                         ret = req.filter.apply(_luci2.rpc, req.priv);
571                                 }
572
573                                 /* store response data */
574                                 if (typeof(req.index) == 'number')
575                                         data[req.index] = ret;
576                                 else
577                                         data = ret;
578
579                                 /* delete request object */
580                                 delete _luci2.rpc._requests[reqs[i].id];
581                         }
582
583                         return $.Deferred().resolveWith(this, [ data ]);
584                 },
585
586                 list: function()
587                 {
588                         var params = [ ];
589                         for (var i = 0; i < arguments.length; i++)
590                                 params[i] = arguments[i];
591
592                         var msg = {
593                                 jsonrpc: '2.0',
594                                 id:      this._id++,
595                                 method:  'list',
596                                 params:  (params.length > 0) ? params : undefined
597                         };
598
599                         return this._call(msg, this._list_cb);
600                 },
601
602                 batch: function()
603                 {
604                         if (!$.isArray(this._batch))
605                                 this._batch = [ ];
606                 },
607
608                 flush: function()
609                 {
610                         if (!$.isArray(this._batch))
611                                 return _luci2.deferrable([ ]);
612
613                         var req = this._batch;
614                         delete this._batch;
615
616                         /* call rpc */
617                         return this._call(req, this._call_cb);
618                 },
619
620                 declare: function(options)
621                 {
622                         var _rpc = this;
623
624                         return function() {
625                                 /* build parameter object */
626                                 var p_off = 0;
627                                 var params = { };
628                                 if ($.isArray(options.params))
629                                         for (p_off = 0; p_off < options.params.length; p_off++)
630                                                 params[options.params[p_off]] = arguments[p_off];
631
632                                 /* all remaining arguments are private args */
633                                 var priv = [ undefined, undefined ];
634                                 for (; p_off < arguments.length; p_off++)
635                                         priv.push(arguments[p_off]);
636
637                                 /* store request info */
638                                 var req = _rpc._requests[_rpc._id] = {
639                                         expect: options.expect,
640                                         filter: options.filter,
641                                         params: params,
642                                         priv:   priv
643                                 };
644
645                                 /* build message object */
646                                 var msg = {
647                                         jsonrpc: '2.0',
648                                         id:      _rpc._id++,
649                                         method:  'call',
650                                         params:  [
651                                                 _luci2.globals.sid,
652                                                 options.object,
653                                                 options.method,
654                                                 params
655                                         ]
656                                 };
657
658                                 /* when a batch is in progress then store index in request data
659                                  * and push message object onto the stack */
660                                 if ($.isArray(_rpc._batch))
661                                 {
662                                         req.index = _rpc._batch.push(msg) - 1;
663                                         return _luci2.deferrable(msg);
664                                 }
665
666                                 /* call rpc */
667                                 return _rpc._call(msg, _rpc._call_cb);
668                         };
669                 }
670         };
671
672         this.UCIContext = Class.extend({
673
674                 init: function()
675                 {
676                         this.state = {
677                                 newid:   0,
678                                 values:  { },
679                                 creates: { },
680                                 changes: { },
681                                 deletes: { },
682                                 reorder: { }
683                         };
684                 },
685
686                 _load: _luci2.rpc.declare({
687                         object: 'uci',
688                         method: 'get',
689                         params: [ 'config' ],
690                         expect: { values: { } }
691                 }),
692
693                 _order: _luci2.rpc.declare({
694                         object: 'uci',
695                         method: 'order',
696                         params: [ 'config', 'sections' ]
697                 }),
698
699                 _add: _luci2.rpc.declare({
700                         object: 'uci',
701                         method: 'add',
702                         params: [ 'config', 'type', 'name', 'values' ],
703                         expect: { section: '' }
704                 }),
705
706                 _set: _luci2.rpc.declare({
707                         object: 'uci',
708                         method: 'set',
709                         params: [ 'config', 'section', 'values' ]
710                 }),
711
712                 _delete: _luci2.rpc.declare({
713                         object: 'uci',
714                         method: 'delete',
715                         params: [ 'config', 'section', 'options' ]
716                 }),
717
718                 load: function(packages)
719                 {
720                         var self = this;
721                         var seen = { };
722                         var pkgs = [ ];
723
724                         if (!$.isArray(packages))
725                                 packages = [ packages ];
726
727                         _luci2.rpc.batch();
728
729                         for (var i = 0; i < packages.length; i++)
730                                 if (!seen[packages[i]])
731                                 {
732                                         pkgs.push(packages[i]);
733                                         seen[packages[i]] = true;
734                                         self._load(packages[i]);
735                                 }
736
737                         return _luci2.rpc.flush().then(function(responses) {
738                                 for (var i = 0; i < responses.length; i++)
739                                         self.state.values[pkgs[i]] = responses[i];
740
741                                 return pkgs;
742                         });
743                 },
744
745                 unload: function(packages)
746                 {
747                         if (!$.isArray(packages))
748                                 packages = [ packages ];
749
750                         for (var i = 0; i < packages.length; i++)
751                         {
752                                 delete this.state.values[packages[i]];
753                                 delete this.state.creates[packages[i]];
754                                 delete this.state.changes[packages[i]];
755                                 delete this.state.deletes[packages[i]];
756                         }
757                 },
758
759                 add: function(conf, type, name)
760                 {
761                         var c = this.state.creates;
762                         var s = '.new.%d'.format(this.state.newid++);
763
764                         if (!c[conf])
765                                 c[conf] = { };
766
767                         c[conf][s] = {
768                                 '.type':      type,
769                                 '.name':      s,
770                                 '.create':    name,
771                                 '.anonymous': !name,
772                                 '.index':     1000 + this.state.newid
773                         };
774
775                         return s;
776                 },
777
778                 remove: function(conf, sid)
779                 {
780                         var n = this.state.creates;
781                         var c = this.state.changes;
782                         var d = this.state.deletes;
783
784                         /* requested deletion of a just created section */
785                         if (sid.indexOf('.new.') == 0)
786                         {
787                                 if (n[conf])
788                                         delete n[conf][sid];
789                         }
790                         else
791                         {
792                                 if (c[conf])
793                                         delete c[conf][sid];
794
795                                 if (!d[conf])
796                                         d[conf] = { };
797
798                                 d[conf][sid] = true;
799                         }
800                 },
801
802                 sections: function(conf, type, cb)
803                 {
804                         var sa = [ ];
805                         var v = this.state.values[conf];
806                         var n = this.state.creates[conf];
807                         var c = this.state.changes[conf];
808                         var d = this.state.deletes[conf];
809
810                         if (!v)
811                                 return sa;
812
813                         for (var s in v)
814                                 if (!d || d[s] !== true)
815                                         if (!type || v[s]['.type'] == type)
816                                                 sa.push($.extend({ }, v[s], c ? c[s] : undefined));
817
818                         if (n)
819                                 for (var s in n)
820                                         if (!type || n[s]['.type'] == type)
821                                                 sa.push(n[s]);
822
823                         sa.sort(function(a, b) {
824                                 return a['.index'] - b['.index'];
825                         });
826
827                         for (var i = 0; i < sa.length; i++)
828                                 sa[i]['.index'] = i;
829
830                         if (typeof(cb) == 'function')
831                                 for (var i = 0; i < sa.length; i++)
832                                         cb.call(this, sa[i], sa[i]['.name']);
833
834                         return sa;
835                 },
836
837                 get: function(conf, sid, opt)
838                 {
839                         var v = this.state.values;
840                         var n = this.state.creates;
841                         var c = this.state.changes;
842                         var d = this.state.deletes;
843
844                         if (typeof(sid) == 'undefined')
845                                 return undefined;
846
847                         /* requested option in a just created section */
848                         if (sid.indexOf('.new.') == 0)
849                         {
850                                 if (!n[conf])
851                                         return undefined;
852
853                                 if (typeof(opt) == 'undefined')
854                                         return n[conf][sid];
855
856                                 return n[conf][sid][opt];
857                         }
858
859                         /* requested an option value */
860                         if (typeof(opt) != 'undefined')
861                         {
862                                 /* check whether option was deleted */
863                                 if (d[conf] && d[conf][sid])
864                                 {
865                                         if (d[conf][sid] === true)
866                                                 return undefined;
867
868                                         for (var i = 0; i < d[conf][sid].length; i++)
869                                                 if (d[conf][sid][i] == opt)
870                                                         return undefined;
871                                 }
872
873                                 /* check whether option was changed */
874                                 if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
875                                         return c[conf][sid][opt];
876
877                                 /* return base value */
878                                 if (v[conf] && v[conf][sid])
879                                         return v[conf][sid][opt];
880
881                                 return undefined;
882                         }
883
884                         /* requested an entire section */
885                         if (v[conf])
886                                 return v[conf][sid];
887
888                         return undefined;
889                 },
890
891                 set: function(conf, sid, opt, val)
892                 {
893                         var n = this.state.creates;
894                         var c = this.state.changes;
895                         var d = this.state.deletes;
896
897                         if (typeof(sid) == 'undefined' ||
898                             typeof(opt) == 'undefined' ||
899                             opt.charAt(0) == '.')
900                                 return;
901
902                         if (sid.indexOf('.new.') == 0)
903                         {
904                                 if (n[conf] && n[conf][sid])
905                                 {
906                                         if (typeof(val) != 'undefined')
907                                                 n[conf][sid][opt] = val;
908                                         else
909                                                 delete n[conf][sid][opt];
910                                 }
911                         }
912                         else if (typeof(val) != 'undefined')
913                         {
914                                 /* do not set within deleted section */
915                                 if (d[conf] && d[conf][sid] === true)
916                                         return;
917
918                                 if (!c[conf])
919                                         c[conf] = { };
920
921                                 if (!c[conf][sid])
922                                         c[conf][sid] = { };
923
924                                 /* undelete option */
925                                 if (d[conf] && d[conf][sid])
926                                         d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
927
928                                 c[conf][sid][opt] = val;
929                         }
930                         else
931                         {
932                                 if (!d[conf])
933                                         d[conf] = { };
934
935                                 if (!d[conf][sid])
936                                         d[conf][sid] = [ ];
937
938                                 if (d[conf][sid] !== true)
939                                         d[conf][sid].push(opt);
940                         }
941                 },
942
943                 unset: function(conf, sid, opt)
944                 {
945                         return this.set(conf, sid, opt, undefined);
946                 },
947
948                 _reload: function()
949                 {
950                         var pkgs = [ ];
951
952                         for (var pkg in this.state.values)
953                                 pkgs.push(pkg);
954
955                         this.init();
956
957                         return this.load(pkgs);
958                 },
959
960                 _reorder: function()
961                 {
962                         var v = this.state.values;
963                         var n = this.state.creates;
964                         var r = this.state.reorder;
965
966                         if ($.isEmptyObject(r))
967                                 return _luci2.deferrable();
968
969                         _luci2.rpc.batch();
970
971                         /*
972                          gather all created and existing sections, sort them according
973                          to their index value and issue an uci order call
974                         */
975                         for (var c in r)
976                         {
977                                 var o = [ ];
978
979                                 if (n && n[c])
980                                         for (var s in n[c])
981                                                 o.push(n[c][s]);
982
983                                 for (var s in v[c])
984                                         o.push(v[c][s]);
985
986                                 if (o.length > 0)
987                                 {
988                                         o.sort(function(a, b) {
989                                                 return (a['.index'] - b['.index']);
990                                         });
991
992                                         var sids = [ ];
993
994                                         for (var i = 0; i < o.length; i++)
995                                                 sids.push(o[i]['.name']);
996
997                                         this._order(c, sids);
998                                 }
999                         }
1000
1001                         this.state.reorder = { };
1002                         return _luci2.rpc.flush();
1003                 },
1004
1005                 swap: function(conf, sid1, sid2)
1006                 {
1007                         var s1 = this.get(conf, sid1);
1008                         var s2 = this.get(conf, sid2);
1009                         var n1 = s1 ? s1['.index'] : NaN;
1010                         var n2 = s2 ? s2['.index'] : NaN;
1011
1012                         if (isNaN(n1) || isNaN(n2))
1013                                 return false;
1014
1015                         s1['.index'] = n2;
1016                         s2['.index'] = n1;
1017
1018                         this.state.reorder[conf] = true;
1019
1020                         return true;
1021                 },
1022
1023                 save: function()
1024                 {
1025                         _luci2.rpc.batch();
1026
1027                         var self = this;
1028                         var snew = [ ];
1029
1030                         if (self.state.creates)
1031                                 for (var c in self.state.creates)
1032                                         for (var s in self.state.creates[c])
1033                                         {
1034                                                 var r = {
1035                                                         config: c,
1036                                                         values: { }
1037                                                 };
1038
1039                                                 for (var k in self.state.creates[c][s])
1040                                                 {
1041                                                         if (k == '.type')
1042                                                                 r.type = self.state.creates[c][s][k];
1043                                                         else if (k == '.create')
1044                                                                 r.name = self.state.creates[c][s][k];
1045                                                         else if (k.charAt(0) != '.')
1046                                                                 r.values[k] = self.state.creates[c][s][k];
1047                                                 }
1048
1049                                                 snew.push(self.state.creates[c][s]);
1050
1051                                                 self._add(r.config, r.type, r.name, r.values);
1052                                         }
1053
1054                         if (self.state.changes)
1055                                 for (var c in self.state.changes)
1056                                         for (var s in self.state.changes[c])
1057                                                 self._set(c, s, self.state.changes[c][s]);
1058
1059                         if (self.state.deletes)
1060                                 for (var c in self.state.deletes)
1061                                         for (var s in self.state.deletes[c])
1062                                         {
1063                                                 var o = self.state.deletes[c][s];
1064                                                 self._delete(c, s, (o === true) ? undefined : o);
1065                                         }
1066
1067                         return _luci2.rpc.flush().then(function(responses) {
1068                                 /*
1069                                  array "snew" holds references to the created uci sections,
1070                                  use it to assign the returned names of the new sections
1071                                 */
1072                                 for (var i = 0; i < snew.length; i++)
1073                                         snew[i]['.name'] = responses[i];
1074
1075                                 return self._reorder();
1076                         });
1077                 },
1078
1079                 _apply: _luci2.rpc.declare({
1080                         object: 'uci',
1081                         method: 'apply',
1082                         params: [ 'timeout', 'rollback' ]
1083                 }),
1084
1085                 _confirm: _luci2.rpc.declare({
1086                         object: 'uci',
1087                         method: 'confirm'
1088                 }),
1089
1090                 apply: function(timeout)
1091                 {
1092                         var self = this;
1093                         var date = new Date();
1094                         var deferred = $.Deferred();
1095
1096                         if (typeof(timeout) != 'number' || timeout < 1)
1097                                 timeout = 10;
1098
1099                         self._apply(timeout, true).then(function(rv) {
1100                                 if (rv != 0)
1101                                 {
1102                                         deferred.rejectWith(self, [ rv ]);
1103                                         return;
1104                                 }
1105
1106                                 var try_deadline = date.getTime() + 1000 * timeout;
1107                                 var try_confirm = function()
1108                                 {
1109                                         return self._confirm().then(function(rv) {
1110                                                 if (rv != 0)
1111                                                 {
1112                                                         if (date.getTime() < try_deadline)
1113                                                                 window.setTimeout(try_confirm, 250);
1114                                                         else
1115                                                                 deferred.rejectWith(self, [ rv ]);
1116
1117                                                         return;
1118                                                 }
1119
1120                                                 deferred.resolveWith(self, [ rv ]);
1121                                         });
1122                                 };
1123
1124                                 window.setTimeout(try_confirm, 1000);
1125                         });
1126
1127                         return deferred;
1128                 },
1129
1130                 changes: _luci2.rpc.declare({
1131                         object: 'uci',
1132                         method: 'changes',
1133                         expect: { changes: { } }
1134                 }),
1135
1136                 readable: function(conf)
1137                 {
1138                         return _luci2.session.hasACL('uci', conf, 'read');
1139                 },
1140
1141                 writable: function(conf)
1142                 {
1143                         return _luci2.session.hasACL('uci', conf, 'write');
1144                 }
1145         });
1146
1147         this.uci = new this.UCIContext();
1148
1149         this.wireless = {
1150                 listDeviceNames: _luci2.rpc.declare({
1151                         object: 'iwinfo',
1152                         method: 'devices',
1153                         expect: { 'devices': [ ] },
1154                         filter: function(data) {
1155                                 data.sort();
1156                                 return data;
1157                         }
1158                 }),
1159
1160                 getDeviceStatus: _luci2.rpc.declare({
1161                         object: 'iwinfo',
1162                         method: 'info',
1163                         params: [ 'device' ],
1164                         expect: { '': { } },
1165                         filter: function(data, params) {
1166                                 if (!$.isEmptyObject(data))
1167                                 {
1168                                         data['device'] = params['device'];
1169                                         return data;
1170                                 }
1171                                 return undefined;
1172                         }
1173                 }),
1174
1175                 getAssocList: _luci2.rpc.declare({
1176                         object: 'iwinfo',
1177                         method: 'assoclist',
1178                         params: [ 'device' ],
1179                         expect: { results: [ ] },
1180                         filter: function(data, params) {
1181                                 for (var i = 0; i < data.length; i++)
1182                                         data[i]['device'] = params['device'];
1183
1184                                 data.sort(function(a, b) {
1185                                         if (a.bssid < b.bssid)
1186                                                 return -1;
1187                                         else if (a.bssid > b.bssid)
1188                                                 return 1;
1189                                         else
1190                                                 return 0;
1191                                 });
1192
1193                                 return data;
1194                         }
1195                 }),
1196
1197                 getWirelessStatus: function() {
1198                         return this.listDeviceNames().then(function(names) {
1199                                 _luci2.rpc.batch();
1200
1201                                 for (var i = 0; i < names.length; i++)
1202                                         _luci2.wireless.getDeviceStatus(names[i]);
1203
1204                                 return _luci2.rpc.flush();
1205                         }).then(function(networks) {
1206                                 var rv = { };
1207
1208                                 var phy_attrs = [
1209                                         'country', 'channel', 'frequency', 'frequency_offset',
1210                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1211                                 ];
1212
1213                                 var net_attrs = [
1214                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1215                                         'signal', 'noise', 'bitrate', 'encryption'
1216                                 ];
1217
1218                                 for (var i = 0; i < networks.length; i++)
1219                                 {
1220                                         var phy = rv[networks[i].phy] || (
1221                                                 rv[networks[i].phy] = { networks: [ ] }
1222                                         );
1223
1224                                         var net = {
1225                                                 device: networks[i].device
1226                                         };
1227
1228                                         for (var j = 0; j < phy_attrs.length; j++)
1229                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1230
1231                                         for (var j = 0; j < net_attrs.length; j++)
1232                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1233
1234                                         phy.networks.push(net);
1235                                 }
1236
1237                                 return rv;
1238                         });
1239                 },
1240
1241                 getAssocLists: function()
1242                 {
1243                         return this.listDeviceNames().then(function(names) {
1244                                 _luci2.rpc.batch();
1245
1246                                 for (var i = 0; i < names.length; i++)
1247                                         _luci2.wireless.getAssocList(names[i]);
1248
1249                                 return _luci2.rpc.flush();
1250                         }).then(function(assoclists) {
1251                                 var rv = [ ];
1252
1253                                 for (var i = 0; i < assoclists.length; i++)
1254                                         for (var j = 0; j < assoclists[i].length; j++)
1255                                                 rv.push(assoclists[i][j]);
1256
1257                                 return rv;
1258                         });
1259                 },
1260
1261                 formatEncryption: function(enc)
1262                 {
1263                         var format_list = function(l, s)
1264                         {
1265                                 var rv = [ ];
1266                                 for (var i = 0; i < l.length; i++)
1267                                         rv.push(l[i].toUpperCase());
1268                                 return rv.join(s ? s : ', ');
1269                         }
1270
1271                         if (!enc || !enc.enabled)
1272                                 return _luci2.tr('None');
1273
1274                         if (enc.wep)
1275                         {
1276                                 if (enc.wep.length == 2)
1277                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1278                                 else if (enc.wep[0] == 'shared')
1279                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1280                                 else
1281                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1282                         }
1283                         else if (enc.wpa)
1284                         {
1285                                 if (enc.wpa.length == 2)
1286                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1287                                                 format_list(enc.authentication, '/'),
1288                                                 format_list(enc.ciphers, ', ')
1289                                         );
1290                                 else if (enc.wpa[0] == 2)
1291                                         return 'WPA2 %s (%s)'.format(
1292                                                 format_list(enc.authentication, '/'),
1293                                                 format_list(enc.ciphers, ', ')
1294                                         );
1295                                 else
1296                                         return 'WPA %s (%s)'.format(
1297                                                 format_list(enc.authentication, '/'),
1298                                                 format_list(enc.ciphers, ', ')
1299                                         );
1300                         }
1301
1302                         return _luci2.tr('Unknown');
1303                 }
1304         };
1305
1306         this.firewall = {
1307                 getZoneColor: function(zone)
1308                 {
1309                         if ($.isPlainObject(zone))
1310                                 zone = zone.name;
1311
1312                         if (zone == 'lan')
1313                                 return '#90f090';
1314                         else if (zone == 'wan')
1315                                 return '#f09090';
1316
1317                         for (var i = 0, hash = 0;
1318                                  i < zone.length;
1319                                  hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
1320
1321                         for (var i = 0, color = '#';
1322                                  i < 3;
1323                                  color += ('00' + ((hash >> i++ * 8) & 0xFF).tostring(16)).slice(-2));
1324
1325                         return color;
1326                 },
1327
1328                 findZoneByNetwork: function(network)
1329                 {
1330                         var self = this;
1331                         var zone = undefined;
1332
1333                         return _luci2.uci.sections('firewall', 'zone', function(z) {
1334                                 if (!z.name || !z.network)
1335                                         return;
1336
1337                                 if (!$.isArray(z.network))
1338                                         z.network = z.network.split(/\s+/);
1339
1340                                 for (var i = 0; i < z.network.length; i++)
1341                                 {
1342                                         if (z.network[i] == network)
1343                                         {
1344                                                 zone = z;
1345                                                 break;
1346                                         }
1347                                 }
1348                         }).then(function() {
1349                                 if (zone)
1350                                         zone.color = self.getZoneColor(zone);
1351
1352                                 return zone;
1353                         });
1354                 }
1355         };
1356
1357         this.NetworkModel = {
1358                 _device_blacklist: [
1359                         /^gre[0-9]+$/,
1360                         /^gretap[0-9]+$/,
1361                         /^ifb[0-9]+$/,
1362                         /^ip6tnl[0-9]+$/,
1363                         /^sit[0-9]+$/,
1364                         /^wlan[0-9]+\.sta[0-9]+$/
1365                 ],
1366
1367                 _cache_functions: [
1368                         'protolist', 0, _luci2.rpc.declare({
1369                                 object: 'network',
1370                                 method: 'get_proto_handlers',
1371                                 expect: { '': { } }
1372                         }),
1373                         'ifstate', 1, _luci2.rpc.declare({
1374                                 object: 'network.interface',
1375                                 method: 'dump',
1376                                 expect: { 'interface': [ ] }
1377                         }),
1378                         'devstate', 2, _luci2.rpc.declare({
1379                                 object: 'network.device',
1380                                 method: 'status',
1381                                 expect: { '': { } }
1382                         }),
1383                         'wifistate', 0, _luci2.rpc.declare({
1384                                 object: 'network.wireless',
1385                                 method: 'status',
1386                                 expect: { '': { } }
1387                         }),
1388                         'bwstate', 2, _luci2.rpc.declare({
1389                                 object: 'luci2.network.bwmon',
1390                                 method: 'statistics',
1391                                 expect: { 'statistics': { } }
1392                         }),
1393                         'devlist', 2, _luci2.rpc.declare({
1394                                 object: 'luci2.network',
1395                                 method: 'device_list',
1396                                 expect: { 'devices': [ ] }
1397                         }),
1398                         'swlist', 0, _luci2.rpc.declare({
1399                                 object: 'luci2.network',
1400                                 method: 'switch_list',
1401                                 expect: { 'switches': [ ] }
1402                         })
1403                 ],
1404
1405                 _fetch_protocol: function(proto)
1406                 {
1407                         var url = _luci2.globals.resource + '/proto/' + proto + '.js';
1408                         var self = _luci2.NetworkModel;
1409
1410                         var def = $.Deferred();
1411
1412                         $.ajax(url, {
1413                                 method: 'GET',
1414                                 cache: true,
1415                                 dataType: 'text'
1416                         }).then(function(data) {
1417                                 try {
1418                                         var protoConstructorSource = (
1419                                                 '(function(L, $) { ' +
1420                                                         'return %s' +
1421                                                 '})(_luci2, $);\n\n' +
1422                                                 '//@ sourceURL=%s'
1423                                         ).format(data, url);
1424
1425                                         var protoClass = eval(protoConstructorSource);
1426
1427                                         self._protos[proto] = new protoClass();
1428                                 }
1429                                 catch(e) {
1430                                         alert('Unable to instantiate proto "%s": %s'.format(url, e));
1431                                 };
1432
1433                                 def.resolve();
1434                         }).fail(function() {
1435                                 def.resolve();
1436                         });
1437
1438                         return def;
1439                 },
1440
1441                 _fetch_protocols: function()
1442                 {
1443                         var self = _luci2.NetworkModel;
1444                         var deferreds = [ ];
1445
1446                         for (var proto in self._cache.protolist)
1447                                 deferreds.push(self._fetch_protocol(proto));
1448
1449                         return $.when.apply($, deferreds);
1450                 },
1451
1452                 _fetch_swstate: _luci2.rpc.declare({
1453                         object: 'luci2.network',
1454                         method: 'switch_info',
1455                         params: [ 'switch' ],
1456                         expect: { 'info': { } }
1457                 }),
1458
1459                 _fetch_swstate_cb: function(responses) {
1460                         var self = _luci2.NetworkModel;
1461                         var swlist = self._cache.swlist;
1462                         var swstate = self._cache.swstate = { };
1463
1464                         for (var i = 0; i < responses.length; i++)
1465                                 swstate[swlist[i]] = responses[i];
1466                 },
1467
1468                 _fetch_cache_cb: function(level)
1469                 {
1470                         var self = _luci2.NetworkModel;
1471                         var name = '_fetch_cache_cb_' + level;
1472
1473                         return self[name] || (
1474                                 self[name] = function(responses)
1475                                 {
1476                                         for (var i = 0; i < self._cache_functions.length; i += 3)
1477                                                 if (!level || self._cache_functions[i + 1] == level)
1478                                                         self._cache[self._cache_functions[i]] = responses.shift();
1479
1480                                         if (!level)
1481                                         {
1482                                                 _luci2.rpc.batch();
1483
1484                                                 for (var i = 0; i < self._cache.swlist.length; i++)
1485                                                         self._fetch_swstate(self._cache.swlist[i]);
1486
1487                                                 return _luci2.rpc.flush().then(self._fetch_swstate_cb);
1488                                         }
1489
1490                                         return _luci2.deferrable();
1491                                 }
1492                         );
1493                 },
1494
1495                 _fetch_cache: function(level)
1496                 {
1497                         var self = _luci2.NetworkModel;
1498
1499                         return _luci2.uci.load(['network', 'wireless']).then(function() {
1500                                 _luci2.rpc.batch();
1501
1502                                 for (var i = 0; i < self._cache_functions.length; i += 3)
1503                                         if (!level || self._cache_functions[i + 1] == level)
1504                                                 self._cache_functions[i + 2]();
1505
1506                                 return _luci2.rpc.flush().then(self._fetch_cache_cb(level || 0));
1507                         });
1508                 },
1509
1510                 _get: function(pkg, sid, key)
1511                 {
1512                         return _luci2.uci.get(pkg, sid, key);
1513                 },
1514
1515                 _set: function(pkg, sid, key, val)
1516                 {
1517                         return _luci2.uci.set(pkg, sid, key, val);
1518                 },
1519
1520                 _is_blacklisted: function(dev)
1521                 {
1522                         for (var i = 0; i < this._device_blacklist.length; i++)
1523                                 if (dev.match(this._device_blacklist[i]))
1524                                         return true;
1525
1526                         return false;
1527                 },
1528
1529                 _sort_devices: function(a, b)
1530                 {
1531                         if (a.options.kind < b.options.kind)
1532                                 return -1;
1533                         else if (a.options.kind > b.options.kind)
1534                                 return 1;
1535
1536                         if (a.options.name < b.options.name)
1537                                 return -1;
1538                         else if (a.options.name > b.options.name)
1539                                 return 1;
1540
1541                         return 0;
1542                 },
1543
1544                 _get_dev: function(ifname)
1545                 {
1546                         var alias = (ifname.charAt(0) == '@');
1547                         return this._devs[ifname] || (
1548                                 this._devs[ifname] = {
1549                                         ifname:  ifname,
1550                                         kind:    alias ? 'alias' : 'ethernet',
1551                                         type:    alias ? 0 : 1,
1552                                         up:      false,
1553                                         changed: { }
1554                                 }
1555                         );
1556                 },
1557
1558                 _get_iface: function(name)
1559                 {
1560                         return this._ifaces[name] || (
1561                                 this._ifaces[name] = {
1562                                         name:    name,
1563                                         proto:   this._protos.none,
1564                                         changed: { }
1565                                 }
1566                         );
1567                 },
1568
1569                 _parse_devices: function()
1570                 {
1571                         var self = _luci2.NetworkModel;
1572                         var wificount = { };
1573
1574                         for (var ifname in self._cache.devstate)
1575                         {
1576                                 if (self._is_blacklisted(ifname))
1577                                         continue;
1578
1579                                 var dev = self._cache.devstate[ifname];
1580                                 var entry = self._get_dev(ifname);
1581
1582                                 entry.up = dev.up;
1583
1584                                 switch (dev.type)
1585                                 {
1586                                 case 'IP tunnel':
1587                                         entry.kind = 'tunnel';
1588                                         break;
1589
1590                                 case 'Bridge':
1591                                         entry.kind = 'bridge';
1592                                         //entry.ports = dev['bridge-members'].sort();
1593                                         break;
1594                                 }
1595                         }
1596
1597                         for (var i = 0; i < self._cache.devlist.length; i++)
1598                         {
1599                                 var dev = self._cache.devlist[i];
1600
1601                                 if (self._is_blacklisted(dev.device))
1602                                         continue;
1603
1604                                 var entry = self._get_dev(dev.device);
1605
1606                                 entry.up   = dev.is_up;
1607                                 entry.type = dev.type;
1608
1609                                 switch (dev.type)
1610                                 {
1611                                 case 1: /* Ethernet */
1612                                         if (dev.is_bridge)
1613                                                 entry.kind = 'bridge';
1614                                         else if (dev.is_tuntap)
1615                                                 entry.kind = 'tunnel';
1616                                         else if (dev.is_wireless)
1617                                                 entry.kind = 'wifi';
1618                                         break;
1619
1620                                 case 512: /* PPP */
1621                                 case 768: /* IP-IP Tunnel */
1622                                 case 769: /* IP6-IP6 Tunnel */
1623                                 case 776: /* IPv6-in-IPv4 */
1624                                 case 778: /* GRE over IP */
1625                                         entry.kind = 'tunnel';
1626                                         break;
1627                                 }
1628                         }
1629
1630                         var net = _luci2.uci.sections('network');
1631                         for (var i = 0; i < net.length; i++)
1632                         {
1633                                 var s = net[i];
1634                                 var sid = s['.name'];
1635
1636                                 if (s['.type'] == 'device' && s.name)
1637                                 {
1638                                         var entry = self._get_dev(s.name);
1639
1640                                         switch (s.type)
1641                                         {
1642                                         case 'macvlan':
1643                                         case 'tunnel':
1644                                                 entry.kind = 'tunnel';
1645                                                 break;
1646                                         }
1647
1648                                         entry.sid = sid;
1649                                 }
1650                                 else if (s['.type'] == 'interface' && !s['.anonymous'] && s.ifname)
1651                                 {
1652                                         var ifnames = _luci2.toArray(s.ifname);
1653
1654                                         for (var j = 0; j < ifnames.length; j++)
1655                                                 self._get_dev(ifnames[j]);
1656
1657                                         if (s['.name'] != 'loopback')
1658                                         {
1659                                                 var entry = self._get_dev('@%s'.format(s['.name']));
1660
1661                                                 entry.type = 0;
1662                                                 entry.kind = 'alias';
1663                                                 entry.sid  = sid;
1664                                         }
1665                                 }
1666                                 else if (s['.type'] == 'switch_vlan' && s.device)
1667                                 {
1668                                         var sw = self._cache.swstate[s.device];
1669                                         var vid = parseInt(s.vid || s.vlan);
1670                                         var ports = _luci2.toArray(s.ports);
1671
1672                                         if (!sw || !ports.length || isNaN(vid))
1673                                                 continue;
1674
1675                                         var ifname = undefined;
1676
1677                                         for (var j = 0; j < ports.length; j++)
1678                                         {
1679                                                 var port = parseInt(ports[j]);
1680                                                 var tag = (ports[j].replace(/[^tu]/g, '') == 't');
1681
1682                                                 if (port == sw.cpu_port)
1683                                                 {
1684                                                         // XXX: need a way to map switch to netdev
1685                                                         if (tag)
1686                                                                 ifname = 'eth0.%d'.format(vid);
1687                                                         else
1688                                                                 ifname = 'eth0';
1689
1690                                                         break;
1691                                                 }
1692                                         }
1693
1694                                         if (!ifname)
1695                                                 continue;
1696
1697                                         var entry = self._get_dev(ifname);
1698
1699                                         entry.kind = 'vlan';
1700                                         entry.sid  = sid;
1701                                         entry.vsw  = sw;
1702                                         entry.vid  = vid;
1703                                 }
1704                         }
1705
1706                         var wifi = _luci2.uci.sections('wireless');
1707                         for (var i = 0; i < wifi.length; i++)
1708                         {
1709                                 var s = wifi[i];
1710                                 var sid = s['.name'];
1711
1712                                 if (s['.type'] == 'wifi-iface' && s.device)
1713                                 {
1714                                         var r = parseInt(s.device.replace(/^[^0-9]+/, ''));
1715                                         var n = wificount[s.device] = (wificount[s.device] || 0) + 1;
1716                                         var id = 'radio%d.network%d'.format(r, n);
1717                                         var ifname = id;
1718
1719                                         if (self._cache.wifistate[s.device])
1720                                         {
1721                                                 var ifcs = self._cache.wifistate[s.device].interfaces;
1722                                                 for (var ifc in ifcs)
1723                                                 {
1724                                                         if (ifcs[ifc].section == sid)
1725                                                         {
1726                                                                 ifname = ifcs[ifc].ifname;
1727                                                                 break;
1728                                                         }
1729                                                 }
1730                                         }
1731
1732                                         var entry = self._get_dev(ifname);
1733
1734                                         entry.kind   = 'wifi';
1735                                         entry.sid    = sid;
1736                                         entry.wid    = id;
1737                                         entry.wdev   = s.device;
1738                                         entry.wmode  = s.mode;
1739                                         entry.wssid  = s.ssid;
1740                                         entry.wbssid = s.bssid;
1741                                 }
1742                         }
1743
1744                         for (var i = 0; i < net.length; i++)
1745                         {
1746                                 var s = net[i];
1747                                 var sid = s['.name'];
1748
1749                                 if (s['.type'] == 'interface' && !s['.anonymous'] && s.type == 'bridge')
1750                                 {
1751                                         var ifnames = _luci2.toArray(s.ifname);
1752
1753                                         for (var ifname in self._devs)
1754                                         {
1755                                                 var dev = self._devs[ifname];
1756
1757                                                 if (dev.kind != 'wifi')
1758                                                         continue;
1759
1760                                                 var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
1761                                                 if ($.inArray(sid, wnets) > -1)
1762                                                         ifnames.push(ifname);
1763                                         }
1764
1765                                         entry = self._get_dev('br-%s'.format(s['.name']));
1766                                         entry.type  = 1;
1767                                         entry.kind  = 'bridge';
1768                                         entry.sid   = sid;
1769                                         entry.ports = ifnames.sort();
1770                                 }
1771                         }
1772                 },
1773
1774                 _parse_interfaces: function()
1775                 {
1776                         var self = _luci2.NetworkModel;
1777                         var net = _luci2.uci.sections('network');
1778
1779                         for (var i = 0; i < net.length; i++)
1780                         {
1781                                 var s = net[i];
1782                                 var sid = s['.name'];
1783
1784                                 if (s['.type'] == 'interface' && !s['.anonymous'] && s.proto)
1785                                 {
1786                                         var entry = self._get_iface(s['.name']);
1787                                         var proto = self._protos[s.proto] || self._protos.none;
1788
1789                                         var l3dev = undefined;
1790                                         var l2dev = undefined;
1791
1792                                         var ifnames = _luci2.toArray(s.ifname);
1793
1794                                         for (var ifname in self._devs)
1795                                         {
1796                                                 var dev = self._devs[ifname];
1797
1798                                                 if (dev.kind != 'wifi')
1799                                                         continue;
1800
1801                                                 var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
1802                                                 if ($.inArray(entry.name, wnets) > -1)
1803                                                         ifnames.push(ifname);
1804                                         }
1805
1806                                         if (proto.virtual)
1807                                                 l3dev = '%s-%s'.format(s.proto, entry.name);
1808                                         else if (s.type == 'bridge')
1809                                                 l3dev = 'br-%s'.format(entry.name);
1810                                         else
1811                                                 l3dev = ifnames[0];
1812
1813                                         if (!proto.virtual && s.type == 'bridge')
1814                                                 l2dev = 'br-%s'.format(entry.name);
1815                                         else if (!proto.virtual)
1816                                                 l2dev = ifnames[0];
1817
1818                                         entry.proto = proto;
1819                                         entry.sid   = sid;
1820                                         entry.l3dev = l3dev;
1821                                         entry.l2dev = l2dev;
1822                                 }
1823                         }
1824
1825                         for (var i = 0; i < self._cache.ifstate.length; i++)
1826                         {
1827                                 var iface = self._cache.ifstate[i];
1828                                 var entry = self._get_iface(iface['interface']);
1829                                 var proto = self._protos[iface.proto] || self._protos.none;
1830
1831                                 /* this is a virtual interface, either deleted from config but
1832                                    not applied yet or set up from external tools (6rd) */
1833                                 if (!entry.sid)
1834                                 {
1835                                         entry.proto = proto;
1836                                         entry.l2dev = iface.device;
1837                                         entry.l3dev = iface.l3_device;
1838                                 }
1839                         }
1840                 },
1841
1842                 init: function()
1843                 {
1844                         var self = this;
1845
1846                         if (self._cache)
1847                                 return _luci2.deferrable();
1848
1849                         self._cache  = { };
1850                         self._devs   = { };
1851                         self._ifaces = { };
1852                         self._protos = { };
1853
1854                         return self._fetch_cache()
1855                                 .then(self._fetch_protocols)
1856                                 .then(self._parse_devices)
1857                                 .then(self._parse_interfaces);
1858                 },
1859
1860                 update: function()
1861                 {
1862                         delete this._cache;
1863                         return this.init();
1864                 },
1865
1866                 refreshInterfaceStatus: function()
1867                 {
1868                         return this._fetch_cache(1).then(this._parse_interfaces);
1869                 },
1870
1871                 refreshDeviceStatus: function()
1872                 {
1873                         return this._fetch_cache(2).then(this._parse_devices);
1874                 },
1875
1876                 refreshStatus: function()
1877                 {
1878                         return this._fetch_cache(1)
1879                                 .then(this._fetch_cache(2))
1880                                 .then(this._parse_devices)
1881                                 .then(this._parse_interfaces);
1882                 },
1883
1884                 getDevices: function()
1885                 {
1886                         var devs = [ ];
1887
1888                         for (var ifname in this._devs)
1889                                 if (ifname != 'lo')
1890                                         devs.push(new _luci2.NetworkModel.Device(this._devs[ifname]));
1891
1892                         return devs.sort(this._sort_devices);
1893                 },
1894
1895                 getDeviceByInterface: function(iface)
1896                 {
1897                         if (iface instanceof _luci2.NetworkModel.Interface)
1898                                 iface = iface.name();
1899
1900                         if (this._ifaces[iface])
1901                                 return this.getDevice(this._ifaces[iface].l3dev) ||
1902                                        this.getDevice(this._ifaces[iface].l2dev);
1903
1904                         return undefined;
1905                 },
1906
1907                 getDevice: function(ifname)
1908                 {
1909                         if (this._devs[ifname])
1910                                 return new _luci2.NetworkModel.Device(this._devs[ifname]);
1911
1912                         return undefined;
1913                 },
1914
1915                 createDevice: function(name)
1916                 {
1917                         return new _luci2.NetworkModel.Device(this._get_dev(name));
1918                 },
1919
1920                 getInterfaces: function()
1921                 {
1922                         var ifaces = [ ];
1923
1924                         for (var name in this._ifaces)
1925                                 if (name != 'loopback')
1926                                         ifaces.push(this.getInterface(name));
1927
1928                         ifaces.sort(function(a, b) {
1929                                 if (a.name() < b.name())
1930                                         return -1;
1931                                 else if (a.name() > b.name())
1932                                         return 1;
1933                                 else
1934                                         return 0;
1935                         });
1936
1937                         return ifaces;
1938                 },
1939
1940                 getInterfacesByDevice: function(dev)
1941                 {
1942                         var ifaces = [ ];
1943
1944                         if (dev instanceof _luci2.NetworkModel.Device)
1945                                 dev = dev.name();
1946
1947                         for (var name in this._ifaces)
1948                         {
1949                                 var iface = this._ifaces[name];
1950                                 if (iface.l2dev == dev || iface.l3dev == dev)
1951                                         ifaces.push(this.getInterface(name));
1952                         }
1953
1954                         ifaces.sort(function(a, b) {
1955                                 if (a.name() < b.name())
1956                                         return -1;
1957                                 else if (a.name() > b.name())
1958                                         return 1;
1959                                 else
1960                                         return 0;
1961                         });
1962
1963                         return ifaces;
1964                 },
1965
1966                 getInterface: function(iface)
1967                 {
1968                         if (this._ifaces[iface])
1969                                 return new _luci2.NetworkModel.Interface(this._ifaces[iface]);
1970
1971                         return undefined;
1972                 },
1973
1974                 getProtocols: function()
1975                 {
1976                         var rv = [ ];
1977
1978                         for (var proto in this._protos)
1979                         {
1980                                 var pr = this._protos[proto];
1981
1982                                 rv.push({
1983                                         name:        proto,
1984                                         description: pr.description,
1985                                         virtual:     pr.virtual,
1986                                         tunnel:      pr.tunnel
1987                                 });
1988                         }
1989
1990                         return rv.sort(function(a, b) {
1991                                 if (a.name < b.name)
1992                                         return -1;
1993                                 else if (a.name > b.name)
1994                                         return 1;
1995                                 else
1996                                         return 0;
1997                         });
1998                 },
1999
2000                 _find_wan: function(ipaddr)
2001                 {
2002                         for (var i = 0; i < this._cache.ifstate.length; i++)
2003                         {
2004                                 var ifstate = this._cache.ifstate[i];
2005
2006                                 if (!ifstate.route)
2007                                         continue;
2008
2009                                 for (var j = 0; j < ifstate.route.length; j++)
2010                                         if (ifstate.route[j].mask == 0 &&
2011                                             ifstate.route[j].target == ipaddr &&
2012                                             typeof(ifstate.route[j].table) == 'undefined')
2013                                         {
2014                                                 return this.getInterface(ifstate['interface']);
2015                                         }
2016                         }
2017
2018                         return undefined;
2019                 },
2020
2021                 findWAN: function()
2022                 {
2023                         return this._find_wan('0.0.0.0');
2024                 },
2025
2026                 findWAN6: function()
2027                 {
2028                         return this._find_wan('::');
2029                 },
2030
2031                 resolveAlias: function(ifname)
2032                 {
2033                         if (ifname instanceof _luci2.NetworkModel.Device)
2034                                 ifname = ifname.name();
2035
2036                         var dev = this._devs[ifname];
2037                         var seen = { };
2038
2039                         while (dev && dev.kind == 'alias')
2040                         {
2041                                 // loop
2042                                 if (seen[dev.ifname])
2043                                         return undefined;
2044
2045                                 var ifc = this._ifaces[dev.sid];
2046
2047                                 seen[dev.ifname] = true;
2048                                 dev = ifc ? this._devs[ifc.l3dev] : undefined;
2049                         }
2050
2051                         return dev ? this.getDevice(dev.ifname) : undefined;
2052                 }
2053         };
2054
2055         this.NetworkModel.Device = Class.extend({
2056                 _wifi_modes: {
2057                         ap: _luci2.tr('Master'),
2058                         sta: _luci2.tr('Client'),
2059                         adhoc: _luci2.tr('Ad-Hoc'),
2060                         monitor: _luci2.tr('Monitor'),
2061                         wds: _luci2.tr('Static WDS')
2062                 },
2063
2064                 _status: function(key)
2065                 {
2066                         var s = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2067
2068                         if (s)
2069                                 return key ? s[key] : s;
2070
2071                         return undefined;
2072                 },
2073
2074                 get: function(key)
2075                 {
2076                         var sid = this.options.sid;
2077                         var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2078                         return _luci2.NetworkModel._get(pkg, sid, key);
2079                 },
2080
2081                 set: function(key, val)
2082                 {
2083                         var sid = this.options.sid;
2084                         var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
2085                         return _luci2.NetworkModel._set(pkg, sid, key, val);
2086                 },
2087
2088                 init: function()
2089                 {
2090                         if (typeof(this.options.type) == 'undefined')
2091                                 this.options.type = 1;
2092
2093                         if (typeof(this.options.kind) == 'undefined')
2094                                 this.options.kind = 'ethernet';
2095
2096                         if (typeof(this.options.networks) == 'undefined')
2097                                 this.options.networks = [ ];
2098                 },
2099
2100                 name: function()
2101                 {
2102                         return this.options.ifname;
2103                 },
2104
2105                 description: function()
2106                 {
2107                         switch (this.options.kind)
2108                         {
2109                         case 'alias':
2110                                 return _luci2.tr('Alias for network "%s"').format(this.options.ifname.substring(1));
2111
2112                         case 'bridge':
2113                                 return _luci2.tr('Network bridge');
2114
2115                         case 'ethernet':
2116                                 return _luci2.tr('Network device');
2117
2118                         case 'tunnel':
2119                                 switch (this.options.type)
2120                                 {
2121                                 case 1: /* tuntap */
2122                                         return _luci2.tr('TAP device');
2123
2124                                 case 512: /* PPP */
2125                                         return _luci2.tr('PPP tunnel');
2126
2127                                 case 768: /* IP-IP Tunnel */
2128                                         return _luci2.tr('IP-in-IP tunnel');
2129
2130                                 case 769: /* IP6-IP6 Tunnel */
2131                                         return _luci2.tr('IPv6-in-IPv6 tunnel');
2132
2133                                 case 776: /* IPv6-in-IPv4 */
2134                                         return _luci2.tr('IPv6-over-IPv4 tunnel');
2135                                         break;
2136
2137                                 case 778: /* GRE over IP */
2138                                         return _luci2.tr('GRE-over-IP tunnel');
2139
2140                                 default:
2141                                         return _luci2.tr('Tunnel device');
2142                                 }
2143
2144                         case 'vlan':
2145                                 return _luci2.tr('VLAN %d on %s').format(this.options.vid, this.options.vsw.model);
2146
2147                         case 'wifi':
2148                                 var o = this.options;
2149                                 return _luci2.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
2150                                         o.wmode ? this._wifi_modes[o.wmode] : _luci2.tr('Unknown mode'),
2151                                         o.wssid || '?', o.wdev
2152                                 );
2153                         }
2154
2155                         return _luci2.tr('Unknown device');
2156                 },
2157
2158                 icon: function(up)
2159                 {
2160                         var kind = this.options.kind;
2161
2162                         if (kind == 'alias')
2163                                 kind = 'ethernet';
2164
2165                         if (typeof(up) == 'undefined')
2166                                 up = this.isUp();
2167
2168                         return _luci2.globals.resource + '/icons/%s%s.png'.format(kind, up ? '' : '_disabled');
2169                 },
2170
2171                 isUp: function()
2172                 {
2173                         var l = _luci2.NetworkModel._cache.devlist;
2174
2175                         for (var i = 0; i < l.length; i++)
2176                                 if (l[i].device == this.options.ifname)
2177                                         return (l[i].is_up === true);
2178
2179                         return false;
2180                 },
2181
2182                 isAlias: function()
2183                 {
2184                         return (this.options.kind == 'alias');
2185                 },
2186
2187                 isBridge: function()
2188                 {
2189                         return (this.options.kind == 'bridge');
2190                 },
2191
2192                 isBridgeable: function()
2193                 {
2194                         return (this.options.type == 1 && this.options.kind != 'bridge');
2195                 },
2196
2197                 isWireless: function()
2198                 {
2199                         return (this.options.kind == 'wifi');
2200                 },
2201
2202                 isInNetwork: function(net)
2203                 {
2204                         if (!(net instanceof _luci2.NetworkModel.Interface))
2205                                 net = _luci2.NetworkModel.getInterface(net);
2206
2207                         if (net)
2208                         {
2209                                 if (net.options.l3dev == this.options.ifname ||
2210                                     net.options.l2dev == this.options.ifname)
2211                                         return true;
2212
2213                                 var dev = _luci2.NetworkModel._devs[net.options.l2dev];
2214                                 if (dev && dev.kind == 'bridge' && dev.ports)
2215                                         return ($.inArray(this.options.ifname, dev.ports) > -1);
2216                         }
2217
2218                         return false;
2219                 },
2220
2221                 getMTU: function()
2222                 {
2223                         var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2224                         if (dev && !isNaN(dev.mtu))
2225                                 return dev.mtu;
2226
2227                         return undefined;
2228                 },
2229
2230                 getMACAddress: function()
2231                 {
2232                         if (this.options.type != 1)
2233                                 return undefined;
2234
2235                         var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
2236                         if (dev && dev.macaddr)
2237                                 return dev.macaddr.toUpperCase();
2238
2239                         return undefined;
2240                 },
2241
2242                 getInterfaces: function()
2243                 {
2244                         return _luci2.NetworkModel.getInterfacesByDevice(this.options.name);
2245                 },
2246
2247                 getStatistics: function()
2248                 {
2249                         var s = this._status('statistics') || { };
2250                         return {
2251                                 rx_bytes: (s.rx_bytes || 0),
2252                                 tx_bytes: (s.tx_bytes || 0),
2253                                 rx_packets: (s.rx_packets || 0),
2254                                 tx_packets: (s.tx_packets || 0)
2255                         };
2256                 },
2257
2258                 getTrafficHistory: function()
2259                 {
2260                         var def = new Array(120);
2261
2262                         for (var i = 0; i < 120; i++)
2263                                 def[i] = 0;
2264
2265                         var h = _luci2.NetworkModel._cache.bwstate[this.options.ifname] || { };
2266                         return {
2267                                 rx_bytes: (h.rx_bytes || def),
2268                                 tx_bytes: (h.tx_bytes || def),
2269                                 rx_packets: (h.rx_packets || def),
2270                                 tx_packets: (h.tx_packets || def)
2271                         };
2272                 },
2273
2274                 removeFromInterface: function(iface)
2275                 {
2276                         if (!(iface instanceof _luci2.NetworkModel.Interface))
2277                                 iface = _luci2.NetworkModel.getInterface(iface);
2278
2279                         if (!iface)
2280                                 return;
2281
2282                         var ifnames = _luci2.toArray(iface.get('ifname'));
2283                         if ($.inArray(this.options.ifname, ifnames) > -1)
2284                                 iface.set('ifname', _luci2.filterArray(ifnames, this.options.ifname));
2285
2286                         if (this.options.kind != 'wifi')
2287                                 return;
2288
2289                         var networks = _luci2.toArray(this.get('network'));
2290                         if ($.inArray(iface.name(), networks) > -1)
2291                                 this.set('network', _luci2.filterArray(networks, iface.name()));
2292                 },
2293
2294                 attachToInterface: function(iface)
2295                 {
2296                         if (!(iface instanceof _luci2.NetworkModel.Interface))
2297                                 iface = _luci2.NetworkModel.getInterface(iface);
2298
2299                         if (!iface)
2300                                 return;
2301
2302                         if (this.options.kind != 'wifi')
2303                         {
2304                                 var ifnames = _luci2.toArray(iface.get('ifname'));
2305                                 if ($.inArray(this.options.ifname, ifnames) < 0)
2306                                 {
2307                                         ifnames.push(this.options.ifname);
2308                                         iface.set('ifname', (ifnames.length > 1) ? ifnames : ifnames[0]);
2309                                 }
2310                         }
2311                         else
2312                         {
2313                                 var networks = _luci2.toArray(this.get('network'));
2314                                 if ($.inArray(iface.name(), networks) < 0)
2315                                 {
2316                                         networks.push(iface.name());
2317                                         this.set('network', (networks.length > 1) ? networks : networks[0]);
2318                                 }
2319                         }
2320                 }
2321         });
2322
2323         this.NetworkModel.Interface = Class.extend({
2324                 _status: function(key)
2325                 {
2326                         var s = _luci2.NetworkModel._cache.ifstate;
2327
2328                         for (var i = 0; i < s.length; i++)
2329                                 if (s[i]['interface'] == this.options.name)
2330                                         return key ? s[i][key] : s[i];
2331
2332                         return undefined;
2333                 },
2334
2335                 get: function(key)
2336                 {
2337                         return _luci2.NetworkModel._get('network', this.options.name, key);
2338                 },
2339
2340                 set: function(key, val)
2341                 {
2342                         return _luci2.NetworkModel._set('network', this.options.name, key, val);
2343                 },
2344
2345                 name: function()
2346                 {
2347                         return this.options.name;
2348                 },
2349
2350                 protocol: function()
2351                 {
2352                         return (this.get('proto') || 'none');
2353                 },
2354
2355                 isUp: function()
2356                 {
2357                         return (this._status('up') === true);
2358                 },
2359
2360                 isVirtual: function()
2361                 {
2362                         return (typeof(this.options.sid) != 'string');
2363                 },
2364
2365                 getProtocol: function()
2366                 {
2367                         var prname = this.get('proto') || 'none';
2368                         return _luci2.NetworkModel._protos[prname] || _luci2.NetworkModel._protos.none;
2369                 },
2370
2371                 getUptime: function()
2372                 {
2373                         var uptime = this._status('uptime');
2374                         return isNaN(uptime) ? 0 : uptime;
2375                 },
2376
2377                 getDevice: function(resolveAlias)
2378                 {
2379                         if (this.options.l3dev)
2380                                 return _luci2.NetworkModel.getDevice(this.options.l3dev);
2381
2382                         return undefined;
2383                 },
2384
2385                 getPhysdev: function()
2386                 {
2387                         if (this.options.l2dev)
2388                                 return _luci2.NetworkModel.getDevice(this.options.l2dev);
2389
2390                         return undefined;
2391                 },
2392
2393                 getSubdevices: function()
2394                 {
2395                         var rv = [ ];
2396                         var dev = this.options.l2dev ?
2397                                 _luci2.NetworkModel._devs[this.options.l2dev] : undefined;
2398
2399                         if (dev && dev.kind == 'bridge' && dev.ports && dev.ports.length)
2400                                 for (var i = 0; i < dev.ports.length; i++)
2401                                         rv.push(_luci2.NetworkModel.getDevice(dev.ports[i]));
2402
2403                         return rv;
2404                 },
2405
2406                 getIPv4Addrs: function(mask)
2407                 {
2408                         var rv = [ ];
2409                         var addrs = this._status('ipv4-address');
2410
2411                         if (addrs)
2412                                 for (var i = 0; i < addrs.length; i++)
2413                                         if (!mask)
2414                                                 rv.push(addrs[i].address);
2415                                         else
2416                                                 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2417
2418                         return rv;
2419                 },
2420
2421                 getIPv6Addrs: function(mask)
2422                 {
2423                         var rv = [ ];
2424                         var addrs;
2425
2426                         addrs = this._status('ipv6-address');
2427
2428                         if (addrs)
2429                                 for (var i = 0; i < addrs.length; i++)
2430                                         if (!mask)
2431                                                 rv.push(addrs[i].address);
2432                                         else
2433                                                 rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
2434
2435                         addrs = this._status('ipv6-prefix-assignment');
2436
2437                         if (addrs)
2438                                 for (var i = 0; i < addrs.length; i++)
2439                                         if (!mask)
2440                                                 rv.push('%s1'.format(addrs[i].address));
2441                                         else
2442                                                 rv.push('%s1/%d'.format(addrs[i].address, addrs[i].mask));
2443
2444                         return rv;
2445                 },
2446
2447                 getDNSAddrs: function()
2448                 {
2449                         var rv = [ ];
2450                         var addrs = this._status('dns-server');
2451
2452                         if (addrs)
2453                                 for (var i = 0; i < addrs.length; i++)
2454                                         rv.push(addrs[i]);
2455
2456                         return rv;
2457                 },
2458
2459                 getIPv4DNS: function()
2460                 {
2461                         var rv = [ ];
2462                         var dns = this._status('dns-server');
2463
2464                         if (dns)
2465                                 for (var i = 0; i < dns.length; i++)
2466                                         if (dns[i].indexOf(':') == -1)
2467                                                 rv.push(dns[i]);
2468
2469                         return rv;
2470                 },
2471
2472                 getIPv6DNS: function()
2473                 {
2474                         var rv = [ ];
2475                         var dns = this._status('dns-server');
2476
2477                         if (dns)
2478                                 for (var i = 0; i < dns.length; i++)
2479                                         if (dns[i].indexOf(':') > -1)
2480                                                 rv.push(dns[i]);
2481
2482                         return rv;
2483                 },
2484
2485                 getIPv4Gateway: function()
2486                 {
2487                         var rt = this._status('route');
2488
2489                         if (rt)
2490                                 for (var i = 0; i < rt.length; i++)
2491                                         if (rt[i].target == '0.0.0.0' && rt[i].mask == 0)
2492                                                 return rt[i].nexthop;
2493
2494                         return undefined;
2495                 },
2496
2497                 getIPv6Gateway: function()
2498                 {
2499                         var rt = this._status('route');
2500
2501                         if (rt)
2502                                 for (var i = 0; i < rt.length; i++)
2503                                         if (rt[i].target == '::' && rt[i].mask == 0)
2504                                                 return rt[i].nexthop;
2505
2506                         return undefined;
2507                 },
2508
2509                 getStatistics: function()
2510                 {
2511                         var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
2512                         return dev.getStatistics();
2513                 },
2514
2515                 getTrafficHistory: function()
2516                 {
2517                         var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
2518                         return dev.getTrafficHistory();
2519                 },
2520
2521                 setDevices: function(devs)
2522                 {
2523                         var dev = this.getPhysdev();
2524                         var old_devs = [ ];
2525                         var changed = false;
2526
2527                         if (dev && dev.isBridge())
2528                                 old_devs = this.getSubdevices();
2529                         else if (dev)
2530                                 old_devs = [ dev ];
2531
2532                         if (old_devs.length != devs.length)
2533                                 changed = true;
2534                         else
2535                                 for (var i = 0; i < old_devs.length; i++)
2536                                 {
2537                                         var dev = devs[i];
2538
2539                                         if (dev instanceof _luci2.NetworkModel.Device)
2540                                                 dev = dev.name();
2541
2542                                         if (!dev || old_devs[i].name() != dev)
2543                                         {
2544                                                 changed = true;
2545                                                 break;
2546                                         }
2547                                 }
2548
2549                         if (changed)
2550                         {
2551                                 for (var i = 0; i < old_devs.length; i++)
2552                                         old_devs[i].removeFromInterface(this);
2553
2554                                 for (var i = 0; i < devs.length; i++)
2555                                 {
2556                                         var dev = devs[i];
2557
2558                                         if (!(dev instanceof _luci2.NetworkModel.Device))
2559                                                 dev = _luci2.NetworkModel.getDevice(dev);
2560
2561                                         if (dev)
2562                                                 dev.attachToInterface(this);
2563                                 }
2564                         }
2565                 },
2566
2567                 changeProtocol: function(proto)
2568                 {
2569                         var pr = _luci2.NetworkModel._protos[proto];
2570
2571                         if (!pr)
2572                                 return;
2573
2574                         for (var opt in (this.get() || { }))
2575                         {
2576                                 switch (opt)
2577                                 {
2578                                 case 'type':
2579                                 case 'ifname':
2580                                 case 'macaddr':
2581                                         if (pr.virtual)
2582                                                 this.set(opt, undefined);
2583                                         break;
2584
2585                                 case 'auto':
2586                                 case 'mtu':
2587                                         break;
2588
2589                                 case 'proto':
2590                                         this.set(opt, pr.protocol);
2591                                         break;
2592
2593                                 default:
2594                                         this.set(opt, undefined);
2595                                         break;
2596                                 }
2597                         }
2598                 },
2599
2600                 createForm: function(mapwidget)
2601                 {
2602                         var self = this;
2603                         var proto = self.getProtocol();
2604                         var device = self.getDevice();
2605
2606                         if (!mapwidget)
2607                                 mapwidget = _luci2.cbi.Map;
2608
2609                         var map = new mapwidget('network', {
2610                                 caption:     _luci2.tr('Configure "%s"').format(self.name())
2611                         });
2612
2613                         var section = map.section(_luci2.cbi.SingleSection, self.name(), {
2614                                 anonymous:   true
2615                         });
2616
2617                         section.tab({
2618                                 id:      'general',
2619                                 caption: _luci2.tr('General Settings')
2620                         });
2621
2622                         section.tab({
2623                                 id:      'advanced',
2624                                 caption: _luci2.tr('Advanced Settings')
2625                         });
2626
2627                         section.tab({
2628                                 id:      'ipv6',
2629                                 caption: _luci2.tr('IPv6')
2630                         });
2631
2632                         section.tab({
2633                                 id:      'physical',
2634                                 caption: _luci2.tr('Physical Settings')
2635                         });
2636
2637
2638                         section.taboption('general', _luci2.cbi.CheckboxValue, 'auto', {
2639                                 caption:     _luci2.tr('Start on boot'),
2640                                 optional:    true,
2641                                 initial:     true
2642                         });
2643
2644                         var pr = section.taboption('general', _luci2.cbi.ListValue, 'proto', {
2645                                 caption:     _luci2.tr('Protocol')
2646                         });
2647
2648                         pr.ucivalue = function(sid) {
2649                                 return self.get('proto') || 'none';
2650                         };
2651
2652                         var ok = section.taboption('general', _luci2.cbi.ButtonValue, '_confirm', {
2653                                 caption:     _luci2.tr('Really switch?'),
2654                                 description: _luci2.tr('Changing the protocol will clear all configuration for this interface!'),
2655                                 text:        _luci2.tr('Change protocol')
2656                         });
2657
2658                         ok.on('click', function(ev) {
2659                                 self.changeProtocol(pr.formvalue(ev.data.sid));
2660                                 self.createForm(mapwidget).show();
2661                         });
2662
2663                         var protos = _luci2.NetworkModel.getProtocols();
2664
2665                         for (var i = 0; i < protos.length; i++)
2666                                 pr.value(protos[i].name, protos[i].description);
2667
2668                         proto.populateForm(section, self);
2669
2670                         if (!proto.virtual)
2671                         {
2672                                 var br = section.taboption('physical', _luci2.cbi.CheckboxValue, 'type', {
2673                                         caption:     _luci2.tr('Network bridge'),
2674                                         description: _luci2.tr('Merges multiple devices into one logical bridge'),
2675                                         optional:    true,
2676                                         enabled:     'bridge',
2677                                         disabled:    '',
2678                                         initial:     ''
2679                                 });
2680
2681                                 section.taboption('physical', _luci2.cbi.DeviceList, '__iface_multi', {
2682                                         caption:     _luci2.tr('Devices'),
2683                                         multiple:    true,
2684                                         bridges:     false
2685                                 }).depends('type', true);
2686
2687                                 section.taboption('physical', _luci2.cbi.DeviceList, '__iface_single', {
2688                                         caption:     _luci2.tr('Device'),
2689                                         multiple:    false,
2690                                         bridges:     true
2691                                 }).depends('type', false);
2692
2693                                 var mac = section.taboption('physical', _luci2.cbi.InputValue, 'macaddr', {
2694                                         caption:     _luci2.tr('Override MAC'),
2695                                         optional:    true,
2696                                         placeholder: device ? device.getMACAddress() : undefined,
2697                                         datatype:    'macaddr'
2698                                 })
2699
2700                                 mac.ucivalue = function(sid)
2701                                 {
2702                                         if (device)
2703                                                 return device.get('macaddr');
2704
2705                                         return this.callSuper('ucivalue', sid);
2706                                 };
2707
2708                                 mac.save = function(sid)
2709                                 {
2710                                         if (!this.changed(sid))
2711                                                 return false;
2712
2713                                         if (device)
2714                                                 device.set('macaddr', this.formvalue(sid));
2715                                         else
2716                                                 this.callSuper('set', sid);
2717
2718                                         return true;
2719                                 };
2720                         }
2721
2722                         section.taboption('physical', _luci2.cbi.InputValue, 'mtu', {
2723                                 caption:     _luci2.tr('Override MTU'),
2724                                 optional:    true,
2725                                 placeholder: device ? device.getMTU() : undefined,
2726                                 datatype:    'range(1, 9000)'
2727                         });
2728
2729                         section.taboption('physical', _luci2.cbi.InputValue, 'metric', {
2730                                 caption:     _luci2.tr('Override Metric'),
2731                                 optional:    true,
2732                                 placeholder: 0,
2733                                 datatype:    'uinteger'
2734                         });
2735
2736                         for (var field in section.fields)
2737                         {
2738                                 switch (field)
2739                                 {
2740                                 case 'proto':
2741                                         break;
2742
2743                                 case '_confirm':
2744                                         for (var i = 0; i < protos.length; i++)
2745                                                 if (protos[i].name != (this.get('proto') || 'none'))
2746                                                         section.fields[field].depends('proto', protos[i].name);
2747                                         break;
2748
2749                                 default:
2750                                         section.fields[field].depends('proto', this.get('proto') || 'none', true);
2751                                         break;
2752                                 }
2753                         }
2754
2755                         return map;
2756                 }
2757         });
2758
2759         this.NetworkModel.Protocol = this.NetworkModel.Interface.extend({
2760                 description: '__unknown__',
2761                 tunnel:      false,
2762                 virtual:     false,
2763
2764                 populateForm: function(section, iface)
2765                 {
2766
2767                 }
2768         });
2769
2770         this.system = {
2771                 getSystemInfo: _luci2.rpc.declare({
2772                         object: 'system',
2773                         method: 'info',
2774                         expect: { '': { } }
2775                 }),
2776
2777                 getBoardInfo: _luci2.rpc.declare({
2778                         object: 'system',
2779                         method: 'board',
2780                         expect: { '': { } }
2781                 }),
2782
2783                 getDiskInfo: _luci2.rpc.declare({
2784                         object: 'luci2.system',
2785                         method: 'diskfree',
2786                         expect: { '': { } }
2787                 }),
2788
2789                 getInfo: function(cb)
2790                 {
2791                         _luci2.rpc.batch();
2792
2793                         this.getSystemInfo();
2794                         this.getBoardInfo();
2795                         this.getDiskInfo();
2796
2797                         return _luci2.rpc.flush().then(function(info) {
2798                                 var rv = { };
2799
2800                                 $.extend(rv, info[0]);
2801                                 $.extend(rv, info[1]);
2802                                 $.extend(rv, info[2]);
2803
2804                                 return rv;
2805                         });
2806                 },
2807
2808                 getProcessList: _luci2.rpc.declare({
2809                         object: 'luci2.system',
2810                         method: 'process_list',
2811                         expect: { processes: [ ] },
2812                         filter: function(data) {
2813                                 data.sort(function(a, b) { return a.pid - b.pid });
2814                                 return data;
2815                         }
2816                 }),
2817
2818                 getSystemLog: _luci2.rpc.declare({
2819                         object: 'luci2.system',
2820                         method: 'syslog',
2821                         expect: { log: '' }
2822                 }),
2823
2824                 getKernelLog: _luci2.rpc.declare({
2825                         object: 'luci2.system',
2826                         method: 'dmesg',
2827                         expect: { log: '' }
2828                 }),
2829
2830                 getZoneInfo: function(cb)
2831                 {
2832                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
2833                 },
2834
2835                 sendSignal: _luci2.rpc.declare({
2836                         object: 'luci2.system',
2837                         method: 'process_signal',
2838                         params: [ 'pid', 'signal' ],
2839                         filter: function(data) {
2840                                 return (data == 0);
2841                         }
2842                 }),
2843
2844                 initList: _luci2.rpc.declare({
2845                         object: 'luci2.system',
2846                         method: 'init_list',
2847                         expect: { initscripts: [ ] },
2848                         filter: function(data) {
2849                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
2850                                 return data;
2851                         }
2852                 }),
2853
2854                 initEnabled: function(init, cb)
2855                 {
2856                         return this.initList().then(function(list) {
2857                                 for (var i = 0; i < list.length; i++)
2858                                         if (list[i].name == init)
2859                                                 return !!list[i].enabled;
2860
2861                                 return false;
2862                         });
2863                 },
2864
2865                 initRun: _luci2.rpc.declare({
2866                         object: 'luci2.system',
2867                         method: 'init_action',
2868                         params: [ 'name', 'action' ],
2869                         filter: function(data) {
2870                                 return (data == 0);
2871                         }
2872                 }),
2873
2874                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
2875                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
2876                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
2877                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
2878                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
2879                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
2880
2881
2882                 getRcLocal: _luci2.rpc.declare({
2883                         object: 'luci2.system',
2884                         method: 'rclocal_get',
2885                         expect: { data: '' }
2886                 }),
2887
2888                 setRcLocal: _luci2.rpc.declare({
2889                         object: 'luci2.system',
2890                         method: 'rclocal_set',
2891                         params: [ 'data' ]
2892                 }),
2893
2894
2895                 getCrontab: _luci2.rpc.declare({
2896                         object: 'luci2.system',
2897                         method: 'crontab_get',
2898                         expect: { data: '' }
2899                 }),
2900
2901                 setCrontab: _luci2.rpc.declare({
2902                         object: 'luci2.system',
2903                         method: 'crontab_set',
2904                         params: [ 'data' ]
2905                 }),
2906
2907
2908                 getSSHKeys: _luci2.rpc.declare({
2909                         object: 'luci2.system',
2910                         method: 'sshkeys_get',
2911                         expect: { keys: [ ] }
2912                 }),
2913
2914                 setSSHKeys: _luci2.rpc.declare({
2915                         object: 'luci2.system',
2916                         method: 'sshkeys_set',
2917                         params: [ 'keys' ]
2918                 }),
2919
2920
2921                 setPassword: _luci2.rpc.declare({
2922                         object: 'luci2.system',
2923                         method: 'password_set',
2924                         params: [ 'user', 'password' ]
2925                 }),
2926
2927
2928                 listLEDs: _luci2.rpc.declare({
2929                         object: 'luci2.system',
2930                         method: 'led_list',
2931                         expect: { leds: [ ] }
2932                 }),
2933
2934                 listUSBDevices: _luci2.rpc.declare({
2935                         object: 'luci2.system',
2936                         method: 'usb_list',
2937                         expect: { devices: [ ] }
2938                 }),
2939
2940
2941                 testUpgrade: _luci2.rpc.declare({
2942                         object: 'luci2.system',
2943                         method: 'upgrade_test',
2944                         expect: { '': { } }
2945                 }),
2946
2947                 startUpgrade: _luci2.rpc.declare({
2948                         object: 'luci2.system',
2949                         method: 'upgrade_start',
2950                         params: [ 'keep' ]
2951                 }),
2952
2953                 cleanUpgrade: _luci2.rpc.declare({
2954                         object: 'luci2.system',
2955                         method: 'upgrade_clean'
2956                 }),
2957
2958
2959                 restoreBackup: _luci2.rpc.declare({
2960                         object: 'luci2.system',
2961                         method: 'backup_restore'
2962                 }),
2963
2964                 cleanBackup: _luci2.rpc.declare({
2965                         object: 'luci2.system',
2966                         method: 'backup_clean'
2967                 }),
2968
2969
2970                 getBackupConfig: _luci2.rpc.declare({
2971                         object: 'luci2.system',
2972                         method: 'backup_config_get',
2973                         expect: { config: '' }
2974                 }),
2975
2976                 setBackupConfig: _luci2.rpc.declare({
2977                         object: 'luci2.system',
2978                         method: 'backup_config_set',
2979                         params: [ 'data' ]
2980                 }),
2981
2982
2983                 listBackup: _luci2.rpc.declare({
2984                         object: 'luci2.system',
2985                         method: 'backup_list',
2986                         expect: { files: [ ] }
2987                 }),
2988
2989
2990                 testReset: _luci2.rpc.declare({
2991                         object: 'luci2.system',
2992                         method: 'reset_test',
2993                         expect: { supported: false }
2994                 }),
2995
2996                 startReset: _luci2.rpc.declare({
2997                         object: 'luci2.system',
2998                         method: 'reset_start'
2999                 }),
3000
3001
3002                 performReboot: _luci2.rpc.declare({
3003                         object: 'luci2.system',
3004                         method: 'reboot'
3005                 })
3006         };
3007
3008         this.opkg = {
3009                 updateLists: _luci2.rpc.declare({
3010                         object: 'luci2.opkg',
3011                         method: 'update',
3012                         expect: { '': { } }
3013                 }),
3014
3015                 _allPackages: _luci2.rpc.declare({
3016                         object: 'luci2.opkg',
3017                         method: 'list',
3018                         params: [ 'offset', 'limit', 'pattern' ],
3019                         expect: { '': { } }
3020                 }),
3021
3022                 _installedPackages: _luci2.rpc.declare({
3023                         object: 'luci2.opkg',
3024                         method: 'list_installed',
3025                         params: [ 'offset', 'limit', 'pattern' ],
3026                         expect: { '': { } }
3027                 }),
3028
3029                 _findPackages: _luci2.rpc.declare({
3030                         object: 'luci2.opkg',
3031                         method: 'find',
3032                         params: [ 'offset', 'limit', 'pattern' ],
3033                         expect: { '': { } }
3034                 }),
3035
3036                 _fetchPackages: function(action, offset, limit, pattern)
3037                 {
3038                         var packages = [ ];
3039
3040                         return action(offset, limit, pattern).then(function(list) {
3041                                 if (!list.total || !list.packages)
3042                                         return { length: 0, total: 0 };
3043
3044                                 packages.push.apply(packages, list.packages);
3045                                 packages.total = list.total;
3046
3047                                 if (limit <= 0)
3048                                         limit = list.total;
3049
3050                                 if (packages.length >= limit)
3051                                         return packages;
3052
3053                                 _luci2.rpc.batch();
3054
3055                                 for (var i = offset + packages.length; i < limit; i += 100)
3056                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
3057
3058                                 return _luci2.rpc.flush();
3059                         }).then(function(lists) {
3060                                 for (var i = 0; i < lists.length; i++)
3061                                 {
3062                                         if (!lists[i].total || !lists[i].packages)
3063                                                 continue;
3064
3065                                         packages.push.apply(packages, lists[i].packages);
3066                                         packages.total = lists[i].total;
3067                                 }
3068
3069                                 return packages;
3070                         });
3071                 },
3072
3073                 listPackages: function(offset, limit, pattern)
3074                 {
3075                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
3076                 },
3077
3078                 installedPackages: function(offset, limit, pattern)
3079                 {
3080                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
3081                 },
3082
3083                 findPackages: function(offset, limit, pattern)
3084                 {
3085                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
3086                 },
3087
3088                 installPackage: _luci2.rpc.declare({
3089                         object: 'luci2.opkg',
3090                         method: 'install',
3091                         params: [ 'package' ],
3092                         expect: { '': { } }
3093                 }),
3094
3095                 removePackage: _luci2.rpc.declare({
3096                         object: 'luci2.opkg',
3097                         method: 'remove',
3098                         params: [ 'package' ],
3099                         expect: { '': { } }
3100                 }),
3101
3102                 getConfig: _luci2.rpc.declare({
3103                         object: 'luci2.opkg',
3104                         method: 'config_get',
3105                         expect: { config: '' }
3106                 }),
3107
3108                 setConfig: _luci2.rpc.declare({
3109                         object: 'luci2.opkg',
3110                         method: 'config_set',
3111                         params: [ 'data' ]
3112                 })
3113         };
3114
3115         this.session = {
3116
3117                 login: _luci2.rpc.declare({
3118                         object: 'session',
3119                         method: 'login',
3120                         params: [ 'username', 'password' ],
3121                         expect: { '': { } }
3122                 }),
3123
3124                 access: _luci2.rpc.declare({
3125                         object: 'session',
3126                         method: 'access',
3127                         params: [ 'scope', 'object', 'function' ],
3128                         expect: { access: false }
3129                 }),
3130
3131                 isAlive: function()
3132                 {
3133                         return _luci2.session.access('ubus', 'session', 'access');
3134                 },
3135
3136                 startHeartbeat: function()
3137                 {
3138                         this._hearbeatInterval = window.setInterval(function() {
3139                                 _luci2.session.isAlive().then(function(alive) {
3140                                         if (!alive)
3141                                         {
3142                                                 _luci2.session.stopHeartbeat();
3143                                                 _luci2.ui.login(true);
3144                                         }
3145
3146                                 });
3147                         }, _luci2.globals.timeout * 2);
3148                 },
3149
3150                 stopHeartbeat: function()
3151                 {
3152                         if (typeof(this._hearbeatInterval) != 'undefined')
3153                         {
3154                                 window.clearInterval(this._hearbeatInterval);
3155                                 delete this._hearbeatInterval;
3156                         }
3157                 },
3158
3159
3160                 _acls: { },
3161
3162                 _fetch_acls: _luci2.rpc.declare({
3163                         object: 'session',
3164                         method: 'access',
3165                         expect: { '': { } }
3166                 }),
3167
3168                 _fetch_acls_cb: function(acls)
3169                 {
3170                         _luci2.session._acls = acls;
3171                 },
3172
3173                 updateACLs: function()
3174                 {
3175                         return _luci2.session._fetch_acls()
3176                                 .then(_luci2.session._fetch_acls_cb);
3177                 },
3178
3179                 hasACL: function(scope, object, func)
3180                 {
3181                         var acls = _luci2.session._acls;
3182
3183                         if (typeof(func) == 'undefined')
3184                                 return (acls && acls[scope] && acls[scope][object]);
3185
3186                         if (acls && acls[scope] && acls[scope][object])
3187                                 for (var i = 0; i < acls[scope][object].length; i++)
3188                                         if (acls[scope][object][i] == func)
3189                                                 return true;
3190
3191                         return false;
3192                 }
3193         };
3194
3195         this.ui = {
3196
3197                 saveScrollTop: function()
3198                 {
3199                         this._scroll_top = $(document).scrollTop();
3200                 },
3201
3202                 restoreScrollTop: function()
3203                 {
3204                         if (typeof(this._scroll_top) == 'undefined')
3205                                 return;
3206
3207                         $(document).scrollTop(this._scroll_top);
3208
3209                         delete this._scroll_top;
3210                 },
3211
3212                 loading: function(enable)
3213                 {
3214                         var win = $(window);
3215                         var body = $('body');
3216
3217                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
3218                                 modal: $('<div />')
3219                                         .css('z-index', 2000)
3220                                         .addClass('modal fade')
3221                                         .append($('<div />')
3222                                                 .addClass('modal-dialog')
3223                                                 .append($('<div />')
3224                                                         .addClass('modal-content luci2-modal-loader')
3225                                                         .append($('<div />')
3226                                                                 .addClass('modal-body')
3227                                                                 .text(_luci2.tr('Loading data…')))))
3228                                         .appendTo(body)
3229                                         .modal({
3230                                                 backdrop: 'static',
3231                                                 keyboard: false
3232                                         })
3233                         });
3234
3235                         state.modal.modal(enable ? 'show' : 'hide');
3236                 },
3237
3238                 dialog: function(title, content, options)
3239                 {
3240                         var win = $(window);
3241                         var body = $('body');
3242
3243                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
3244                                 dialog: $('<div />')
3245                                         .addClass('modal fade')
3246                                         .append($('<div />')
3247                                                 .addClass('modal-dialog')
3248                                                 .append($('<div />')
3249                                                         .addClass('modal-content')
3250                                                         .append($('<div />')
3251                                                                 .addClass('modal-header')
3252                                                                 .append('<h4 />')
3253                                                                         .addClass('modal-title'))
3254                                                         .append($('<div />')
3255                                                                 .addClass('modal-body'))
3256                                                         .append($('<div />')
3257                                                                 .addClass('modal-footer')
3258                                                                 .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
3259                                                                         .click(function() {
3260                                                                                 $(this).parents('div.modal').modal('hide');
3261                                                                         })))))
3262                                         .appendTo(body)
3263                         });
3264
3265                         if (typeof(options) != 'object')
3266                                 options = { };
3267
3268                         if (title === false)
3269                         {
3270                                 state.dialog.modal('hide');
3271
3272                                 return state.dialog;
3273                         }
3274
3275                         var cnt = state.dialog.children().children().children('div.modal-body');
3276                         var ftr = state.dialog.children().children().children('div.modal-footer');
3277
3278                         ftr.empty().show();
3279
3280                         if (options.style == 'confirm')
3281                         {
3282                                 ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
3283                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
3284
3285                                 ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
3286                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
3287                         }
3288                         else if (options.style == 'close')
3289                         {
3290                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
3291                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
3292                         }
3293                         else if (options.style == 'wait')
3294                         {
3295                                 ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
3296                                         .attr('disabled', true));
3297                         }
3298
3299                         if (options.wide)
3300                         {
3301                                 state.dialog.addClass('wide');
3302                         }
3303                         else
3304                         {
3305                                 state.dialog.removeClass('wide');
3306                         }
3307
3308                         state.dialog.find('h4:first').text(title);
3309                         state.dialog.modal('show');
3310
3311                         cnt.empty().append(content);
3312
3313                         return state.dialog;
3314                 },
3315
3316                 upload: function(title, content, options)
3317                 {
3318                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
3319                                 form: $('<form />')
3320                                         .attr('method', 'post')
3321                                         .attr('action', '/cgi-bin/luci-upload')
3322                                         .attr('enctype', 'multipart/form-data')
3323                                         .attr('target', 'cbi-fileupload-frame')
3324                                         .append($('<p />'))
3325                                         .append($('<input />')
3326                                                 .attr('type', 'hidden')
3327                                                 .attr('name', 'sessionid'))
3328                                         .append($('<input />')
3329                                                 .attr('type', 'hidden')
3330                                                 .attr('name', 'filename'))
3331                                         .append($('<input />')
3332                                                 .attr('type', 'file')
3333                                                 .attr('name', 'filedata')
3334                                                 .addClass('cbi-input-file'))
3335                                         .append($('<div />')
3336                                                 .css('width', '100%')
3337                                                 .addClass('progress progress-striped active')
3338                                                 .append($('<div />')
3339                                                         .addClass('progress-bar')
3340                                                         .css('width', '100%')))
3341                                         .append($('<iframe />')
3342                                                 .addClass('pull-right')
3343                                                 .attr('name', 'cbi-fileupload-frame')
3344                                                 .css('width', '1px')
3345                                                 .css('height', '1px')
3346                                                 .css('visibility', 'hidden')),
3347
3348                                 finish_cb: function(ev) {
3349                                         $(this).off('load');
3350
3351                                         var body = (this.contentDocument || this.contentWindow.document).body;
3352                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
3353                                                 body = body.firstChild;
3354
3355                                         var json;
3356                                         try {
3357                                                 json = $.parseJSON(body.innerHTML);
3358                                         } catch(e) {
3359                                                 json = {
3360                                                         message: _luci2.tr('Invalid server response received'),
3361                                                         error: [ -1, _luci2.tr('Invalid data') ]
3362                                                 };
3363                                         };
3364
3365                                         if (json.error)
3366                                         {
3367                                                 L.ui.dialog(L.tr('File upload'), [
3368                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
3369                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
3370                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
3371                                                 ], { style: 'close' });
3372                                         }
3373                                         else if (typeof(state.success_cb) == 'function')
3374                                         {
3375                                                 state.success_cb(json);
3376                                         }
3377                                 },
3378
3379                                 confirm_cb: function() {
3380                                         var f = state.form.find('.cbi-input-file');
3381                                         var b = state.form.find('.progress');
3382                                         var p = state.form.find('p');
3383
3384                                         if (!f.val())
3385                                                 return;
3386
3387                                         state.form.find('iframe').on('load', state.finish_cb);
3388                                         state.form.submit();
3389
3390                                         f.hide();
3391                                         b.show();
3392                                         p.text(_luci2.tr('File upload in progress â€¦'));
3393
3394                                         state.form.parent().parent().find('button').prop('disabled', true);
3395                                 }
3396                         });
3397
3398                         state.form.find('.progress').hide();
3399                         state.form.find('.cbi-input-file').val('').show();
3400                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
3401
3402                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
3403                         state.form.find('[name=filename]').val(options.filename);
3404
3405                         state.success_cb = options.success;
3406
3407                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
3408                                 style: 'confirm',
3409                                 confirm: state.confirm_cb
3410                         });
3411                 },
3412
3413                 reconnect: function()
3414                 {
3415                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
3416                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
3417                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
3418                         var images    = $();
3419                         var interval, timeout;
3420
3421                         _luci2.ui.dialog(
3422                                 _luci2.tr('Waiting for device'), [
3423                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring â€¦')),
3424                                         $('<div />')
3425                                                 .css('width', '100%')
3426                                                 .addClass('progressbar')
3427                                                 .addClass('intermediate')
3428                                                 .append($('<div />')
3429                                                         .css('width', '100%'))
3430                                 ], { style: 'wait' }
3431                         );
3432
3433                         for (var i = 0; i < protocols.length; i++)
3434                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
3435
3436                         //_luci2.network.getNetworkStatus(function(s) {
3437                         //      for (var i = 0; i < protocols.length; i++)
3438                         //      {
3439                         //              for (var j = 0; j < s.length; j++)
3440                         //              {
3441                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
3442                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
3443                         //
3444                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
3445                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
3446                         //              }
3447                         //      }
3448                         //}).then(function() {
3449                                 images.on('load', function() {
3450                                         var url = this.getAttribute('url');
3451                                         _luci2.session.isAlive().then(function(access) {
3452                                                 if (access)
3453                                                 {
3454                                                         window.clearTimeout(timeout);
3455                                                         window.clearInterval(interval);
3456                                                         _luci2.ui.dialog(false);
3457                                                         images = null;
3458                                                 }
3459                                                 else
3460                                                 {
3461                                                         location.href = url;
3462                                                 }
3463                                         });
3464                                 });
3465
3466                                 interval = window.setInterval(function() {
3467                                         images.each(function() {
3468                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
3469                                         });
3470                                 }, 5000);
3471
3472                                 timeout = window.setTimeout(function() {
3473                                         window.clearInterval(interval);
3474                                         images.off('load');
3475
3476                                         _luci2.ui.dialog(
3477                                                 _luci2.tr('Device not responding'),
3478                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
3479                                                 { style: 'close' }
3480                                         );
3481                                 }, 180000);
3482                         //});
3483                 },
3484
3485                 login: function(invalid)
3486                 {
3487                         var state = _luci2.ui._login || (_luci2.ui._login = {
3488                                 form: $('<form />')
3489                                         .attr('target', '')
3490                                         .attr('method', 'post')
3491                                         .append($('<p />')
3492                                                 .addClass('alert-message')
3493                                                 .text(_luci2.tr('Wrong username or password given!')))
3494                                         .append($('<p />')
3495                                                 .append($('<label />')
3496                                                         .text(_luci2.tr('Username'))
3497                                                         .append($('<br />'))
3498                                                         .append($('<input />')
3499                                                                 .attr('type', 'text')
3500                                                                 .attr('name', 'username')
3501                                                                 .attr('value', 'root')
3502                                                                 .addClass('form-control')
3503                                                                 .keypress(function(ev) {
3504                                                                         if (ev.which == 10 || ev.which == 13)
3505                                                                                 state.confirm_cb();
3506                                                                 }))))
3507                                         .append($('<p />')
3508                                                 .append($('<label />')
3509                                                         .text(_luci2.tr('Password'))
3510                                                         .append($('<br />'))
3511                                                         .append($('<input />')
3512                                                                 .attr('type', 'password')
3513                                                                 .attr('name', 'password')
3514                                                                 .addClass('form-control')
3515                                                                 .keypress(function(ev) {
3516                                                                         if (ev.which == 10 || ev.which == 13)
3517                                                                                 state.confirm_cb();
3518                                                                 }))))
3519                                         .append($('<p />')
3520                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
3521
3522                                 response_cb: function(response) {
3523                                         if (!response.ubus_rpc_session)
3524                                         {
3525                                                 _luci2.ui.login(true);
3526                                         }
3527                                         else
3528                                         {
3529                                                 _luci2.globals.sid = response.ubus_rpc_session;
3530                                                 _luci2.setHash('id', _luci2.globals.sid);
3531                                                 _luci2.session.startHeartbeat();
3532                                                 _luci2.ui.dialog(false);
3533                                                 state.deferred.resolve();
3534                                         }
3535                                 },
3536
3537                                 confirm_cb: function() {
3538                                         var u = state.form.find('[name=username]').val();
3539                                         var p = state.form.find('[name=password]').val();
3540
3541                                         if (!u)
3542                                                 return;
3543
3544                                         _luci2.ui.dialog(
3545                                                 _luci2.tr('Logging in'), [
3546                                                         $('<p />').text(_luci2.tr('Log in in progress â€¦')),
3547                                                         $('<div />')
3548                                                                 .css('width', '100%')
3549                                                                 .addClass('progressbar')
3550                                                                 .addClass('intermediate')
3551                                                                 .append($('<div />')
3552                                                                         .css('width', '100%'))
3553                                                 ], { style: 'wait' }
3554                                         );
3555
3556                                         _luci2.globals.sid = '00000000000000000000000000000000';
3557                                         _luci2.session.login(u, p).then(state.response_cb);
3558                                 }
3559                         });
3560
3561                         if (!state.deferred || state.deferred.state() != 'pending')
3562                                 state.deferred = $.Deferred();
3563
3564                         /* try to find sid from hash */
3565                         var sid = _luci2.getHash('id');
3566                         if (sid && sid.match(/^[a-f0-9]{32}$/))
3567                         {
3568                                 _luci2.globals.sid = sid;
3569                                 _luci2.session.isAlive().then(function(access) {
3570                                         if (access)
3571                                         {
3572                                                 _luci2.session.startHeartbeat();
3573                                                 state.deferred.resolve();
3574                                         }
3575                                         else
3576                                         {
3577                                                 _luci2.setHash('id', undefined);
3578                                                 _luci2.ui.login();
3579                                         }
3580                                 });
3581
3582                                 return state.deferred;
3583                         }
3584
3585                         if (invalid)
3586                                 state.form.find('.alert-message').show();
3587                         else
3588                                 state.form.find('.alert-message').hide();
3589
3590                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
3591                                 style: 'confirm',
3592                                 confirm: state.confirm_cb
3593                         });
3594
3595                         state.form.find('[name=password]').focus();
3596
3597                         return state.deferred;
3598                 },
3599
3600                 cryptPassword: _luci2.rpc.declare({
3601                         object: 'luci2.ui',
3602                         method: 'crypt',
3603                         params: [ 'data' ],
3604                         expect: { crypt: '' }
3605                 }),
3606
3607
3608                 _acl_merge_scope: function(acl_scope, scope)
3609                 {
3610                         if ($.isArray(scope))
3611                         {
3612                                 for (var i = 0; i < scope.length; i++)
3613                                         acl_scope[scope[i]] = true;
3614                         }
3615                         else if ($.isPlainObject(scope))
3616                         {
3617                                 for (var object_name in scope)
3618                                 {
3619                                         if (!$.isArray(scope[object_name]))
3620                                                 continue;
3621
3622                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
3623
3624                                         for (var i = 0; i < scope[object_name].length; i++)
3625                                                 acl_object[scope[object_name][i]] = true;
3626                                 }
3627                         }
3628                 },
3629
3630                 _acl_merge_permission: function(acl_perm, perm)
3631                 {
3632                         if ($.isPlainObject(perm))
3633                         {
3634                                 for (var scope_name in perm)
3635                                 {
3636                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
3637                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
3638                                 }
3639                         }
3640                 },
3641
3642                 _acl_merge_group: function(acl_group, group)
3643                 {
3644                         if ($.isPlainObject(group))
3645                         {
3646                                 if (!acl_group.description)
3647                                         acl_group.description = group.description;
3648
3649                                 if (group.read)
3650                                 {
3651                                         var acl_perm = acl_group.read || (acl_group.read = { });
3652                                         this._acl_merge_permission(acl_perm, group.read);
3653                                 }
3654
3655                                 if (group.write)
3656                                 {
3657                                         var acl_perm = acl_group.write || (acl_group.write = { });
3658                                         this._acl_merge_permission(acl_perm, group.write);
3659                                 }
3660                         }
3661                 },
3662
3663                 _acl_merge_tree: function(acl_tree, tree)
3664                 {
3665                         if ($.isPlainObject(tree))
3666                         {
3667                                 for (var group_name in tree)
3668                                 {
3669                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
3670                                         this._acl_merge_group(acl_group, tree[group_name]);
3671                                 }
3672                         }
3673                 },
3674
3675                 listAvailableACLs: _luci2.rpc.declare({
3676                         object: 'luci2.ui',
3677                         method: 'acls',
3678                         expect: { acls: [ ] },
3679                         filter: function(trees) {
3680                                 var acl_tree = { };
3681                                 for (var i = 0; i < trees.length; i++)
3682                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
3683                                 return acl_tree;
3684                         }
3685                 }),
3686
3687                 _render_change_indicator: function()
3688                 {
3689                         return $('<ul />')
3690                                 .addClass('nav navbar-nav navbar-right')
3691                                 .append($('<li />')
3692                                         .append($('<a />')
3693                                                 .attr('id', 'changes')
3694                                                 .attr('href', '#')
3695                                                 .append($('<span />')
3696                                                         .addClass('label label-info'))));
3697                 },
3698
3699                 renderMainMenu: _luci2.rpc.declare({
3700                         object: 'luci2.ui',
3701                         method: 'menu',
3702                         expect: { menu: { } },
3703                         filter: function(entries) {
3704                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
3705                                 _luci2.globals.mainMenu.entries(entries);
3706
3707                                 $('#mainmenu')
3708                                         .empty()
3709                                         .append(_luci2.globals.mainMenu.render(0, 1))
3710                                         .append(_luci2.ui._render_change_indicator());
3711                         }
3712                 }),
3713
3714                 renderViewMenu: function()
3715                 {
3716                         $('#viewmenu')
3717                                 .empty()
3718                                 .append(_luci2.globals.mainMenu.render(2, 900));
3719                 },
3720
3721                 renderView: function()
3722                 {
3723                         var node  = arguments[0];
3724                         var name  = node.view.split(/\//).join('.');
3725                         var cname = _luci2.toClassName(name);
3726                         var views = _luci2.views || (_luci2.views = { });
3727                         var args  = [ ];
3728
3729                         for (var i = 1; i < arguments.length; i++)
3730                                 args.push(arguments[i]);
3731
3732                         if (_luci2.globals.currentView)
3733                                 _luci2.globals.currentView.finish();
3734
3735                         _luci2.ui.renderViewMenu();
3736                         _luci2.setHash('view', node.view);
3737
3738                         if (views[cname] instanceof _luci2.ui.view)
3739                         {
3740                                 _luci2.globals.currentView = views[cname];
3741                                 return views[cname].render.apply(views[cname], args);
3742                         }
3743
3744                         var url = _luci2.globals.resource + '/view/' + name + '.js';
3745
3746                         return $.ajax(url, {
3747                                 method: 'GET',
3748                                 cache: true,
3749                                 dataType: 'text'
3750                         }).then(function(data) {
3751                                 try {
3752                                         var viewConstructorSource = (
3753                                                 '(function(L, $) { ' +
3754                                                         'return %s' +
3755                                                 '})(_luci2, $);\n\n' +
3756                                                 '//@ sourceURL=%s'
3757                                         ).format(data, url);
3758
3759                                         var viewConstructor = eval(viewConstructorSource);
3760
3761                                         views[cname] = new viewConstructor({
3762                                                 name: name,
3763                                                 acls: node.write || { }
3764                                         });
3765
3766                                         _luci2.globals.currentView = views[cname];
3767                                         return views[cname].render.apply(views[cname], args);
3768                                 }
3769                                 catch(e) {
3770                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
3771                                 };
3772
3773                                 return $.Deferred().resolve();
3774                         });
3775                 },
3776
3777                 changeView: function()
3778                 {
3779                         var name = _luci2.getHash('view');
3780                         var node = _luci2.globals.defaultNode;
3781
3782                         if (name && _luci2.globals.mainMenu)
3783                                 node = _luci2.globals.mainMenu.getNode(name);
3784
3785                         if (node)
3786                         {
3787                                 _luci2.ui.loading(true);
3788                                 _luci2.ui.renderView(node).then(function() {
3789                                         _luci2.ui.loading(false);
3790                                 });
3791                         }
3792                 },
3793
3794                 updateHostname: function()
3795                 {
3796                         return _luci2.system.getBoardInfo().then(function(info) {
3797                                 if (info.hostname)
3798                                         $('#hostname').text(info.hostname);
3799                         });
3800                 },
3801
3802                 updateChanges: function()
3803                 {
3804                         return _luci2.uci.changes().then(function(changes) {
3805                                 var n = 0;
3806                                 var html = '';
3807
3808                                 for (var config in changes)
3809                                 {
3810                                         var log = [ ];
3811
3812                                         for (var i = 0; i < changes[config].length; i++)
3813                                         {
3814                                                 var c = changes[config][i];
3815
3816                                                 switch (c[0])
3817                                                 {
3818                                                 case 'order':
3819                                                         log.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
3820                                                         break;
3821
3822                                                 case 'remove':
3823                                                         if (c.length < 3)
3824                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
3825                                                         else
3826                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
3827                                                         break;
3828
3829                                                 case 'rename':
3830                                                         if (c.length < 4)
3831                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
3832                                                         else
3833                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3834                                                         break;
3835
3836                                                 case 'add':
3837                                                         log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
3838                                                         break;
3839
3840                                                 case 'list-add':
3841                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3842                                                         break;
3843
3844                                                 case 'list-del':
3845                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
3846                                                         break;
3847
3848                                                 case 'set':
3849                                                         if (c.length < 4)
3850                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
3851                                                         else
3852                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
3853                                                         break;
3854                                                 }
3855                                         }
3856
3857                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
3858                                         n += changes[config].length;
3859                                 }
3860
3861                                 if (n > 0)
3862                                         $('#changes')
3863                                                 .empty()
3864                                                 .show()
3865                                                 .append($('<a />')
3866                                                         .attr('href', '#')
3867                                                         .addClass('label')
3868                                                         .addClass('notice')
3869                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
3870                                                         .click(function(ev) {
3871                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
3872                                                                 ev.preventDefault();
3873                                                         }));
3874                                 else
3875                                         $('#changes')
3876                                                 .hide();
3877                         });
3878                 },
3879
3880                 init: function()
3881                 {
3882                         _luci2.ui.loading(true);
3883
3884                         $.when(
3885                                 _luci2.session.updateACLs(),
3886                                 _luci2.ui.updateHostname(),
3887                                 _luci2.ui.updateChanges(),
3888                                 _luci2.ui.renderMainMenu(),
3889                                 _luci2.NetworkModel.init()
3890                         ).then(function() {
3891                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
3892                                         _luci2.ui.loading(false);
3893                                 });
3894
3895                                 $(window).on('hashchange', function() {
3896                                         _luci2.ui.changeView();
3897                                 });
3898                         });
3899                 },
3900
3901                 button: function(label, style, title)
3902                 {
3903                         style = style || 'default';
3904
3905                         return $('<button />')
3906                                 .attr('type', 'button')
3907                                 .attr('title', title ? title : '')
3908                                 .addClass('btn btn-' + style)
3909                                 .text(label);
3910                 }
3911         };
3912
3913         this.ui.AbstractWidget = Class.extend({
3914                 i18n: function(text) {
3915                         return text;
3916                 },
3917
3918                 label: function() {
3919                         var key = arguments[0];
3920                         var args = [ ];
3921
3922                         for (var i = 1; i < arguments.length; i++)
3923                                 args.push(arguments[i]);
3924
3925                         switch (typeof(this.options[key]))
3926                         {
3927                         case 'undefined':
3928                                 return '';
3929
3930                         case 'function':
3931                                 return this.options[key].apply(this, args);
3932
3933                         default:
3934                                 return ''.format.apply('' + this.options[key], args);
3935                         }
3936                 },
3937
3938                 toString: function() {
3939                         return $('<div />').append(this.render()).html();
3940                 },
3941
3942                 insertInto: function(id) {
3943                         return $(id).empty().append(this.render());
3944                 },
3945
3946                 appendTo: function(id) {
3947                         return $(id).append(this.render());
3948                 }
3949         });
3950
3951         this.ui.view = this.ui.AbstractWidget.extend({
3952                 _fetch_template: function()
3953                 {
3954                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
3955                                 method: 'GET',
3956                                 cache: true,
3957                                 dataType: 'text',
3958                                 success: function(data) {
3959                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
3960                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
3961                                                 switch (p1)
3962                                                 {
3963                                                 case '#':
3964                                                         return '';
3965
3966                                                 case ':':
3967                                                         return _luci2.tr(p2);
3968
3969                                                 case '=':
3970                                                         return _luci2.globals[p2] || '';
3971
3972                                                 default:
3973                                                         return '(?' + match + ')';
3974                                                 }
3975                                         });
3976
3977                                         $('#maincontent').append(data);
3978                                 }
3979                         });
3980                 },
3981
3982                 execute: function()
3983                 {
3984                         throw "Not implemented";
3985                 },
3986
3987                 render: function()
3988                 {
3989                         var container = $('#maincontent');
3990
3991                         container.empty();
3992
3993                         if (this.title)
3994                                 container.append($('<h2 />').append(this.title));
3995
3996                         if (this.description)
3997                                 container.append($('<p />').append(this.description));
3998
3999                         var self = this;
4000                         var args = [ ];
4001
4002                         for (var i = 0; i < arguments.length; i++)
4003                                 args.push(arguments[i]);
4004
4005                         return this._fetch_template().then(function() {
4006                                 return _luci2.deferrable(self.execute.apply(self, args));
4007                         });
4008                 },
4009
4010                 repeat: function(func, interval)
4011                 {
4012                         var self = this;
4013
4014                         if (!self._timeouts)
4015                                 self._timeouts = [ ];
4016
4017                         var index = self._timeouts.length;
4018
4019                         if (typeof(interval) != 'number')
4020                                 interval = 5000;
4021
4022                         var setTimer, runTimer;
4023
4024                         setTimer = function() {
4025                                 if (self._timeouts)
4026                                         self._timeouts[index] = window.setTimeout(runTimer, interval);
4027                         };
4028
4029                         runTimer = function() {
4030                                 _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
4031                         };
4032
4033                         runTimer();
4034                 },
4035
4036                 finish: function()
4037                 {
4038                         if ($.isArray(this._timeouts))
4039                         {
4040                                 for (var i = 0; i < this._timeouts.length; i++)
4041                                         window.clearTimeout(this._timeouts[i]);
4042
4043                                 delete this._timeouts;
4044                         }
4045                 }
4046         });
4047
4048         this.ui.menu = this.ui.AbstractWidget.extend({
4049                 init: function() {
4050                         this._nodes = { };
4051                 },
4052
4053                 entries: function(entries)
4054                 {
4055                         for (var entry in entries)
4056                         {
4057                                 var path = entry.split(/\//);
4058                                 var node = this._nodes;
4059
4060                                 for (i = 0; i < path.length; i++)
4061                                 {
4062                                         if (!node.childs)
4063                                                 node.childs = { };
4064
4065                                         if (!node.childs[path[i]])
4066                                                 node.childs[path[i]] = { };
4067
4068                                         node = node.childs[path[i]];
4069                                 }
4070
4071                                 $.extend(node, entries[entry]);
4072                         }
4073                 },
4074
4075                 _indexcmp: function(a, b)
4076                 {
4077                         var x = a.index || 0;
4078                         var y = b.index || 0;
4079                         return (x - y);
4080                 },
4081
4082                 firstChildView: function(node)
4083                 {
4084                         if (node.view)
4085                                 return node;
4086
4087                         var nodes = [ ];
4088                         for (var child in (node.childs || { }))
4089                                 nodes.push(node.childs[child]);
4090
4091                         nodes.sort(this._indexcmp);
4092
4093                         for (var i = 0; i < nodes.length; i++)
4094                         {
4095                                 var child = this.firstChildView(nodes[i]);
4096                                 if (child)
4097                                 {
4098                                         for (var key in child)
4099                                                 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
4100                                                         node[key] = child[key];
4101
4102                                         return node;
4103                                 }
4104                         }
4105
4106                         return undefined;
4107                 },
4108
4109                 _onclick: function(ev)
4110                 {
4111                         _luci2.setHash('view', ev.data);
4112
4113                         ev.preventDefault();
4114                         this.blur();
4115                 },
4116
4117                 _render: function(childs, level, min, max)
4118                 {
4119                         var nodes = [ ];
4120                         for (var node in childs)
4121                         {
4122                                 var child = this.firstChildView(childs[node]);
4123                                 if (child)
4124                                         nodes.push(childs[node]);
4125                         }
4126
4127                         nodes.sort(this._indexcmp);
4128
4129                         var list = $('<ul />');
4130
4131                         if (level == 0)
4132                                 list.addClass('nav').addClass('navbar-nav');
4133                         else if (level == 1)
4134                                 list.addClass('dropdown-menu').addClass('navbar-inverse');
4135
4136                         for (var i = 0; i < nodes.length; i++)
4137                         {
4138                                 if (!_luci2.globals.defaultNode)
4139                                 {
4140                                         var v = _luci2.getHash('view');
4141                                         if (!v || v == nodes[i].view)
4142                                                 _luci2.globals.defaultNode = nodes[i];
4143                                 }
4144
4145                                 var item = $('<li />')
4146                                         .append($('<a />')
4147                                                 .attr('href', '#')
4148                                                 .text(_luci2.tr(nodes[i].title)))
4149                                         .appendTo(list);
4150
4151                                 if (nodes[i].childs && level < max)
4152                                 {
4153                                         item.addClass('dropdown');
4154
4155                                         item.find('a')
4156                                                 .addClass('dropdown-toggle')
4157                                                 .attr('data-toggle', 'dropdown')
4158                                                 .append('<b class="caret"></b>');
4159
4160                                         item.append(this._render(nodes[i].childs, level + 1));
4161                                 }
4162                                 else
4163                                 {
4164                                         item.find('a').click(nodes[i].view, this._onclick);
4165                                 }
4166                         }
4167
4168                         return list.get(0);
4169                 },
4170
4171                 render: function(min, max)
4172                 {
4173                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
4174                         return this._render(top.childs, 0, min, max);
4175                 },
4176
4177                 getNode: function(path, max)
4178                 {
4179                         var p = path.split(/\//);
4180                         var n = this._nodes;
4181
4182                         if (typeof(max) == 'undefined')
4183                                 max = p.length;
4184
4185                         for (var i = 0; i < max; i++)
4186                         {
4187                                 if (!n.childs[p[i]])
4188                                         return undefined;
4189
4190                                 n = n.childs[p[i]];
4191                         }
4192
4193                         return n;
4194                 }
4195         });
4196
4197         this.ui.table = this.ui.AbstractWidget.extend({
4198                 init: function()
4199                 {
4200                         this._rows = [ ];
4201                 },
4202
4203                 row: function(values)
4204                 {
4205                         if ($.isArray(values))
4206                         {
4207                                 this._rows.push(values);
4208                         }
4209                         else if ($.isPlainObject(values))
4210                         {
4211                                 var v = [ ];
4212                                 for (var i = 0; i < this.options.columns.length; i++)
4213                                 {
4214                                         var col = this.options.columns[i];
4215
4216                                         if (typeof col.key == 'string')
4217                                                 v.push(values[col.key]);
4218                                         else
4219                                                 v.push(null);
4220                                 }
4221                                 this._rows.push(v);
4222                         }
4223                 },
4224
4225                 rows: function(rows)
4226                 {
4227                         for (var i = 0; i < rows.length; i++)
4228                                 this.row(rows[i]);
4229                 },
4230
4231                 render: function(id)
4232                 {
4233                         var fieldset = document.createElement('fieldset');
4234                                 fieldset.className = 'cbi-section';
4235
4236                         if (this.options.caption)
4237                         {
4238                                 var legend = document.createElement('legend');
4239                                 $(legend).append(this.options.caption);
4240                                 fieldset.appendChild(legend);
4241                         }
4242
4243                         var table = document.createElement('table');
4244                                 table.className = 'table table-condensed table-hover';
4245
4246                         var has_caption = false;
4247                         var has_description = false;
4248
4249                         for (var i = 0; i < this.options.columns.length; i++)
4250                                 if (this.options.columns[i].caption)
4251                                 {
4252                                         has_caption = true;
4253                                         break;
4254                                 }
4255                                 else if (this.options.columns[i].description)
4256                                 {
4257                                         has_description = true;
4258                                         break;
4259                                 }
4260
4261                         if (has_caption)
4262                         {
4263                                 var tr = table.insertRow(-1);
4264                                         tr.className = 'cbi-section-table-titles';
4265
4266                                 for (var i = 0; i < this.options.columns.length; i++)
4267                                 {
4268                                         var col = this.options.columns[i];
4269                                         var th = document.createElement('th');
4270                                                 th.className = 'cbi-section-table-cell';
4271
4272                                         tr.appendChild(th);
4273
4274                                         if (col.width)
4275                                                 th.style.width = col.width;
4276
4277                                         if (col.align)
4278                                                 th.style.textAlign = col.align;
4279
4280                                         if (col.caption)
4281                                                 $(th).append(col.caption);
4282                                 }
4283                         }
4284
4285                         if (has_description)
4286                         {
4287                                 var tr = table.insertRow(-1);
4288                                         tr.className = 'cbi-section-table-descr';
4289
4290                                 for (var i = 0; i < this.options.columns.length; i++)
4291                                 {
4292                                         var col = this.options.columns[i];
4293                                         var th = document.createElement('th');
4294                                                 th.className = 'cbi-section-table-cell';
4295
4296                                         tr.appendChild(th);
4297
4298                                         if (col.width)
4299                                                 th.style.width = col.width;
4300
4301                                         if (col.align)
4302                                                 th.style.textAlign = col.align;
4303
4304                                         if (col.description)
4305                                                 $(th).append(col.description);
4306                                 }
4307                         }
4308
4309                         if (this._rows.length == 0)
4310                         {
4311                                 if (this.options.placeholder)
4312                                 {
4313                                         var tr = table.insertRow(-1);
4314                                         var td = tr.insertCell(-1);
4315                                                 td.className = 'cbi-section-table-cell';
4316
4317                                         td.colSpan = this.options.columns.length;
4318                                         $(td).append(this.options.placeholder);
4319                                 }
4320                         }
4321                         else
4322                         {
4323                                 for (var i = 0; i < this._rows.length; i++)
4324                                 {
4325                                         var tr = table.insertRow(-1);
4326
4327                                         for (var j = 0; j < this.options.columns.length; j++)
4328                                         {
4329                                                 var col = this.options.columns[j];
4330                                                 var td = tr.insertCell(-1);
4331
4332                                                 var val = this._rows[i][j];
4333
4334                                                 if (typeof(val) == 'undefined')
4335                                                         val = col.placeholder;
4336
4337                                                 if (typeof(val) == 'undefined')
4338                                                         val = '';
4339
4340                                                 if (col.width)
4341                                                         td.style.width = col.width;
4342
4343                                                 if (col.align)
4344                                                         td.style.textAlign = col.align;
4345
4346                                                 if (typeof col.format == 'string')
4347                                                         $(td).append(col.format.format(val));
4348                                                 else if (typeof col.format == 'function')
4349                                                         $(td).append(col.format(val, i));
4350                                                 else
4351                                                         $(td).append(val);
4352                                         }
4353                                 }
4354                         }
4355
4356                         this._rows = [ ];
4357                         fieldset.appendChild(table);
4358
4359                         return fieldset;
4360                 }
4361         });
4362
4363         this.ui.progress = this.ui.AbstractWidget.extend({
4364                 render: function()
4365                 {
4366                         var vn = parseInt(this.options.value) || 0;
4367                         var mn = parseInt(this.options.max) || 100;
4368                         var pc = Math.floor((100 / mn) * vn);
4369
4370                         var text;
4371
4372                         if (typeof(this.options.format) == 'string')
4373                                 text = this.options.format.format(this.options.value, this.options.max, pc);
4374                         else if (typeof(this.options.format) == 'function')
4375                                 text = this.options.format(pc);
4376                         else
4377                                 text = '%.2f%%'.format(pc);
4378
4379                         return $('<div />')
4380                                 .addClass('progress')
4381                                 .append($('<div />')
4382                                         .addClass('progress-bar')
4383                                         .addClass('progress-bar-info')
4384                                         .css('width', pc + '%'))
4385                                 .append($('<small />')
4386                                         .text(text));
4387                 }
4388         });
4389
4390         this.ui.devicebadge = this.ui.AbstractWidget.extend({
4391                 render: function()
4392                 {
4393                         var l2dev = this.options.l2_device || this.options.device;
4394                         var l3dev = this.options.l3_device;
4395                         var dev = l3dev || l2dev || '?';
4396
4397                         var span = document.createElement('span');
4398                                 span.className = 'badge';
4399
4400                         if (typeof(this.options.signal) == 'number' ||
4401                                 typeof(this.options.noise) == 'number')
4402                         {
4403                                 var r = 'none';
4404                                 if (typeof(this.options.signal) != 'undefined' &&
4405                                         typeof(this.options.noise) != 'undefined')
4406                                 {
4407                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
4408                                         if (q < 1)
4409                                                 r = '0';
4410                                         else if (q < 2)
4411                                                 r = '0-25';
4412                                         else if (q < 3)
4413                                                 r = '25-50';
4414                                         else if (q < 4)
4415                                                 r = '50-75';
4416                                         else
4417                                                 r = '75-100';
4418                                 }
4419
4420                                 span.appendChild(document.createElement('img'));
4421                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
4422
4423                                 if (r == 'none')
4424                                         span.title = _luci2.tr('No signal');
4425                                 else
4426                                         span.title = '%s: %d %s / %s: %d %s'.format(
4427                                                 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
4428                                                 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
4429                                         );
4430                         }
4431                         else
4432                         {
4433                                 var type = 'ethernet';
4434                                 var desc = _luci2.tr('Ethernet device');
4435
4436                                 if (l3dev != l2dev)
4437                                 {
4438                                         type = 'tunnel';
4439                                         desc = _luci2.tr('Tunnel interface');
4440                                 }
4441                                 else if (dev.indexOf('br-') == 0)
4442                                 {
4443                                         type = 'bridge';
4444                                         desc = _luci2.tr('Bridge');
4445                                 }
4446                                 else if (dev.indexOf('.') > 0)
4447                                 {
4448                                         type = 'vlan';
4449                                         desc = _luci2.tr('VLAN interface');
4450                                 }
4451                                 else if (dev.indexOf('wlan') == 0 ||
4452                                                  dev.indexOf('ath') == 0 ||
4453                                                  dev.indexOf('wl') == 0)
4454                                 {
4455                                         type = 'wifi';
4456                                         desc = _luci2.tr('Wireless Network');
4457                                 }
4458
4459                                 span.appendChild(document.createElement('img'));
4460                                 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
4461                                 span.title = desc;
4462                         }
4463
4464                         $(span).append(' ');
4465                         $(span).append(dev);
4466
4467                         return span;
4468                 }
4469         });
4470
4471         var type = function(f, l)
4472         {
4473                 f.message = l;
4474                 return f;
4475         };
4476
4477         this.cbi = {
4478                 validation: {
4479                         i18n: function(msg)
4480                         {
4481                                 _luci2.cbi.validation.message = _luci2.tr(msg);
4482                         },
4483
4484                         compile: function(code)
4485                         {
4486                                 var pos = 0;
4487                                 var esc = false;
4488                                 var depth = 0;
4489                                 var types = _luci2.cbi.validation.types;
4490                                 var stack = [ ];
4491
4492                                 code += ',';
4493
4494                                 for (var i = 0; i < code.length; i++)
4495                                 {
4496                                         if (esc)
4497                                         {
4498                                                 esc = false;
4499                                                 continue;
4500                                         }
4501
4502                                         switch (code.charCodeAt(i))
4503                                         {
4504                                         case 92:
4505                                                 esc = true;
4506                                                 break;
4507
4508                                         case 40:
4509                                         case 44:
4510                                                 if (depth <= 0)
4511                                                 {
4512                                                         if (pos < i)
4513                                                         {
4514                                                                 var label = code.substring(pos, i);
4515                                                                         label = label.replace(/\\(.)/g, '$1');
4516                                                                         label = label.replace(/^[ \t]+/g, '');
4517                                                                         label = label.replace(/[ \t]+$/g, '');
4518
4519                                                                 if (label && !isNaN(label))
4520                                                                 {
4521                                                                         stack.push(parseFloat(label));
4522                                                                 }
4523                                                                 else if (label.match(/^(['"]).*\1$/))
4524                                                                 {
4525                                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
4526                                                                 }
4527                                                                 else if (typeof types[label] == 'function')
4528                                                                 {
4529                                                                         stack.push(types[label]);
4530                                                                         stack.push([ ]);
4531                                                                 }
4532                                                                 else
4533                                                                 {
4534                                                                         throw "Syntax error, unhandled token '"+label+"'";
4535                                                                 }
4536                                                         }
4537                                                         pos = i+1;
4538                                                 }
4539                                                 depth += (code.charCodeAt(i) == 40);
4540                                                 break;
4541
4542                                         case 41:
4543                                                 if (--depth <= 0)
4544                                                 {
4545                                                         if (typeof stack[stack.length-2] != 'function')
4546                                                                 throw "Syntax error, argument list follows non-function";
4547
4548                                                         stack[stack.length-1] =
4549                                                                 _luci2.cbi.validation.compile(code.substring(pos, i));
4550
4551                                                         pos = i+1;
4552                                                 }
4553                                                 break;
4554                                         }
4555                                 }
4556
4557                                 return stack;
4558                         }
4559                 }
4560         };
4561
4562         var validation = this.cbi.validation;
4563
4564         validation.types = {
4565                 'integer': function()
4566                 {
4567                         if (this.match(/^-?[0-9]+$/) != null)
4568                                 return true;
4569
4570                         validation.i18n('Must be a valid integer');
4571                         return false;
4572                 },
4573
4574                 'uinteger': function()
4575                 {
4576                         if (validation.types['integer'].apply(this) && (this >= 0))
4577                                 return true;
4578
4579                         validation.i18n('Must be a positive integer');
4580                         return false;
4581                 },
4582
4583                 'float': function()
4584                 {
4585                         if (!isNaN(parseFloat(this)))
4586                                 return true;
4587
4588                         validation.i18n('Must be a valid number');
4589                         return false;
4590                 },
4591
4592                 'ufloat': function()
4593                 {
4594                         if (validation.types['float'].apply(this) && (this >= 0))
4595                                 return true;
4596
4597                         validation.i18n('Must be a positive number');
4598                         return false;
4599                 },
4600
4601                 'ipaddr': function()
4602                 {
4603                         if (validation.types['ip4addr'].apply(this) ||
4604                                 validation.types['ip6addr'].apply(this))
4605                                 return true;
4606
4607                         validation.i18n('Must be a valid IP address');
4608                         return false;
4609                 },
4610
4611                 'ip4addr': function()
4612                 {
4613                         if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
4614                         {
4615                                 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
4616                                     (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
4617                                     (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
4618                                     (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
4619                                     ((RegExp.$6.indexOf('.') < 0)
4620                                       ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
4621                                       : (validation.types['ip4addr'].apply(RegExp.$6))))
4622                                         return true;
4623                         }
4624
4625                         validation.i18n('Must be a valid IPv4 address');
4626                         return false;
4627                 },
4628
4629                 'ip6addr': function()
4630                 {
4631                         if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
4632                         {
4633                                 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
4634                                 {
4635                                         var addr = RegExp.$1;
4636
4637                                         if (addr == '::')
4638                                         {
4639                                                 return true;
4640                                         }
4641
4642                                         if (addr.indexOf('.') > 0)
4643                                         {
4644                                                 var off = addr.lastIndexOf(':');
4645
4646                                                 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
4647                                                 {
4648                                                         validation.i18n('Must be a valid IPv6 address');
4649                                                         return false;
4650                                                 }
4651
4652                                                 addr = addr.substr(0, off) + ':0:0';
4653                                         }
4654
4655                                         if (addr.indexOf('::') >= 0)
4656                                         {
4657                                                 var colons = 0;
4658                                                 var fill = '0';
4659
4660                                                 for (var i = 1; i < (addr.length-1); i++)
4661                                                         if (addr.charAt(i) == ':')
4662                                                                 colons++;
4663
4664                                                 if (colons > 7)
4665                                                 {
4666                                                         validation.i18n('Must be a valid IPv6 address');
4667                                                         return false;
4668                                                 }
4669
4670                                                 for (var i = 0; i < (7 - colons); i++)
4671                                                         fill += ':0';
4672
4673                                                 if (addr.match(/^(.*?)::(.*?)$/))
4674                                                         addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
4675                                                                    (RegExp.$2 ? ':' + RegExp.$2 : '');
4676                                         }
4677
4678                                         if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
4679                                                 return true;
4680
4681                                         validation.i18n('Must be a valid IPv6 address');
4682                                         return false;
4683                                 }
4684                         }
4685
4686                         validation.i18n('Must be a valid IPv6 address');
4687                         return false;
4688                 },
4689
4690                 'port': function()
4691                 {
4692                         if (validation.types['integer'].apply(this) &&
4693                                 (this >= 0) && (this <= 65535))
4694                                 return true;
4695
4696                         validation.i18n('Must be a valid port number');
4697                         return false;
4698                 },
4699
4700                 'portrange': function()
4701                 {
4702                         if (this.match(/^(\d+)-(\d+)$/))
4703                         {
4704                                 var p1 = RegExp.$1;
4705                                 var p2 = RegExp.$2;
4706
4707                                 if (validation.types['port'].apply(p1) &&
4708                                     validation.types['port'].apply(p2) &&
4709                                     (parseInt(p1) <= parseInt(p2)))
4710                                         return true;
4711                         }
4712                         else if (validation.types['port'].apply(this))
4713                         {
4714                                 return true;
4715                         }
4716
4717                         validation.i18n('Must be a valid port range');
4718                         return false;
4719                 },
4720
4721                 'macaddr': function()
4722                 {
4723                         if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
4724                                 return true;
4725
4726                         validation.i18n('Must be a valid MAC address');
4727                         return false;
4728                 },
4729
4730                 'host': function()
4731                 {
4732                         if (validation.types['hostname'].apply(this) ||
4733                             validation.types['ipaddr'].apply(this))
4734                                 return true;
4735
4736                         validation.i18n('Must be a valid hostname or IP address');
4737                         return false;
4738                 },
4739
4740                 'hostname': function()
4741                 {
4742                         if ((this.length <= 253) &&
4743                             ((this.match(/^[a-zA-Z0-9]+$/) != null ||
4744                              (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
4745                               this.match(/[^0-9.]/)))))
4746                                 return true;
4747
4748                         validation.i18n('Must be a valid host name');
4749                         return false;
4750                 },
4751
4752                 'network': function()
4753                 {
4754                         if (validation.types['uciname'].apply(this) ||
4755                             validation.types['host'].apply(this))
4756                                 return true;
4757
4758                         validation.i18n('Must be a valid network name');
4759                         return false;
4760                 },
4761
4762                 'wpakey': function()
4763                 {
4764                         var v = this;
4765
4766                         if ((v.length == 64)
4767                               ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
4768                                   : ((v.length >= 8) && (v.length <= 63)))
4769                                 return true;
4770
4771                         validation.i18n('Must be a valid WPA key');
4772                         return false;
4773                 },
4774
4775                 'wepkey': function()
4776                 {
4777                         var v = this;
4778
4779                         if (v.substr(0,2) == 's:')
4780                                 v = v.substr(2);
4781
4782                         if (((v.length == 10) || (v.length == 26))
4783                               ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
4784                               : ((v.length == 5) || (v.length == 13)))
4785                                 return true;
4786
4787                         validation.i18n('Must be a valid WEP key');
4788                         return false;
4789                 },
4790
4791                 'uciname': function()
4792                 {
4793                         if (this.match(/^[a-zA-Z0-9_]+$/) != null)
4794                                 return true;
4795
4796                         validation.i18n('Must be a valid UCI identifier');
4797                         return false;
4798                 },
4799
4800                 'range': function(min, max)
4801                 {
4802                         var val = parseFloat(this);
4803
4804                         if (validation.types['integer'].apply(this) &&
4805                             !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
4806                                 return true;
4807
4808                         validation.i18n('Must be a number between %d and %d');
4809                         return false;
4810                 },
4811
4812                 'min': function(min)
4813                 {
4814                         var val = parseFloat(this);
4815
4816                         if (validation.types['integer'].apply(this) &&
4817                             !isNaN(min) && !isNaN(val) && (val >= min))
4818                                 return true;
4819
4820                         validation.i18n('Must be a number greater or equal to %d');
4821                         return false;
4822                 },
4823
4824                 'max': function(max)
4825                 {
4826                         var val = parseFloat(this);
4827
4828                         if (validation.types['integer'].apply(this) &&
4829                             !isNaN(max) && !isNaN(val) && (val <= max))
4830                                 return true;
4831
4832                         validation.i18n('Must be a number lower or equal to %d');
4833                         return false;
4834                 },
4835
4836                 'rangelength': function(min, max)
4837                 {
4838                         var val = '' + this;
4839
4840                         if (!isNaN(min) && !isNaN(max) &&
4841                             (val.length >= min) && (val.length <= max))
4842                                 return true;
4843
4844                         validation.i18n('Must be between %d and %d characters');
4845                         return false;
4846                 },
4847
4848                 'minlength': function(min)
4849                 {
4850                         var val = '' + this;
4851
4852                         if (!isNaN(min) && (val.length >= min))
4853                                 return true;
4854
4855                         validation.i18n('Must be at least %d characters');
4856                         return false;
4857                 },
4858
4859                 'maxlength': function(max)
4860                 {
4861                         var val = '' + this;
4862
4863                         if (!isNaN(max) && (val.length <= max))
4864                                 return true;
4865
4866                         validation.i18n('Must be at most %d characters');
4867                         return false;
4868                 },
4869
4870                 'or': function()
4871                 {
4872                         var msgs = [ ];
4873
4874                         for (var i = 0; i < arguments.length; i += 2)
4875                         {
4876                                 delete validation.message;
4877
4878                                 if (typeof(arguments[i]) != 'function')
4879                                 {
4880                                         if (arguments[i] == this)
4881                                                 return true;
4882                                         i--;
4883                                 }
4884                                 else if (arguments[i].apply(this, arguments[i+1]))
4885                                 {
4886                                         return true;
4887                                 }
4888
4889                                 if (validation.message)
4890                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
4891                         }
4892
4893                         validation.message = msgs.join( _luci2.tr(' - or - '));
4894                         return false;
4895                 },
4896
4897                 'and': function()
4898                 {
4899                         var msgs = [ ];
4900
4901                         for (var i = 0; i < arguments.length; i += 2)
4902                         {
4903                                 delete validation.message;
4904
4905                                 if (typeof arguments[i] != 'function')
4906                                 {
4907                                         if (arguments[i] != this)
4908                                                 return false;
4909                                         i--;
4910                                 }
4911                                 else if (!arguments[i].apply(this, arguments[i+1]))
4912                                 {
4913                                         return false;
4914                                 }
4915
4916                                 if (validation.message)
4917                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
4918                         }
4919
4920                         validation.message = msgs.join(', ');
4921                         return true;
4922                 },
4923
4924                 'neg': function()
4925                 {
4926                         return validation.types['or'].apply(
4927                                 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
4928                 },
4929
4930                 'list': function(subvalidator, subargs)
4931                 {
4932                         if (typeof subvalidator != 'function')
4933                                 return false;
4934
4935                         var tokens = this.match(/[^ \t]+/g);
4936                         for (var i = 0; i < tokens.length; i++)
4937                                 if (!subvalidator.apply(tokens[i], subargs))
4938                                         return false;
4939
4940                         return true;
4941                 },
4942
4943                 'phonedigit': function()
4944                 {
4945                         if (this.match(/^[0-9\*#!\.]+$/) != null)
4946                                 return true;
4947
4948                         validation.i18n('Must be a valid phone number digit');
4949                         return false;
4950                 },
4951
4952                 'string': function()
4953                 {
4954                         return true;
4955                 }
4956         };
4957
4958
4959         this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
4960                 init: function(name, options)
4961                 {
4962                         this.name = name;
4963                         this.instance = { };
4964                         this.dependencies = [ ];
4965                         this.rdependency = { };
4966
4967                         this.options = _luci2.defaults(options, {
4968                                 placeholder: '',
4969                                 datatype: 'string',
4970                                 optional: false,
4971                                 keep: true
4972                         });
4973                 },
4974
4975                 id: function(sid)
4976                 {
4977                         return this.section.id('field', sid || '__unknown__', this.name);
4978                 },
4979
4980                 render: function(sid, condensed)
4981                 {
4982                         var i = this.instance[sid] = { };
4983
4984                         i.top = $('<div />');
4985
4986                         if (!condensed)
4987                         {
4988                                 i.top.addClass('form-group');
4989
4990                                 if (typeof(this.options.caption) == 'string')
4991                                         $('<label />')
4992                                                 .addClass('col-lg-2 control-label')
4993                                                 .attr('for', this.id(sid))
4994                                                 .text(this.options.caption)
4995                                                 .appendTo(i.top);
4996                         }
4997
4998                         i.error = $('<div />')
4999                                 .hide()
5000                                 .addClass('label label-danger');
5001
5002                         i.widget = $('<div />')
5003
5004                                 .append(this.widget(sid))
5005                                 .append(i.error)
5006                                 .appendTo(i.top);
5007
5008                         if (!condensed)
5009                         {
5010                                 i.widget.addClass('col-lg-5');
5011
5012                                 $('<div />')
5013                                         .addClass('col-lg-5')
5014                                         .text((typeof(this.options.description) == 'string') ? this.options.description : '')
5015                                         .appendTo(i.top);
5016                         }
5017
5018                         return i.top;
5019                 },
5020
5021                 ucipath: function(sid)
5022                 {
5023                         return {
5024                                 config:  (this.options.uci_package || this.map.uci_package),
5025                                 section: (this.options.uci_section || sid),
5026                                 option:  (this.options.uci_option  || this.name)
5027                         };
5028                 },
5029
5030                 ucivalue: function(sid)
5031                 {
5032                         var uci = this.ucipath(sid);
5033                         var val = this.map.get(uci.config, uci.section, uci.option);
5034
5035                         if (typeof(val) == 'undefined')
5036                                 return this.options.initial;
5037
5038                         return val;
5039                 },
5040
5041                 formvalue: function(sid)
5042                 {
5043                         var v = $('#' + this.id(sid)).val();
5044                         return (v === '') ? undefined : v;
5045                 },
5046
5047                 textvalue: function(sid)
5048                 {
5049                         var v = this.formvalue(sid);
5050
5051                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
5052                                 v = this.ucivalue(sid);
5053
5054                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
5055                                 v = this.options.placeholder;
5056
5057                         if (typeof(v) == 'undefined' || v === '')
5058                                 return undefined;
5059
5060                         if (typeof(v) == 'string' && $.isArray(this.choices))
5061                         {
5062                                 for (var i = 0; i < this.choices.length; i++)
5063                                         if (v === this.choices[i][0])
5064                                                 return this.choices[i][1];
5065                         }
5066                         else if (v === true)
5067                                 return _luci2.tr('yes');
5068                         else if (v === false)
5069                                 return _luci2.tr('no');
5070                         else if ($.isArray(v))
5071                                 return v.join(', ');
5072
5073                         return v;
5074                 },
5075
5076                 changed: function(sid)
5077                 {
5078                         var a = this.ucivalue(sid);
5079                         var b = this.formvalue(sid);
5080
5081                         if (typeof(a) != typeof(b))
5082                                 return true;
5083
5084                         if (typeof(a) == 'object')
5085                         {
5086                                 if (a.length != b.length)
5087                                         return true;
5088
5089                                 for (var i = 0; i < a.length; i++)
5090                                         if (a[i] != b[i])
5091                                                 return true;
5092
5093                                 return false;
5094                         }
5095
5096                         return (a != b);
5097                 },
5098
5099                 save: function(sid)
5100                 {
5101                         var uci = this.ucipath(sid);
5102
5103                         if (this.instance[sid].disabled)
5104                         {
5105                                 if (!this.options.keep)
5106                                         return this.map.set(uci.config, uci.section, uci.option, undefined);
5107
5108                                 return false;
5109                         }
5110
5111                         var chg = this.changed(sid);
5112                         var val = this.formvalue(sid);
5113
5114                         if (chg)
5115                                 this.map.set(uci.config, uci.section, uci.option, val);
5116
5117                         return chg;
5118                 },
5119
5120                 _ev_validate: function(ev)
5121                 {
5122                         var d = ev.data;
5123                         var rv = true;
5124                         var val = d.elem.val();
5125                         var vstack = d.vstack;
5126
5127                         if (vstack && typeof(vstack[0]) == 'function')
5128                         {
5129                                 delete validation.message;
5130
5131                                 if ((val.length == 0 && !d.opt))
5132                                 {
5133                                         d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
5134                                         d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5135
5136                                         d.inst.error.text(_luci2.tr('Field must not be empty')).show();
5137                                         rv = false;
5138                                 }
5139                                 else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
5140                                 {
5141                                         d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
5142                                         d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
5143
5144                                         d.inst.error.text(validation.message.format.apply(validation.message, vstack[1])).show();
5145                                         rv = false;
5146                                 }
5147                                 else
5148                                 {
5149                                         d.elem.parents('div.form-group, td').first().removeClass('luci2-form-error');
5150                                         d.elem.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
5151
5152                                         if (d.multi && d.inst.widget && d.inst.widget.find('input.error, select.error').length > 0)
5153                                                 rv = false;
5154                                         else
5155                                                 d.inst.error.text('').hide();
5156                                 }
5157                         }
5158
5159                         if (rv)
5160                                 for (var field in d.self.rdependency)
5161                                         d.self.rdependency[field].toggle(d.sid);
5162
5163                         return rv;
5164                 },
5165
5166                 validator: function(sid, elem, multi)
5167                 {
5168                         if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
5169                                 return elem;
5170
5171                         var vstack;
5172                         if (typeof(this.options.datatype) == 'string')
5173                         {
5174                                 try {
5175                                         vstack = _luci2.cbi.validation.compile(this.options.datatype);
5176                                 } catch(e) { };
5177                         }
5178                         else if (typeof(this.options.datatype) == 'function')
5179                         {
5180                                 var vfunc = this.options.datatype;
5181                                 vstack = [ function(elem) {
5182                                         var rv = vfunc(this, elem);
5183                                         if (rv !== true)
5184                                                 validation.message = rv;
5185                                         return (rv === true);
5186                                 }, [ elem ] ];
5187                         }
5188
5189                         var evdata = {
5190                                 self:   this,
5191                                 sid:    sid,
5192                                 elem:   elem,
5193                                 multi:  multi,
5194                                 vstack: vstack,
5195                                 inst:   this.instance[sid],
5196                                 opt:    this.options.optional
5197                         };
5198
5199                         if (elem.prop('tagName') == 'SELECT')
5200                         {
5201                                 elem.change(evdata, this._ev_validate);
5202                         }
5203                         else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
5204                         {
5205                                 elem.click(evdata, this._ev_validate);
5206                                 elem.blur(evdata, this._ev_validate);
5207                         }
5208                         else
5209                         {
5210                                 elem.keyup(evdata, this._ev_validate);
5211                                 elem.blur(evdata, this._ev_validate);
5212                         }
5213
5214                         elem.attr('cbi-validate', true).on('validate', evdata, this._ev_validate);
5215
5216                         return elem;
5217                 },
5218
5219                 validate: function(sid)
5220                 {
5221                         var i = this.instance[sid];
5222
5223                         i.widget.find('[cbi-validate]').trigger('validate');
5224
5225                         return (i.disabled || i.error.text() == '');
5226                 },
5227
5228                 depends: function(d, v)
5229                 {
5230                         var dep;
5231
5232                         if ($.isArray(d))
5233                         {
5234                                 dep = { };
5235                                 for (var i = 0; i < d.length; i++)
5236                                 {
5237                                         if (typeof(d[i]) == 'string')
5238                                                 dep[d[i]] = true;
5239                                         else if (d[i] instanceof _luci2.cbi.AbstractValue)
5240                                                 dep[d[i].name] = true;
5241                                 }
5242                         }
5243                         else if (d instanceof _luci2.cbi.AbstractValue)
5244                         {
5245                                 dep = { };
5246                                 dep[d.name] = (typeof(v) == 'undefined') ? true : v;
5247                         }
5248                         else if (typeof(d) == 'object')
5249                         {
5250                                 dep = d;
5251                         }
5252                         else if (typeof(d) == 'string')
5253                         {
5254                                 dep = { };
5255                                 dep[d] = (typeof(v) == 'undefined') ? true : v;
5256                         }
5257
5258                         if (!dep || $.isEmptyObject(dep))
5259                                 return this;
5260
5261                         for (var field in dep)
5262                         {
5263                                 var f = this.section.fields[field];
5264                                 if (f)
5265                                         f.rdependency[this.name] = this;
5266                                 else
5267                                         delete dep[field];
5268                         }
5269
5270                         if ($.isEmptyObject(dep))
5271                                 return this;
5272
5273                         this.dependencies.push(dep);
5274
5275                         return this;
5276                 },
5277
5278                 toggle: function(sid)
5279                 {
5280                         var d = this.dependencies;
5281                         var i = this.instance[sid];
5282
5283                         if (!d.length)
5284                                 return true;
5285
5286                         for (var n = 0; n < d.length; n++)
5287                         {
5288                                 var rv = true;
5289
5290                                 for (var field in d[n])
5291                                 {
5292                                         var val = this.section.fields[field].formvalue(sid);
5293                                         var cmp = d[n][field];
5294
5295                                         if (typeof(cmp) == 'boolean')
5296                                         {
5297                                                 if (cmp == (typeof(val) == 'undefined' || val === '' || val === false))
5298                                                 {
5299                                                         rv = false;
5300                                                         break;
5301                                                 }
5302                                         }
5303                                         else if (typeof(cmp) == 'string')
5304                                         {
5305                                                 if (val != cmp)
5306                                                 {
5307                                                         rv = false;
5308                                                         break;
5309                                                 }
5310                                         }
5311                                         else if (typeof(cmp) == 'function')
5312                                         {
5313                                                 if (!cmp(val))
5314                                                 {
5315                                                         rv = false;
5316                                                         break;
5317                                                 }
5318                                         }
5319                                         else if (cmp instanceof RegExp)
5320                                         {
5321                                                 if (!cmp.test(val))
5322                                                 {
5323                                                         rv = false;
5324                                                         break;
5325                                                 }
5326                                         }
5327                                 }
5328
5329                                 if (rv)
5330                                 {
5331                                         if (i.disabled)
5332                                         {
5333                                                 i.disabled = false;
5334                                                 i.top.fadeIn();
5335                                         }
5336
5337                                         return true;
5338                                 }
5339                         }
5340
5341                         if (!i.disabled)
5342                         {
5343                                 i.disabled = true;
5344                                 i.top.is(':visible') ? i.top.fadeOut() : i.top.hide();
5345                         }
5346
5347                         return false;
5348                 }
5349         });
5350
5351         this.cbi.CheckboxValue = this.cbi.AbstractValue.extend({
5352                 widget: function(sid)
5353                 {
5354                         var o = this.options;
5355
5356                         if (typeof(o.enabled)  == 'undefined') o.enabled  = '1';
5357                         if (typeof(o.disabled) == 'undefined') o.disabled = '0';
5358
5359                         var i = $('<input />')
5360                                 .attr('id', this.id(sid))
5361                                 .attr('type', 'checkbox')
5362                                 .prop('checked', this.ucivalue(sid));
5363
5364                         return $('<div />')
5365                                 .addClass('checkbox')
5366                                 .append(this.validator(sid, i));
5367                 },
5368
5369                 ucivalue: function(sid)
5370                 {
5371                         var v = this.callSuper('ucivalue', sid);
5372
5373                         if (typeof(v) == 'boolean')
5374                                 return v;
5375
5376                         return (v == this.options.enabled);
5377                 },
5378
5379                 formvalue: function(sid)
5380                 {
5381                         var v = $('#' + this.id(sid)).prop('checked');
5382
5383                         if (typeof(v) == 'undefined')
5384                                 return !!this.options.initial;
5385
5386                         return v;
5387                 },
5388
5389                 save: function(sid)
5390                 {
5391                         var uci = this.ucipath(sid);
5392
5393                         if (this.instance[sid].disabled)
5394                         {
5395                                 if (!this.options.keep)
5396                                         return this.map.set(uci.config, uci.section, uci.option, undefined);
5397
5398                                 return false;
5399                         }
5400
5401                         var chg = this.changed(sid);
5402                         var val = this.formvalue(sid);
5403
5404                         if (chg)
5405                         {
5406                                 if (this.options.optional && val == this.options.initial)
5407                                         this.map.set(uci.config, uci.section, uci.option, undefined);
5408                                 else
5409                                         this.map.set(uci.config, uci.section, uci.option, val ? this.options.enabled : this.options.disabled);
5410                         }
5411
5412                         return chg;
5413                 }
5414         });
5415
5416         this.cbi.InputValue = this.cbi.AbstractValue.extend({
5417                 widget: function(sid)
5418                 {
5419                         var i = $('<input />')
5420                                 .addClass('form-control')
5421                                 .attr('id', this.id(sid))
5422                                 .attr('type', 'text')
5423                                 .attr('placeholder', this.options.placeholder)
5424                                 .val(this.ucivalue(sid));
5425
5426                         return this.validator(sid, i);
5427                 }
5428         });
5429
5430         this.cbi.PasswordValue = this.cbi.AbstractValue.extend({
5431                 widget: function(sid)
5432                 {
5433                         var i = $('<input />')
5434                                 .addClass('form-control')
5435                                 .attr('id', this.id(sid))
5436                                 .attr('type', 'password')
5437                                 .attr('placeholder', this.options.placeholder)
5438                                 .val(this.ucivalue(sid));
5439
5440                         var t = $('<span />')
5441                                 .addClass('input-group-btn')
5442                                 .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
5443                                         .click(function(ev) {
5444                                                 var b = $(this);
5445                                                 var i = b.parent().prev();
5446                                                 var t = i.attr('type');
5447                                                 b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
5448                                                 i.attr('type', (t == 'password') ? 'text' : 'password');
5449                                                 b = i = t = null;
5450                                         }));
5451
5452                         this.validator(sid, i);
5453
5454                         return $('<div />')
5455                                 .addClass('input-group')
5456                                 .append(i)
5457                                 .append(t);
5458                 }
5459         });
5460
5461         this.cbi.ListValue = this.cbi.AbstractValue.extend({
5462                 widget: function(sid)
5463                 {
5464                         var s = $('<select />')
5465                                 .addClass('form-control');
5466
5467                         if (this.options.optional)
5468                                 $('<option />')
5469                                         .attr('value', '')
5470                                         .text(_luci2.tr('-- Please choose --'))
5471                                         .appendTo(s);
5472
5473                         if (this.choices)
5474                                 for (var i = 0; i < this.choices.length; i++)
5475                                         $('<option />')
5476                                                 .attr('value', this.choices[i][0])
5477                                                 .text(this.choices[i][1])
5478                                                 .appendTo(s);
5479
5480                         s.attr('id', this.id(sid)).val(this.ucivalue(sid));
5481
5482                         return this.validator(sid, s);
5483                 },
5484
5485                 value: function(k, v)
5486                 {
5487                         if (!this.choices)
5488                                 this.choices = [ ];
5489
5490                         this.choices.push([k, v || k]);
5491                         return this;
5492                 }
5493         });
5494
5495         this.cbi.MultiValue = this.cbi.ListValue.extend({
5496                 widget: function(sid)
5497                 {
5498                         var v = this.ucivalue(sid);
5499                         var t = $('<div />').attr('id', this.id(sid));
5500
5501                         if (!$.isArray(v))
5502                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
5503
5504                         var s = { };
5505                         for (var i = 0; i < v.length; i++)
5506                                 s[v[i]] = true;
5507
5508                         if (this.choices)
5509                                 for (var i = 0; i < this.choices.length; i++)
5510                                 {
5511                                         $('<label />')
5512                                                 .addClass('checkbox')
5513                                                 .append($('<input />')
5514                                                         .attr('type', 'checkbox')
5515                                                         .attr('value', this.choices[i][0])
5516                                                         .prop('checked', s[this.choices[i][0]]))
5517                                                 .append(this.choices[i][1])
5518                                                 .appendTo(t);
5519                                 }
5520
5521                         return t;
5522                 },
5523
5524                 formvalue: function(sid)
5525                 {
5526                         var rv = [ ];
5527                         var fields = $('#' + this.id(sid) + ' > label > input');
5528
5529                         for (var i = 0; i < fields.length; i++)
5530                                 if (fields[i].checked)
5531                                         rv.push(fields[i].getAttribute('value'));
5532
5533                         return rv;
5534                 },
5535
5536                 textvalue: function(sid)
5537                 {
5538                         var v = this.formvalue(sid);
5539                         var c = { };
5540
5541                         if (this.choices)
5542                                 for (var i = 0; i < this.choices.length; i++)
5543                                         c[this.choices[i][0]] = this.choices[i][1];
5544
5545                         var t = [ ];
5546
5547                         for (var i = 0; i < v.length; i++)
5548                                 t.push(c[v[i]] || v[i]);
5549
5550                         return t.join(', ');
5551                 }
5552         });
5553
5554         this.cbi.ComboBox = this.cbi.AbstractValue.extend({
5555                 _change: function(ev)
5556                 {
5557                         var s = ev.target;
5558                         var self = ev.data.self;
5559
5560                         if (s.selectedIndex == (s.options.length - 1))
5561                         {
5562                                 ev.data.select.hide();
5563                                 ev.data.input.show().focus();
5564
5565                                 var v = ev.data.input.val();
5566                                 ev.data.input.val(' ');
5567                                 ev.data.input.val(v);
5568                         }
5569                         else if (self.options.optional && s.selectedIndex == 0)
5570                         {
5571                                 ev.data.input.val('');
5572                         }
5573                         else
5574                         {
5575                                 ev.data.input.val(ev.data.select.val());
5576                         }
5577                 },
5578
5579                 _blur: function(ev)
5580                 {
5581                         var seen = false;
5582                         var val = this.value;
5583                         var self = ev.data.self;
5584
5585                         ev.data.select.empty();
5586
5587                         if (self.options.optional)
5588                                 $('<option />')
5589                                         .attr('value', '')
5590                                         .text(_luci2.tr('-- please choose --'))
5591                                         .appendTo(ev.data.select);
5592
5593                         if (self.choices)
5594                                 for (var i = 0; i < self.choices.length; i++)
5595                                 {
5596                                         if (self.choices[i][0] == val)
5597                                                 seen = true;
5598
5599                                         $('<option />')
5600                                                 .attr('value', self.choices[i][0])
5601                                                 .text(self.choices[i][1])
5602                                                 .appendTo(ev.data.select);
5603                                 }
5604
5605                         if (!seen && val != '')
5606                                 $('<option />')
5607                                         .attr('value', val)
5608                                         .text(val)
5609                                         .appendTo(ev.data.select);
5610
5611                         $('<option />')
5612                                 .attr('value', ' ')
5613                                 .text(_luci2.tr('-- custom --'))
5614                                 .appendTo(ev.data.select);
5615
5616                         ev.data.input.hide();
5617                         ev.data.select.val(val).show().focus();
5618                 },
5619
5620                 _enter: function(ev)
5621                 {
5622                         if (ev.which != 13)
5623                                 return true;
5624
5625                         ev.preventDefault();
5626                         ev.data.self._blur(ev);
5627                         return false;
5628                 },
5629
5630                 widget: function(sid)
5631                 {
5632                         var d = $('<div />')
5633                                 .attr('id', this.id(sid));
5634
5635                         var t = $('<input />')
5636                                 .attr('type', 'text')
5637                                 .hide()
5638                                 .appendTo(d);
5639
5640                         var s = $('<select />')
5641                                 .appendTo(d);
5642
5643                         var evdata = {
5644                                 self: this,
5645                                 input: this.validator(sid, t),
5646                                 select: this.validator(sid, s)
5647                         };
5648
5649                         s.change(evdata, this._change);
5650                         t.blur(evdata, this._blur);
5651                         t.keydown(evdata, this._enter);
5652
5653                         t.val(this.ucivalue(sid));
5654                         t.blur();
5655
5656                         return d;
5657                 },
5658
5659                 value: function(k, v)
5660                 {
5661                         if (!this.choices)
5662                                 this.choices = [ ];
5663
5664                         this.choices.push([k, v || k]);
5665                         return this;
5666                 },
5667
5668                 formvalue: function(sid)
5669                 {
5670                         var v = $('#' + this.id(sid)).children('input').val();
5671                         return (v == '') ? undefined : v;
5672                 }
5673         });
5674
5675         this.cbi.DynamicList = this.cbi.ComboBox.extend({
5676                 _redraw: function(focus, add, del, s)
5677                 {
5678                         var v = s.values || [ ];
5679                         delete s.values;
5680
5681                         $(s.parent).children('div.input-group').children('input').each(function(i) {
5682                                 if (i != del)
5683                                         v.push(this.value || '');
5684                         });
5685
5686                         $(s.parent).empty();
5687
5688                         if (add >= 0)
5689                         {
5690                                 focus = add + 1;
5691                                 v.splice(focus, 0, '');
5692                         }
5693                         else if (v.length == 0)
5694                         {
5695                                 focus = 0;
5696                                 v.push('');
5697                         }
5698
5699                         for (var i = 0; i < v.length; i++)
5700                         {
5701                                 var evdata = {
5702                                         sid: s.sid,
5703                                         self: s.self,
5704                                         parent: s.parent,
5705                                         index: i,
5706                                         remove: ((i+1) < v.length)
5707                                 };
5708
5709                                 var btn;
5710                                 if (evdata.remove)
5711                                         btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
5712                                 else
5713                                         btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
5714
5715                                 if (this.choices)
5716                                 {
5717                                         var txt = $('<input />')
5718                                                 .addClass('form-control')
5719                                                 .attr('type', 'text')
5720                                                 .hide();
5721
5722                                         var sel = $('<select />')
5723                                                 .addClass('form-control');
5724
5725                                         $('<div />')
5726                                                 .addClass('input-group')
5727                                                 .append(txt)
5728                                                 .append(sel)
5729                                                 .append($('<span />')
5730                                                         .addClass('input-group-btn')
5731                                                         .append(btn))
5732                                                 .appendTo(s.parent);
5733
5734                                         evdata.input = this.validator(s.sid, txt, true);
5735                                         evdata.select = this.validator(s.sid, sel, true);
5736
5737                                         sel.change(evdata, this._change);
5738                                         txt.blur(evdata, this._blur);
5739                                         txt.keydown(evdata, this._keydown);
5740
5741                                         txt.val(v[i]);
5742                                         txt.blur();
5743
5744                                         if (i == focus || -(i+1) == focus)
5745                                                 sel.focus();
5746
5747                                         sel = txt = null;
5748                                 }
5749                                 else
5750                                 {
5751                                         var f = $('<input />')
5752                                                 .attr('type', 'text')
5753                                                 .attr('index', i)
5754                                                 .attr('placeholder', (i == 0) ? this.options.placeholder : '')
5755                                                 .addClass('form-control')
5756                                                 .keydown(evdata, this._keydown)
5757                                                 .keypress(evdata, this._keypress)
5758                                                 .val(v[i]);
5759
5760                                         $('<div />')
5761                                                 .addClass('input-group')
5762                                                 .append(f)
5763                                                 .append($('<span />')
5764                                                         .addClass('input-group-btn')
5765                                                         .append(btn))
5766                                                 .appendTo(s.parent);
5767
5768                                         if (i == focus)
5769                                         {
5770                                                 f.focus();
5771                                         }
5772                                         else if (-(i+1) == focus)
5773                                         {
5774                                                 f.focus();
5775
5776                                                 /* force cursor to end */
5777                                                 var val = f.val();
5778                                                 f.val(' ');
5779                                                 f.val(val);
5780                                         }
5781
5782                                         evdata.input = this.validator(s.sid, f, true);
5783
5784                                         f = null;
5785                                 }
5786
5787                                 evdata = null;
5788                         }
5789
5790                         s = null;
5791                 },
5792
5793                 _keypress: function(ev)
5794                 {
5795                         switch (ev.which)
5796                         {
5797                                 /* backspace, delete */
5798                                 case 8:
5799                                 case 46:
5800                                         if (ev.data.input.val() == '')
5801                                         {
5802                                                 ev.preventDefault();
5803                                                 return false;
5804                                         }
5805
5806                                         return true;
5807
5808                                 /* enter, arrow up, arrow down */
5809                                 case 13:
5810                                 case 38:
5811                                 case 40:
5812                                         ev.preventDefault();
5813                                         return false;
5814                         }
5815
5816                         return true;
5817                 },
5818
5819                 _keydown: function(ev)
5820                 {
5821                         var input = ev.data.input;
5822
5823                         switch (ev.which)
5824                         {
5825                                 /* backspace, delete */
5826                                 case 8:
5827                                 case 46:
5828                                         if (input.val().length == 0)
5829                                         {
5830                                                 ev.preventDefault();
5831
5832                                                 var index = ev.data.index;
5833                                                 var focus = index;
5834
5835                                                 if (ev.which == 8)
5836                                                         focus = -focus;
5837
5838                                                 ev.data.self._redraw(focus, -1, index, ev.data);
5839                                                 return false;
5840                                         }
5841
5842                                         break;
5843
5844                                 /* enter */
5845                                 case 13:
5846                                         ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
5847                                         break;
5848
5849                                 /* arrow up */
5850                                 case 38:
5851                                         var prev = input.parent().prevAll('div.input-group:first').children('input');
5852                                         if (prev.is(':visible'))
5853                                                 prev.focus();
5854                                         else
5855                                                 prev.next('select').focus();
5856                                         break;
5857
5858                                 /* arrow down */
5859                                 case 40:
5860                                         var next = input.parent().nextAll('div.input-group:first').children('input');
5861                                         if (next.is(':visible'))
5862                                                 next.focus();
5863                                         else
5864                                                 next.next('select').focus();
5865                                         break;
5866                         }
5867
5868                         return true;
5869                 },
5870
5871                 _btnclick: function(ev)
5872                 {
5873                         if (!this.getAttribute('disabled'))
5874                         {
5875                                 if (ev.data.remove)
5876                                 {
5877                                         var index = ev.data.index;
5878                                         ev.data.self._redraw(-index, -1, index, ev.data);
5879                                 }
5880                                 else
5881                                 {
5882                                         ev.data.self._redraw(NaN, ev.data.index, -1, ev.data);
5883                                 }
5884                         }
5885
5886                         return false;
5887                 },
5888
5889                 widget: function(sid)
5890                 {
5891                         this.options.optional = true;
5892
5893                         var v = this.ucivalue(sid);
5894
5895                         if (!$.isArray(v))
5896                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
5897
5898                         var d = $('<div />')
5899                                 .attr('id', this.id(sid))
5900                                 .addClass('cbi-input-dynlist');
5901
5902                         this._redraw(NaN, -1, -1, {
5903                                 self:      this,
5904                                 parent:    d[0],
5905                                 values:    v,
5906                                 sid:       sid
5907                         });
5908
5909                         return d;
5910                 },
5911
5912                 ucivalue: function(sid)
5913                 {
5914                         var v = this.callSuper('ucivalue', sid);
5915
5916                         if (!$.isArray(v))
5917                                 v = (typeof(v) != 'undefined') ? v.toString().split(/\s+/) : [ ];
5918
5919                         return v;
5920                 },
5921
5922                 formvalue: function(sid)
5923                 {
5924                         var rv = [ ];
5925                         var fields = $('#' + this.id(sid) + ' > input');
5926
5927                         for (var i = 0; i < fields.length; i++)
5928                                 if (typeof(fields[i].value) == 'string' && fields[i].value.length)
5929                                         rv.push(fields[i].value);
5930
5931                         return rv;
5932                 }
5933         });
5934
5935         this.cbi.DummyValue = this.cbi.AbstractValue.extend({
5936                 widget: function(sid)
5937                 {
5938                         return $('<div />')
5939                                 .addClass('form-control-static')
5940                                 .attr('id', this.id(sid))
5941                                 .html(this.ucivalue(sid));
5942                 },
5943
5944                 formvalue: function(sid)
5945                 {
5946                         return this.ucivalue(sid);
5947                 }
5948         });
5949
5950         this.cbi.ButtonValue = this.cbi.AbstractValue.extend({
5951                 widget: function(sid)
5952                 {
5953                         this.options.optional = true;
5954
5955                         var btn = $('<button />')
5956                                 .addClass('btn btn-default')
5957                                 .attr('id', this.id(sid))
5958                                 .attr('type', 'button')
5959                                 .text(this.label('text'));
5960
5961                         return this.validator(sid, btn);
5962                 }
5963         });
5964
5965         this.cbi.NetworkList = this.cbi.AbstractValue.extend({
5966                 load: function(sid)
5967                 {
5968                         return _luci2.NetworkModel.init();
5969                 },
5970
5971                 _device_icon: function(dev)
5972                 {
5973                         return $('<img />')
5974                                 .attr('src', dev.icon())
5975                                 .attr('title', '%s (%s)'.format(dev.description(), dev.name() || '?'));
5976                 },
5977
5978                 widget: function(sid)
5979                 {
5980                         var id = this.id(sid);
5981                         var ul = $('<ul />')
5982                                 .attr('id', id)
5983                                 .addClass('list-unstyled');
5984
5985                         var itype = this.options.multiple ? 'checkbox' : 'radio';
5986                         var value = this.ucivalue(sid);
5987                         var check = { };
5988
5989                         if (!this.options.multiple)
5990                                 check[value] = true;
5991                         else
5992                                 for (var i = 0; i < value.length; i++)
5993                                         check[value[i]] = true;
5994
5995                         var interfaces = _luci2.NetworkModel.getInterfaces();
5996
5997                         for (var i = 0; i < interfaces.length; i++)
5998                         {
5999                                 var iface = interfaces[i];
6000                                 var badge = $('<span />')
6001                                         .addClass('badge')
6002                                         .text('%s: '.format(iface.name()));
6003
6004                                 var dev = iface.getDevice();
6005                                 var subdevs = iface.getSubdevices();
6006
6007                                 if (subdevs.length)
6008                                         for (var j = 0; j < subdevs.length; j++)
6009                                                 badge.append(this._device_icon(subdevs[j]));
6010                                 else if (dev)
6011                                         badge.append(this._device_icon(dev));
6012                                 else
6013                                         badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
6014
6015                                 $('<li />')
6016                                         .append($('<label />')
6017                                                 .addClass(itype + ' inline')
6018                                                 .append($('<input />')
6019                                                         .attr('name', itype + id)
6020                                                         .attr('type', itype)
6021                                                         .attr('value', iface.name())
6022                                                         .prop('checked', !!check[iface.name()]))
6023                                                 .append(badge))
6024                                         .appendTo(ul);
6025                         }
6026
6027                         if (!this.options.multiple)
6028                         {
6029                                 $('<li />')
6030                                         .append($('<label />')
6031                                                 .addClass(itype + ' inline text-muted')
6032                                                 .append($('<input />')
6033                                                         .attr('name', itype + id)
6034                                                         .attr('type', itype)
6035                                                         .attr('value', '')
6036                                                         .prop('checked', $.isEmptyObject(check)))
6037                                                 .append(_luci2.tr('unspecified')))
6038                                         .appendTo(ul);
6039                         }
6040
6041                         return ul;
6042                 },
6043
6044                 ucivalue: function(sid)
6045                 {
6046                         var v = this.callSuper('ucivalue', sid);
6047
6048                         if (!this.options.multiple)
6049                         {
6050                                 if ($.isArray(v))
6051                                 {
6052                                         return v[0];
6053                                 }
6054                                 else if (typeof(v) == 'string')
6055                                 {
6056                                         v = v.match(/\S+/);
6057                                         return v ? v[0] : undefined;
6058                                 }
6059
6060                                 return v;
6061                         }
6062                         else
6063                         {
6064                                 if (typeof(v) == 'string')
6065                                         v = v.match(/\S+/g);
6066
6067                                 return v || [ ];
6068                         }
6069                 },
6070
6071                 formvalue: function(sid)
6072                 {
6073                         var inputs = $('#' + this.id(sid) + ' input');
6074
6075                         if (!this.options.multiple)
6076                         {
6077                                 for (var i = 0; i < inputs.length; i++)
6078                                         if (inputs[i].checked && inputs[i].value !== '')
6079                                                 return inputs[i].value;
6080
6081                                 return undefined;
6082                         }
6083
6084                         var rv = [ ];
6085
6086                         for (var i = 0; i < inputs.length; i++)
6087                                 if (inputs[i].checked)
6088                                         rv.push(inputs[i].value);
6089
6090                         return rv.length ? rv : undefined;
6091                 }
6092         });
6093
6094
6095         this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
6096                 id: function()
6097                 {
6098                         var s = [ arguments[0], this.map.uci_package, this.uci_type ];
6099
6100                         for (var i = 1; i < arguments.length; i++)
6101                                 s.push(arguments[i].replace(/\./g, '_'));
6102
6103                         return s.join('_');
6104                 },
6105
6106                 option: function(widget, name, options)
6107                 {
6108                         if (this.tabs.length == 0)
6109                                 this.tab({ id: '__default__', selected: true });
6110
6111                         return this.taboption('__default__', widget, name, options);
6112                 },
6113
6114                 tab: function(options)
6115                 {
6116                         if (options.selected)
6117                                 this.tabs.selected = this.tabs.length;
6118
6119                         this.tabs.push({
6120                                 id:          options.id,
6121                                 caption:     options.caption,
6122                                 description: options.description,
6123                                 fields:      [ ],
6124                                 li:          { }
6125                         });
6126                 },
6127
6128                 taboption: function(tabid, widget, name, options)
6129                 {
6130                         var tab;
6131                         for (var i = 0; i < this.tabs.length; i++)
6132                         {
6133                                 if (this.tabs[i].id == tabid)
6134                                 {
6135                                         tab = this.tabs[i];
6136                                         break;
6137                                 }
6138                         }
6139
6140                         if (!tab)
6141                                 throw 'Cannot append to unknown tab ' + tabid;
6142
6143                         var w = widget ? new widget(name, options) : null;
6144
6145                         if (!(w instanceof _luci2.cbi.AbstractValue))
6146                                 throw 'Widget must be an instance of AbstractValue';
6147
6148                         w.section = this;
6149                         w.map     = this.map;
6150
6151                         this.fields[name] = w;
6152                         tab.fields.push(w);
6153
6154                         return w;
6155                 },
6156
6157                 ucipackages: function(pkg)
6158                 {
6159                         for (var i = 0; i < this.tabs.length; i++)
6160                                 for (var j = 0; j < this.tabs[i].fields.length; j++)
6161                                         if (this.tabs[i].fields[j].options.uci_package)
6162                                                 pkg[this.tabs[i].fields[j].options.uci_package] = true;
6163                 },
6164
6165                 formvalue: function()
6166                 {
6167                         var rv = { };
6168
6169                         this.sections(function(s) {
6170                                 var sid = s['.name'];
6171                                 var sv = rv[sid] || (rv[sid] = { });
6172
6173                                 for (var i = 0; i < this.tabs.length; i++)
6174                                         for (var j = 0; j < this.tabs[i].fields.length; j++)
6175                                         {
6176                                                 var val = this.tabs[i].fields[j].formvalue(sid);
6177                                                 sv[this.tabs[i].fields[j].name] = val;
6178                                         }
6179                         });
6180
6181                         return rv;
6182                 },
6183
6184                 validate_section: function(sid)
6185                 {
6186                         var inst = this.instance[sid];
6187
6188                         var invals = 0;
6189                         var badge = $('#' + this.id('teaser', sid)).children('span:first');
6190
6191                         for (var i = 0; i < this.tabs.length; i++)
6192                         {
6193                                 var inval = 0;
6194                                 var stbadge = $('#' + this.id('nodetab', sid, this.tabs[i].id)).children('span:first');
6195
6196                                 for (var j = 0; j < this.tabs[i].fields.length; j++)
6197                                         if (!this.tabs[i].fields[j].validate(sid))
6198                                                 inval++;
6199
6200                                 if (inval > 0)
6201                                         stbadge.show()
6202                                                 .text(inval)
6203                                                 .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
6204                                 else
6205                                         stbadge.hide();
6206
6207                                 invals += inval;
6208                         }
6209
6210                         if (invals > 0)
6211                                 badge.show()
6212                                         .text(invals)
6213                                         .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
6214                         else
6215                                 badge.hide();
6216
6217                         return invals;
6218                 },
6219
6220                 validate: function()
6221                 {
6222                         this.error_count = 0;
6223
6224                         var as = this.sections();
6225
6226                         for (var i = 0; i < as.length; i++)
6227                         {
6228                                 var invals = this.validate_section(as[i]['.name']);
6229
6230                                 if (invals > 0)
6231                                         this.error_count += invals;
6232                         }
6233
6234                         var badge = $('#' + this.id('sectiontab')).children('span:first');
6235
6236                         if (this.error_count > 0)
6237                                 badge.show()
6238                                         .text(this.error_count)
6239                                         .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
6240                         else
6241                                 badge.hide();
6242
6243                         return (this.error_count == 0);
6244                 }
6245         });
6246
6247         this.cbi.TypedSection = this.cbi.AbstractSection.extend({
6248                 init: function(uci_type, options)
6249                 {
6250                         this.uci_type = uci_type;
6251                         this.options  = options;
6252                         this.tabs     = [ ];
6253                         this.fields   = { };
6254                         this.error_count  = 0;
6255                         this.active_panel = 0;
6256                         this.active_tab   = { };
6257                 },
6258
6259                 filter: function(section)
6260                 {
6261                         return true;
6262                 },
6263
6264                 sections: function(cb)
6265                 {
6266                         var s1 = _luci2.uci.sections(this.map.uci_package);
6267                         var s2 = [ ];
6268
6269                         for (var i = 0; i < s1.length; i++)
6270                                 if (s1[i]['.type'] == this.uci_type)
6271                                         if (this.filter(s1[i]))
6272                                                 s2.push(s1[i]);
6273
6274                         if (typeof(cb) == 'function')
6275                                 for (var i = 0; i < s2.length; i++)
6276                                         cb.apply(this, [ s2[i] ]);
6277
6278                         return s2;
6279                 },
6280
6281                 add: function(name)
6282                 {
6283                         this.map.add(this.map.uci_package, this.uci_type, name);
6284                 },
6285
6286                 remove: function(sid)
6287                 {
6288                         this.map.remove(this.map.uci_package, sid);
6289                 },
6290
6291                 _ev_add: function(ev)
6292                 {
6293                         var addb = $(this);
6294                         var name = undefined;
6295                         var self = ev.data.self;
6296
6297                         if (addb.prev().prop('nodeName') == 'INPUT')
6298                                 name = addb.prev().val();
6299
6300                         if (addb.prop('disabled') || name === '')
6301                                 return;
6302
6303                         _luci2.ui.saveScrollTop();
6304
6305                         self.active_panel = -1;
6306                         self.map.save();
6307                         self.add(name);
6308                         self.map.redraw();
6309
6310                         _luci2.ui.restoreScrollTop();
6311                 },
6312
6313                 _ev_remove: function(ev)
6314                 {
6315                         var self = ev.data.self;
6316                         var sid  = ev.data.sid;
6317
6318                         _luci2.ui.saveScrollTop();
6319
6320                         self.map.save();
6321                         self.remove(sid);
6322                         self.map.redraw();
6323
6324                         _luci2.ui.restoreScrollTop();
6325
6326                         ev.stopPropagation();
6327                 },
6328
6329                 _ev_sid: function(ev)
6330                 {
6331                         var self = ev.data.self;
6332                         var text = $(this);
6333                         var addb = text.next();
6334                         var errt = addb.next();
6335                         var name = text.val();
6336
6337                         if (!/^[a-zA-Z0-9_]*$/.test(name))
6338                         {
6339                                 errt.text(_luci2.tr('Invalid section name')).show();
6340                                 text.addClass('error');
6341                                 addb.prop('disabled', true);
6342                                 return false;
6343                         }
6344
6345                         if (_luci2.uci.get(self.map.uci_package, name))
6346                         {
6347                                 errt.text(_luci2.tr('Name already used')).show();
6348                                 text.addClass('error');
6349                                 addb.prop('disabled', true);
6350                                 return false;
6351                         }
6352
6353                         errt.text('').hide();
6354                         text.removeClass('error');
6355                         addb.prop('disabled', false);
6356                         return true;
6357                 },
6358
6359                 _ev_tab: function(ev)
6360                 {
6361                         var self = ev.data.self;
6362                         var sid  = ev.data.sid;
6363
6364                         self.validate();
6365                         self.active_tab[sid] = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
6366                 },
6367
6368                 _ev_panel_collapse: function(ev)
6369                 {
6370                         var self = ev.data.self;
6371
6372                         var this_panel = $(ev.target);
6373                         var this_toggle = this_panel.prevAll('[data-toggle="collapse"]:first');
6374
6375                         var prev_toggle = $($(ev.delegateTarget).find('[data-toggle="collapse"]:eq(%d)'.format(self.active_panel)));
6376                         var prev_panel = $(prev_toggle.attr('data-target'));
6377
6378                         prev_panel
6379                                 .removeClass('in')
6380                                 .addClass('collapse');
6381
6382                         prev_toggle.find('.luci2-section-teaser')
6383                                 .show()
6384                                 .children('span:last')
6385                                 .empty()
6386                                 .append(self.teaser(prev_panel.attr('data-luci2-sid')));
6387
6388                         this_toggle.find('.luci2-section-teaser')
6389                                 .hide();
6390
6391                         self.active_panel = parseInt(this_panel.attr('data-luci2-panel-index'));
6392                         self.validate();
6393                 },
6394
6395                 _ev_panel_open: function(ev)
6396                 {
6397                         var self  = ev.data.self;
6398                         var panel = $($(this).attr('data-target'));
6399                         var index = parseInt(panel.attr('data-luci2-panel-index'));
6400
6401                         if (index == self.active_panel)
6402                                 ev.stopPropagation();
6403                 },
6404
6405                 _ev_sort: function(ev)
6406                 {
6407                         var self    = ev.data.self;
6408                         var cur_idx = ev.data.index;
6409                         var new_idx = cur_idx + (ev.data.up ? -1 : 1);
6410                         var s       = self.sections();
6411
6412                         if (new_idx >= 0 && new_idx < s.length)
6413                         {
6414                                 _luci2.uci.swap(self.map.uci_package, s[cur_idx]['.name'], s[new_idx]['.name']);
6415
6416                                 self.map.save();
6417                                 self.map.redraw();
6418                         }
6419
6420                         ev.stopPropagation();
6421                 },
6422
6423                 teaser: function(sid)
6424                 {
6425                         var tf = this.teaser_fields;
6426
6427                         if (!tf)
6428                         {
6429                                 tf = this.teaser_fields = [ ];
6430
6431                                 if ($.isArray(this.options.teasers))
6432                                 {
6433                                         for (var i = 0; i < this.options.teasers.length; i++)
6434                                         {
6435                                                 var f = this.options.teasers[i];
6436                                                 if (f instanceof _luci2.cbi.AbstractValue)
6437                                                         tf.push(f);
6438                                                 else if (typeof(f) == 'string' && this.fields[f] instanceof _luci2.cbi.AbstractValue)
6439                                                         tf.push(this.fields[f]);
6440                                         }
6441                                 }
6442                                 else
6443                                 {
6444                                         for (var i = 0; tf.length <= 5 && i < this.tabs.length; i++)
6445                                                 for (var j = 0; tf.length <= 5 && j < this.tabs[i].fields.length; j++)
6446                                                         tf.push(this.tabs[i].fields[j]);
6447                                 }
6448                         }
6449
6450                         var t = '';
6451
6452                         for (var i = 0; i < tf.length; i++)
6453                         {
6454                                 if (tf[i].instance[sid] && tf[i].instance[sid].disabled)
6455                                         continue;
6456
6457                                 var n = tf[i].options.caption || tf[i].name;
6458                                 var v = tf[i].textvalue(sid);
6459
6460                                 if (typeof(v) == 'undefined')
6461                                         continue;
6462
6463                                 t = t + '%s%s: <strong>%s</strong>'.format(t ? ' | ' : '', n, v);
6464                         }
6465
6466                         return t;
6467                 },
6468
6469                 _render_add: function()
6470                 {
6471                         if (!this.options.addremove)
6472                                 return null;
6473
6474                         var text = _luci2.tr('Add section');
6475                         var ttip = _luci2.tr('Create new section...');
6476
6477                         if ($.isArray(this.options.add_caption))
6478                                 text = this.options.add_caption[0], ttip = this.options.add_caption[1];
6479                         else if (typeof(this.options.add_caption) == 'string')
6480                                 text = this.options.add_caption, ttip = '';
6481
6482                         var add = $('<div />');
6483
6484                         if (this.options.anonymous === false)
6485                         {
6486                                 $('<input />')
6487                                         .addClass('cbi-input-text')
6488                                         .attr('type', 'text')
6489                                         .attr('placeholder', ttip)
6490                                         .blur({ self: this }, this._ev_sid)
6491                                         .keyup({ self: this }, this._ev_sid)
6492                                         .appendTo(add);
6493
6494                                 $('<img />')
6495                                         .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
6496                                         .attr('title', text)
6497                                         .addClass('cbi-button')
6498                                         .click({ self: this }, this._ev_add)
6499                                         .appendTo(add);
6500
6501                                 $('<div />')
6502                                         .addClass('cbi-value-error')
6503                                         .hide()
6504                                         .appendTo(add);
6505                         }
6506                         else
6507                         {
6508                                 _luci2.ui.button(text, 'success', ttip)
6509                                         .click({ self: this }, this._ev_add)
6510                                         .appendTo(add);
6511                         }
6512
6513                         return add;
6514                 },
6515
6516                 _render_remove: function(sid, index)
6517                 {
6518                         if (!this.options.addremove)
6519                                 return null;
6520
6521                         var text = _luci2.tr('Remove');
6522                         var ttip = _luci2.tr('Remove this section');
6523
6524                         if ($.isArray(this.options.remove_caption))
6525                                 text = this.options.remove_caption[0], ttip = this.options.remove_caption[1];
6526                         else if (typeof(this.options.remove_caption) == 'string')
6527                                 text = this.options.remove_caption, ttip = '';
6528
6529                         return _luci2.ui.button(text, 'danger', ttip)
6530                                 .click({ self: this, sid: sid, index: index }, this._ev_remove);
6531                 },
6532
6533                 _render_sort: function(sid, index)
6534                 {
6535                         if (!this.options.sortable)
6536                                 return null;
6537
6538                         var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
6539                                 .click({ self: this, index: index, up: true }, this._ev_sort);
6540
6541                         var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
6542                                 .click({ self: this, index: index, up: false }, this._ev_sort);
6543
6544                         return b1.add(b2);
6545                 },
6546
6547                 _render_caption: function()
6548                 {
6549                         return $('<h3 />')
6550                                 .addClass('panel-title')
6551                                 .append(this.label('caption') || this.uci_type);
6552                 },
6553
6554                 _render_description: function()
6555                 {
6556                         var text = this.label('description');
6557
6558                         if (text)
6559                                 return $('<div />')
6560                                         .addClass('luci2-section-description')
6561                                         .text(text);
6562
6563                         return null;
6564                 },
6565
6566                 _render_teaser: function(sid, index)
6567                 {
6568                         if (this.options.collabsible || this.map.options.collabsible)
6569                         {
6570                                 return $('<div />')
6571                                         .attr('id', this.id('teaser', sid))
6572                                         .addClass('luci2-section-teaser well well-sm')
6573                                         .append($('<span />')
6574                                                 .addClass('badge'))
6575                                         .append($('<span />'));
6576                         }
6577
6578                         return null;
6579                 },
6580
6581                 _render_head: function(condensed)
6582                 {
6583                         if (condensed)
6584                                 return null;
6585
6586                         return $('<div />')
6587                                 .addClass('panel-heading')
6588                                 .append(this._render_caption())
6589                                 .append(this._render_description());
6590                 },
6591
6592                 _render_tab_description: function(sid, index, tab_index)
6593                 {
6594                         var tab = this.tabs[tab_index];
6595
6596                         if (typeof(tab.description) == 'string')
6597                         {
6598                                 return $('<div />')
6599                                         .addClass('cbi-tab-descr')
6600                                         .text(tab.description);
6601                         }
6602
6603                         return null;
6604                 },
6605
6606                 _render_tab_head: function(sid, index, tab_index)
6607                 {
6608                         var tab = this.tabs[tab_index];
6609                         var cur = this.active_tab[sid] || 0;
6610
6611                         var tabh = $('<li />')
6612                                 .append($('<a />')
6613                                         .attr('id', this.id('nodetab', sid, tab.id))
6614                                         .attr('href', '#' + this.id('node', sid, tab.id))
6615                                         .attr('data-toggle', 'tab')
6616                                         .attr('data-luci2-tab-index', tab_index)
6617                                         .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
6618                                         .append($('<span />')
6619                                                 .addClass('badge'))
6620                                         .on('shown.bs.tab', { self: this, sid: sid }, this._ev_tab));
6621
6622                         if (cur == tab_index)
6623                                 tabh.addClass('active');
6624
6625                         return tabh;
6626                 },
6627
6628                 _render_tab_body: function(sid, index, tab_index)
6629                 {
6630                         var tab = this.tabs[tab_index];
6631                         var cur = this.active_tab[sid] || 0;
6632
6633                         var tabb = $('<div />')
6634                                 .addClass('tab-pane')
6635                                 .attr('id', this.id('node', sid, tab.id))
6636                                 .attr('data-luci2-tab-index', tab_index)
6637                                 .append(this._render_tab_description(sid, index, tab_index));
6638
6639                         if (cur == tab_index)
6640                                 tabb.addClass('active');
6641
6642                         for (var i = 0; i < tab.fields.length; i++)
6643                                 tabb.append(tab.fields[i].render(sid));
6644
6645                         return tabb;
6646                 },
6647
6648                 _render_section_head: function(sid, index)
6649                 {
6650                         var head = $('<div />')
6651                                 .addClass('luci2-section-header')
6652                                 .append(this._render_teaser(sid, index))
6653                                 .append($('<div />')
6654                                         .addClass('btn-group')
6655                                         .append(this._render_sort(sid, index))
6656                                         .append(this._render_remove(sid, index)));
6657
6658                         if (this.options.collabsible)
6659                         {
6660                                 head.attr('data-toggle', 'collapse')
6661                                         .attr('data-parent', this.id('sectiongroup'))
6662                                         .attr('data-target', '#' + this.id('panel', sid))
6663                                         .on('click', { self: this }, this._ev_panel_open);
6664                         }
6665
6666                         return head;
6667                 },
6668
6669                 _render_section_body: function(sid, index)
6670                 {
6671                         var body = $('<div />')
6672                                 .attr('id', this.id('panel', sid))
6673                                 .attr('data-luci2-panel-index', index)
6674                                 .attr('data-luci2-sid', sid);
6675
6676                         if (this.options.collabsible || this.map.options.collabsible)
6677                         {
6678                                 body.addClass('panel-collapse collapse');
6679
6680                                 if (index == this.active_panel)
6681                                         body.addClass('in');
6682                         }
6683
6684                         var tab_heads = $('<ul />')
6685                                 .addClass('nav nav-tabs');
6686
6687                         var tab_bodies = $('<div />')
6688                                 .addClass('form-horizontal tab-content')
6689                                 .append(tab_heads);
6690
6691                         for (var j = 0; j < this.tabs.length; j++)
6692                         {
6693                                 tab_heads.append(this._render_tab_head(sid, index, j));
6694                                 tab_bodies.append(this._render_tab_body(sid, index, j));
6695                         }
6696
6697                         body.append(tab_bodies);
6698
6699                         if (this.tabs.length <= 1)
6700                                 tab_heads.hide();
6701
6702                         return body;
6703                 },
6704
6705                 _render_body: function(condensed)
6706                 {
6707                         var s = this.sections();
6708
6709                         if (this.active_panel < 0)
6710                                 this.active_panel += s.length;
6711                         else if (this.active_panel >= s.length)
6712                                 this.active_panel = s.length - 1;
6713
6714                         var body = $('<ul />')
6715                                 .addClass('list-group');
6716
6717                         if (this.options.collabsible)
6718                         {
6719                                 body.attr('id', this.id('sectiongroup'))
6720                                         .on('show.bs.collapse', { self: this }, this._ev_panel_collapse);
6721                         }
6722
6723                         if (s.length == 0)
6724                         {
6725                                 body.append($('<li />')
6726                                         .addClass('list-group-item text-muted')
6727                                         .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
6728                         }
6729
6730                         for (var i = 0; i < s.length; i++)
6731                         {
6732                                 var sid = s[i]['.name'];
6733                                 var inst = this.instance[sid] = { tabs: [ ] };
6734
6735                                 body.append($('<li />')
6736                                         .addClass('list-group-item')
6737                                         .append(this._render_section_head(sid, i))
6738                                         .append(this._render_section_body(sid, i)));
6739                         }
6740
6741                         return body;
6742                 },
6743
6744                 render: function(condensed)
6745                 {
6746                         this.instance = { };
6747
6748                         var panel = $('<div />')
6749                                 .addClass('panel panel-default')
6750                                 .append(this._render_head(condensed))
6751                                 .append(this._render_body(condensed));
6752
6753                         if (this.options.addremove)
6754                                 panel.append($('<div />')
6755                                         .addClass('panel-footer')
6756                                         .append(this._render_add()));
6757
6758                         return panel;
6759                 },
6760
6761                 finish: function()
6762                 {
6763                         var s = this.sections();
6764
6765                         for (var i = 0; i < s.length; i++)
6766                         {
6767                                 var sid = s[i]['.name'];
6768
6769                                 this.validate_section(sid);
6770
6771                                 if (i != this.active_panel)
6772                                         $('#' + this.id('teaser', sid)).children('span:last')
6773                                                 .append(this.teaser(sid));
6774                                 else
6775                                         $('#' + this.id('teaser', sid))
6776                                                 .hide();
6777                         }
6778                 }
6779         });
6780
6781         this.cbi.TableSection = this.cbi.TypedSection.extend({
6782                 _render_table_head: function()
6783                 {
6784                         var thead = $('<thead />')
6785                                 .append($('<tr />')
6786                                         .addClass('cbi-section-table-titles'));
6787
6788                         for (var j = 0; j < this.tabs[0].fields.length; j++)
6789                                 thead.children().append($('<th />')
6790                                         .addClass('cbi-section-table-cell')
6791                                         .css('width', this.tabs[0].fields[j].options.width || '')
6792                                         .append(this.tabs[0].fields[j].label('caption')));
6793
6794                         if (this.options.addremove !== false || this.options.sortable)
6795                                 thead.children().append($('<th />')
6796                                         .addClass('cbi-section-table-cell')
6797                                         .text(' '));
6798
6799                         return thead;
6800                 },
6801
6802                 _render_table_row: function(sid, index)
6803                 {
6804                         var row = $('<tr />')
6805                                 .attr('data-luci2-sid', sid);
6806
6807                         for (var j = 0; j < this.tabs[0].fields.length; j++)
6808                         {
6809                                 row.append($('<td />')
6810                                         .css('width', this.tabs[0].fields[j].options.width || '')
6811                                         .append(this.tabs[0].fields[j].render(sid, true)));
6812                         }
6813
6814                         if (this.options.addremove !== false || this.options.sortable)
6815                         {
6816                                 row.append($('<td />')
6817                                         .addClass('text-right')
6818                                         .append($('<div />')
6819                                                 .addClass('btn-group')
6820                                                 .append(this._render_sort(sid, index))
6821                                                 .append(this._render_remove(sid, index))));
6822                         }
6823
6824                         return row;
6825                 },
6826
6827                 _render_table_body: function()
6828                 {
6829                         var s = this.sections();
6830
6831                         var tbody = $('<tbody />');
6832
6833                         if (s.length == 0)
6834                         {
6835                                 var cols = this.tabs[0].fields.length;
6836
6837                                 if (this.options.addremove !== false || this.options.sortable)
6838                                         cols++;
6839
6840                                 tbody.append($('<tr />')
6841                                         .append($('<td />')
6842                                                 .addClass('text-muted')
6843                                                 .attr('colspan', cols)
6844                                                 .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
6845                         }
6846
6847                         for (var i = 0; i < s.length; i++)
6848                         {
6849                                 var sid = s[i]['.name'];
6850                                 var inst = this.instance[sid] = { tabs: [ ] };
6851
6852                                 tbody.append(this._render_table_row(sid, i));
6853                         }
6854
6855                         return tbody;
6856                 },
6857
6858                 _render_body: function(condensed)
6859                 {
6860                         return $('<table />')
6861                                 .addClass('table table-condensed table-hover')
6862                                 .append(this._render_table_head())
6863                                 .append(this._render_table_body());
6864                 }
6865         });
6866
6867         this.cbi.NamedSection = this.cbi.TypedSection.extend({
6868                 sections: function(cb)
6869                 {
6870                         var sa = [ ];
6871                         var sl = _luci2.uci.sections(this.map.uci_package);
6872
6873                         for (var i = 0; i < sl.length; i++)
6874                                 if (sl[i]['.name'] == this.uci_type)
6875                                 {
6876                                         sa.push(sl[i]);
6877                                         break;
6878                                 }
6879
6880                         if (typeof(cb) == 'function' && sa.length > 0)
6881                                 cb.call(this, sa[0]);
6882
6883                         return sa;
6884                 }
6885         });
6886
6887         this.cbi.SingleSection = this.cbi.NamedSection.extend({
6888                 render: function()
6889                 {
6890                         this.instance = { };
6891                         this.instance[this.uci_type] = { tabs: [ ] };
6892
6893                         return this._render_section_body(this.uci_type, 0);
6894                 }
6895         });
6896
6897         this.cbi.DummySection = this.cbi.TypedSection.extend({
6898                 sections: function(cb)
6899                 {
6900                         if (typeof(cb) == 'function')
6901                                 cb.apply(this, [ { '.name': this.uci_type } ]);
6902
6903                         return [ { '.name': this.uci_type } ];
6904                 }
6905         });
6906
6907         this.cbi.Map = this.ui.AbstractWidget.extend({
6908                 init: function(uci_package, options)
6909                 {
6910                         var self = this;
6911
6912                         this.uci_package = uci_package;
6913                         this.sections = [ ];
6914                         this.options = _luci2.defaults(options, {
6915                                 save:    function() { },
6916                                 prepare: function() { }
6917                         });
6918                 },
6919
6920                 _load_cb: function()
6921                 {
6922                         var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
6923
6924                         for (var i = 0; i < this.sections.length; i++)
6925                         {
6926                                 for (var f in this.sections[i].fields)
6927                                 {
6928                                         if (typeof(this.sections[i].fields[f].load) != 'function')
6929                                                 continue;
6930
6931                                         var s = this.sections[i].sections();
6932                                         for (var j = 0; j < s.length; j++)
6933                                         {
6934                                                 var rv = this.sections[i].fields[f].load(s[j]['.name']);
6935                                                 if (_luci2.isDeferred(rv))
6936                                                         deferreds.push(rv);
6937                                         }
6938                                 }
6939                         }
6940
6941                         return $.when.apply($, deferreds);
6942                 },
6943
6944                 load: function()
6945                 {
6946                         var self = this;
6947                         var packages = { };
6948
6949                         for (var i = 0; i < this.sections.length; i++)
6950                                 this.sections[i].ucipackages(packages);
6951
6952                         packages[this.uci_package] = true;
6953
6954                         for (var pkg in packages)
6955                                 if (!_luci2.uci.writable(pkg))
6956                                         this.options.readonly = true;
6957
6958                         return _luci2.uci.load(_luci2.toArray(packages)).then(function() {
6959                                 return self._load_cb();
6960                         });
6961                 },
6962
6963                 _ev_tab: function(ev)
6964                 {
6965                         var self = ev.data.self;
6966
6967                         self.validate();
6968                         self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
6969                 },
6970
6971                 _render_tab_head: function(tab_index)
6972                 {
6973                         var section = this.sections[tab_index];
6974                         var cur = this.active_tab || 0;
6975
6976                         var tabh = $('<li />')
6977                                 .append($('<a />')
6978                                         .attr('id', section.id('sectiontab'))
6979                                         .attr('href', '#' + section.id('section'))
6980                                         .attr('data-toggle', 'tab')
6981                                         .attr('data-luci2-tab-index', tab_index)
6982                                         .text(section.label('caption') + ' ')
6983                                         .append($('<span />')
6984                                                 .addClass('badge'))
6985                                         .on('shown.bs.tab', { self: this }, this._ev_tab));
6986
6987                         if (cur == tab_index)
6988                                 tabh.addClass('active');
6989
6990                         return tabh;
6991                 },
6992
6993                 _render_tab_body: function(tab_index)
6994                 {
6995                         var section = this.sections[tab_index];
6996                         var desc = section.label('description');
6997                         var cur = this.active_tab || 0;
6998
6999                         var tabb = $('<div />')
7000                                 .addClass('tab-pane')
7001                                 .attr('id', section.id('section'))
7002                                 .attr('data-luci2-tab-index', tab_index);
7003
7004                         if (cur == tab_index)
7005                                 tabb.addClass('active');
7006
7007                         if (desc)
7008                                 tabb.append($('<p />')
7009                                         .text(desc));
7010
7011                         var s = section.render(this.options.tabbed);
7012
7013                         if (this.options.readonly || section.options.readonly)
7014                                 s.find('input, select, button, img.cbi-button').attr('disabled', true);
7015
7016                         tabb.append(s);
7017
7018                         return tabb;
7019                 },
7020
7021                 _render_body: function()
7022                 {
7023                         var tabs = $('<ul />')
7024                                 .addClass('nav nav-tabs');
7025
7026                         var body = $('<div />')
7027                                 .append(tabs);
7028
7029                         for (var i = 0; i < this.sections.length; i++)
7030                         {
7031                                 tabs.append(this._render_tab_head(i));
7032                                 body.append(this._render_tab_body(i));
7033                         }
7034
7035                         if (this.options.tabbed)
7036                                 body.addClass('tab-content');
7037                         else
7038                                 tabs.hide();
7039
7040                         return body;
7041                 },
7042
7043                 render: function()
7044                 {
7045                         var map = $('<form />');
7046
7047                         if (typeof(this.options.caption) == 'string')
7048                                 map.append($('<h2 />')
7049                                         .text(this.options.caption));
7050
7051                         if (typeof(this.options.description) == 'string')
7052                                 map.append($('<p />')
7053                                         .text(this.options.description));
7054
7055                         map.append(this._render_body());
7056
7057                         if (this.options.pageaction !== false)
7058                         {
7059                                 map.append($('<div />')
7060                                         .addClass('panel panel-default panel-body text-right')
7061                                         .append($('<div />')
7062                                                 .addClass('btn-group')
7063                                                 .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
7064                                                         .click({ self: this }, function(ev) {  }))
7065                                                 .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
7066                                                         .click({ self: this }, function(ev) { ev.data.self.send(); }))
7067                                                 .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
7068                                                         .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
7069                         }
7070
7071                         return map;
7072                 },
7073
7074                 finish: function()
7075                 {
7076                         for (var i = 0; i < this.sections.length; i++)
7077                                 this.sections[i].finish();
7078
7079                         this.validate();
7080                 },
7081
7082                 redraw: function()
7083                 {
7084                         this.target.hide().empty().append(this.render());
7085                         this.finish();
7086                         this.target.show();
7087                 },
7088
7089                 section: function(widget, uci_type, options)
7090                 {
7091                         var w = widget ? new widget(uci_type, options) : null;
7092
7093                         if (!(w instanceof _luci2.cbi.AbstractSection))
7094                                 throw 'Widget must be an instance of AbstractSection';
7095
7096                         w.map = this;
7097                         w.index = this.sections.length;
7098
7099                         this.sections.push(w);
7100                         return w;
7101                 },
7102
7103                 formvalue: function()
7104                 {
7105                         var rv = { };
7106
7107                         for (var i = 0; i < this.sections.length; i++)
7108                         {
7109                                 var sids = this.sections[i].formvalue();
7110                                 for (var sid in sids)
7111                                 {
7112                                         var s = rv[sid] || (rv[sid] = { });
7113                                         $.extend(s, sids[sid]);
7114                                 }
7115                         }
7116
7117                         return rv;
7118                 },
7119
7120                 add: function(conf, type, name)
7121                 {
7122                         return _luci2.uci.add(conf, type, name);
7123                 },
7124
7125                 remove: function(conf, sid)
7126                 {
7127                         return _luci2.uci.remove(conf, sid);
7128                 },
7129
7130                 get: function(conf, sid, opt)
7131                 {
7132                         return _luci2.uci.get(conf, sid, opt);
7133                 },
7134
7135                 set: function(conf, sid, opt, val)
7136                 {
7137                         return _luci2.uci.set(conf, sid, opt, val);
7138                 },
7139
7140                 validate: function()
7141                 {
7142                         var rv = true;
7143
7144                         for (var i = 0; i < this.sections.length; i++)
7145                         {
7146                                 if (!this.sections[i].validate())
7147                                         rv = false;
7148                         }
7149
7150                         return rv;
7151                 },
7152
7153                 save: function()
7154                 {
7155                         var self = this;
7156
7157                         if (self.options.readonly)
7158                                 return _luci2.deferrable();
7159
7160                         var deferreds = [ ];
7161
7162                         for (var i = 0; i < self.sections.length; i++)
7163                         {
7164                                 if (self.sections[i].options.readonly)
7165                                         continue;
7166
7167                                 for (var f in self.sections[i].fields)
7168                                 {
7169                                         if (typeof(self.sections[i].fields[f].save) != 'function')
7170                                                 continue;
7171
7172                                         var s = self.sections[i].sections();
7173                                         for (var j = 0; j < s.length; j++)
7174                                         {
7175                                                 var rv = self.sections[i].fields[f].save(s[j]['.name']);
7176                                                 if (_luci2.isDeferred(rv))
7177                                                         deferreds.push(rv);
7178                                         }
7179                                 }
7180                         }
7181
7182                         return $.when.apply($, deferreds).then(function() {
7183                                 return _luci2.deferrable(self.options.save());
7184                         });
7185                 },
7186
7187                 send: function()
7188                 {
7189                         if (!this.validate())
7190                                 return _luci2.deferrable();
7191
7192                         var self = this;
7193
7194                         _luci2.ui.saveScrollTop();
7195                         _luci2.ui.loading(true);
7196
7197                         return this.save().then(function() {
7198                                 return _luci2.uci.save();
7199                         }).then(function() {
7200                                 return _luci2.ui.updateChanges();
7201                         }).then(function() {
7202                                 return self.load();
7203                         }).then(function() {
7204                                 self.redraw();
7205                                 self = null;
7206
7207                                 _luci2.ui.loading(false);
7208                                 _luci2.ui.restoreScrollTop();
7209                         });
7210                 },
7211
7212                 insertInto: function(id)
7213                 {
7214                         var self = this;
7215                             self.target = $(id);
7216
7217                         _luci2.ui.loading(true);
7218                         self.target.hide();
7219
7220                         return self.load().then(function() {
7221                                 self.target.empty().append(self.render());
7222                                 self.finish();
7223                                 self.target.show();
7224                                 self = null;
7225                                 _luci2.ui.loading(false);
7226                         });
7227                 }
7228         });
7229 };