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