luci2: fix interface type detection in LuCI2.ui.devicebadge()
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
1 /*
2         LuCI2 - OpenWrt Web Interface
3
4         Copyright 2013 Jo-Philipp Wich <jow@openwrt.org>
5
6         Licensed under the Apache License, Version 2.0 (the "License");
7         you may not use this file except in compliance with the License.
8         You may obtain a copy of the License at
9
10                 http://www.apache.org/licenses/LICENSE-2.0
11 */
12
13 String.prototype.format = function()
14 {
15         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
16         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
17
18         function esc(s, r) {
19                 for( var i = 0; i < r.length; i += 2 )
20                         s = s.replace(r[i], r[i+1]);
21                 return s;
22         }
23
24         var str = this;
25         var out = '';
26         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
27         var a = b = [], numSubstitutions = 0, numMatches = 0;
28
29         while ((a = re.exec(str)) != null)
30         {
31                 var m = a[1];
32                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
33                 var pPrecision = a[6], pType = a[7];
34
35                 numMatches++;
36
37                 if (pType == '%')
38                 {
39                         subst = '%';
40                 }
41                 else
42                 {
43                         if (numSubstitutions < arguments.length)
44                         {
45                                 var param = arguments[numSubstitutions++];
46
47                                 var pad = '';
48                                 if (pPad && pPad.substr(0,1) == "'")
49                                         pad = leftpart.substr(1,1);
50                                 else if (pPad)
51                                         pad = pPad;
52
53                                 var justifyRight = true;
54                                 if (pJustify && pJustify === "-")
55                                         justifyRight = false;
56
57                                 var minLength = -1;
58                                 if (pMinLength)
59                                         minLength = parseInt(pMinLength);
60
61                                 var precision = -1;
62                                 if (pPrecision && pType == 'f')
63                                         precision = parseInt(pPrecision.substring(1));
64
65                                 var subst = param;
66
67                                 switch(pType)
68                                 {
69                                         case 'b':
70                                                 subst = (parseInt(param) || 0).toString(2);
71                                                 break;
72
73                                         case 'c':
74                                                 subst = String.fromCharCode(parseInt(param) || 0);
75                                                 break;
76
77                                         case 'd':
78                                                 subst = (parseInt(param) || 0);
79                                                 break;
80
81                                         case 'u':
82                                                 subst = Math.abs(parseInt(param) || 0);
83                                                 break;
84
85                                         case 'f':
86                                                 subst = (precision > -1)
87                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
88                                                         : (parseFloat(param) || 0.0);
89                                                 break;
90
91                                         case 'o':
92                                                 subst = (parseInt(param) || 0).toString(8);
93                                                 break;
94
95                                         case 's':
96                                                 subst = param;
97                                                 break;
98
99                                         case 'x':
100                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
101                                                 break;
102
103                                         case 'X':
104                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
105                                                 break;
106
107                                         case 'h':
108                                                 subst = esc(param, html_esc);
109                                                 break;
110
111                                         case 'q':
112                                                 subst = esc(param, quot_esc);
113                                                 break;
114
115                                         case 'j':
116                                                 subst = String.serialize(param);
117                                                 break;
118
119                                         case 't':
120                                                 var td = 0;
121                                                 var th = 0;
122                                                 var tm = 0;
123                                                 var ts = (param || 0);
124
125                                                 if (ts > 60) {
126                                                         tm = Math.floor(ts / 60);
127                                                         ts = (ts % 60);
128                                                 }
129
130                                                 if (tm > 60) {
131                                                         th = Math.floor(tm / 60);
132                                                         tm = (tm % 60);
133                                                 }
134
135                                                 if (th > 24) {
136                                                         td = Math.floor(th / 24);
137                                                         th = (th % 24);
138                                                 }
139
140                                                 subst = (td > 0)
141                                                         ? '%dd %dh %dm %ds'.format(td, th, tm, ts)
142                                                         : '%dh %dm %ds'.format(th, tm, ts);
143
144                                                 break;
145
146                                         case 'm':
147                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
148                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
149
150                                                 var i = 0;
151                                                 var val = parseFloat(param || 0);
152                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
153
154                                                 for (i = 0; (i < units.length) && (val > mf); i++)
155                                                         val /= mf;
156
157                                                 subst = val.toFixed(pr) + ' ' + units[i];
158                                                 break;
159                                 }
160
161                                 subst = (typeof(subst) == 'undefined') ? '' : subst.toString();
162
163                                 if (minLength > 0 && pad.length > 0)
164                                         for (var i = 0; i < (minLength - subst.length); i++)
165                                                 subst = justifyRight ? (pad + subst) : (subst + pad);
166                         }
167                 }
168
169                 out += leftpart + subst;
170                 str = str.substr(m.length);
171         }
172
173         return out + str;
174 }
175
176 function LuCI2()
177 {
178         var _luci2 = this;
179
180         var Class = function() { };
181
182         Class.extend = function(properties)
183         {
184                 Class.initializing = true;
185
186                 var prototype = new this();
187                 var superprot = this.prototype;
188
189                 Class.initializing = false;
190
191                 $.extend(prototype, properties, {
192                         callSuper: function() {
193                                 var args = [ ];
194                                 var meth = arguments[0];
195
196                                 if (typeof(superprot[meth]) != 'function')
197                                         return undefined;
198
199                                 for (var i = 1; i < arguments.length; i++)
200                                         args.push(arguments[i]);
201
202                                 return superprot[meth].apply(this, args);
203                         }
204                 });
205
206                 function _class()
207                 {
208                         this.options = arguments[0] || { };
209
210                         if (!Class.initializing && typeof(this.init) == 'function')
211                                 this.init.apply(this, arguments);
212                 }
213
214                 _class.prototype = prototype;
215                 _class.prototype.constructor = _class;
216
217                 _class.extend = arguments.callee;
218
219                 return _class;
220         };
221
222         this.defaults = function(obj, def)
223         {
224                 for (var key in def)
225                         if (typeof(obj[key]) == 'undefined')
226                                 obj[key] = def[key];
227
228                 return obj;
229         };
230
231         this.isDeferred = function(x)
232         {
233                 return (typeof(x) == 'object' &&
234                         typeof(x.then) == 'function' &&
235                         typeof(x.promise) == 'function');
236         };
237
238         this.deferrable = function()
239         {
240                 if (this.isDeferred(arguments[0]))
241                         return arguments[0];
242
243                 var d = $.Deferred();
244                     d.resolve.apply(d, arguments);
245
246                 return d.promise();
247         };
248
249         this.i18n = {
250
251                 loaded: false,
252                 catalog: { },
253                 plural:  function(n) { return 0 + (n != 1) },
254
255                 init: function() {
256                         if (_luci2.i18n.loaded)
257                                 return;
258
259                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
260                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
261
262                         for (var i = 0; i < langs.length; i++)
263                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
264                                         async:    false,
265                                         cache:    true,
266                                         dataType: 'json',
267                                         success:  function(data) {
268                                                 $.extend(_luci2.i18n.catalog, data);
269
270                                                 var pe = _luci2.i18n.catalog[''];
271                                                 if (pe)
272                                                 {
273                                                         delete _luci2.i18n.catalog[''];
274                                                         try {
275                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
276                                                                 _luci2.i18n.plural = pf;
277                                                         } catch (e) { };
278                                                 }
279                                         }
280                                 });
281
282                         _luci2.i18n.loaded = true;
283                 }
284
285         };
286
287         this.tr = function(msgid)
288         {
289                 _luci2.i18n.init();
290
291                 var msgstr = _luci2.i18n.catalog[msgid];
292
293                 if (typeof(msgstr) == 'undefined')
294                         return msgid;
295                 else if (typeof(msgstr) == 'string')
296                         return msgstr;
297                 else
298                         return msgstr[0];
299         };
300
301         this.trp = function(msgid, msgid_plural, count)
302         {
303                 _luci2.i18n.init();
304
305                 var msgstr = _luci2.i18n.catalog[msgid];
306
307                 if (typeof(msgstr) == 'undefined')
308                         return (count == 1) ? msgid : msgid_plural;
309                 else if (typeof(msgstr) == 'string')
310                         return msgstr;
311                 else
312                         return msgstr[_luci2.i18n.plural(count)];
313         };
314
315         this.trc = function(msgctx, msgid)
316         {
317                 _luci2.i18n.init();
318
319                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
320
321                 if (typeof(msgstr) == 'undefined')
322                         return msgid;
323                 else if (typeof(msgstr) == 'string')
324                         return msgstr;
325                 else
326                         return msgstr[0];
327         };
328
329         this.trcp = function(msgctx, msgid, msgid_plural, count)
330         {
331                 _luci2.i18n.init();
332
333                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
334
335                 if (typeof(msgstr) == 'undefined')
336                         return (count == 1) ? msgid : msgid_plural;
337                 else if (typeof(msgstr) == 'string')
338                         return msgstr;
339                 else
340                         return msgstr[_luci2.i18n.plural(count)];
341         };
342
343         this.setHash = function(key, value)
344         {
345                 var h = '';
346                 var data = this.getHash(undefined);
347
348                 if (typeof(value) == 'undefined')
349                         delete data[key];
350                 else
351                         data[key] = value;
352
353                 var keys = [ ];
354                 for (var k in data)
355                         keys.push(k);
356
357                 keys.sort();
358
359                 for (var i = 0; i < keys.length; i++)
360                 {
361                         if (i > 0)
362                                 h += ',';
363
364                         h += keys[i] + ':' + data[keys[i]];
365                 }
366
367                 if (h)
368                         location.hash = '#' + h;
369         };
370
371         this.getHash = function(key)
372         {
373                 var data = { };
374                 var tuples = (location.hash || '#').substring(1).split(/,/);
375
376                 for (var i = 0; i < tuples.length; i++)
377                 {
378                         var tuple = tuples[i].split(/:/);
379                         if (tuple.length == 2)
380                                 data[tuple[0]] = tuple[1];
381                 }
382
383                 if (typeof(key) != 'undefined')
384                         return data[key];
385
386                 return data;
387         };
388
389         this.globals = {
390                 timeout:  15000,
391                 resource: '/luci2',
392                 sid:      '00000000000000000000000000000000'
393         };
394
395         this.rpc = {
396
397                 _id: 1,
398                 _batch: undefined,
399                 _requests: { },
400
401                 _call: function(req, cb)
402                 {
403                         return $.ajax('/ubus', {
404                                 cache:       false,
405                                 contentType: 'application/json',
406                                 data:        JSON.stringify(req),
407                                 dataType:    'json',
408                                 type:        'POST',
409                                 timeout:     _luci2.globals.timeout
410                         }).then(cb);
411                 },
412
413                 _list_cb: function(msg)
414                 {
415                         /* verify message frame */
416                         if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
417                                 throw 'Invalid JSON response';
418
419                         return msg.result;
420                 },
421
422                 _call_cb: function(msg)
423                 {
424                         var data = [ ];
425                         var type = Object.prototype.toString;
426
427                         if (!$.isArray(msg))
428                                 msg = [ msg ];
429
430                         for (var i = 0; i < msg.length; i++)
431                         {
432                                 /* verify message frame */
433                                 if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
434                                         throw 'Invalid JSON response';
435
436                                 /* fetch related request info */
437                                 var req = _luci2.rpc._requests[msg[i].id];
438                                 if (typeof(req) != 'object')
439                                         throw 'No related request for JSON response';
440
441                                 /* fetch response attribute and verify returned type */
442                                 var ret = undefined;
443
444                                 if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
445                                         ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
446
447                                 if (req.expect)
448                                 {
449                                         for (var key in req.expect)
450                                         {
451                                                 if (typeof(ret) != 'undefined' && key != '')
452                                                         ret = ret[key];
453
454                                                 if (type.call(ret) != type.call(req.expect[key]))
455                                                         ret = req.expect[key];
456
457                                                 break;
458                                         }
459                                 }
460
461                                 /* apply filter */
462                                 if (typeof(req.filter) == 'function')
463                                 {
464                                         req.priv[0] = ret;
465                                         req.priv[1] = req.params;
466                                         ret = req.filter.apply(_luci2.rpc, req.priv);
467                                 }
468
469                                 /* store response data */
470                                 if (typeof(req.index) == 'number')
471                                         data[req.index] = ret;
472                                 else
473                                         data = ret;
474
475                                 /* delete request object */
476                                 delete _luci2.rpc._requests[msg[i].id];
477                         }
478
479                         return data;
480                 },
481
482                 list: function()
483                 {
484                         var params = [ ];
485                         for (var i = 0; i < arguments.length; i++)
486                                 params[i] = arguments[i];
487
488                         var msg = {
489                                 jsonrpc: '2.0',
490                                 id:      this._id++,
491                                 method:  'list',
492                                 params:  (params.length > 0) ? params : undefined
493                         };
494
495                         return this._call(msg, this._list_cb);
496                 },
497
498                 batch: function()
499                 {
500                         if (!$.isArray(this._batch))
501                                 this._batch = [ ];
502                 },
503
504                 flush: function()
505                 {
506                         if (!$.isArray(this._batch))
507                                 return _luci2.deferrable([ ]);
508
509                         var req = this._batch;
510                         delete this._batch;
511
512                         /* call rpc */
513                         return this._call(req, this._call_cb);
514                 },
515
516                 declare: function(options)
517                 {
518                         var _rpc = this;
519
520                         return function() {
521                                 /* build parameter object */
522                                 var p_off = 0;
523                                 var params = { };
524                                 if ($.isArray(options.params))
525                                         for (p_off = 0; p_off < options.params.length; p_off++)
526                                                 params[options.params[p_off]] = arguments[p_off];
527
528                                 /* all remaining arguments are private args */
529                                 var priv = [ undefined, undefined ];
530                                 for (; p_off < arguments.length; p_off++)
531                                         priv.push(arguments[p_off]);
532
533                                 /* store request info */
534                                 var req = _rpc._requests[_rpc._id] = {
535                                         expect: options.expect,
536                                         filter: options.filter,
537                                         params: params,
538                                         priv:   priv
539                                 };
540
541                                 /* build message object */
542                                 var msg = {
543                                         jsonrpc: '2.0',
544                                         id:      _rpc._id++,
545                                         method:  'call',
546                                         params:  [
547                                                 _luci2.globals.sid,
548                                                 options.object,
549                                                 options.method,
550                                                 params
551                                         ]
552                                 };
553
554                                 /* when a batch is in progress then store index in request data
555                                  * and push message object onto the stack */
556                                 if ($.isArray(_rpc._batch))
557                                 {
558                                         req.index = _rpc._batch.push(msg) - 1;
559                                         return _luci2.deferrable(msg);
560                                 }
561
562                                 /* call rpc */
563                                 return _rpc._call(msg, _rpc._call_cb);
564                         };
565                 }
566         };
567
568         this.uci = {
569
570                 writable: function()
571                 {
572                         return _luci2.session.access('ubus', 'uci', 'commit');
573                 },
574
575                 add: _luci2.rpc.declare({
576                         object: 'uci',
577                         method: 'add',
578                         params: [ 'config', 'type', 'name', 'values' ],
579                         expect: { section: '' }
580                 }),
581
582                 apply: function()
583                 {
584
585                 },
586
587                 configs: _luci2.rpc.declare({
588                         object: 'uci',
589                         method: 'configs',
590                         expect: { configs: [ ] }
591                 }),
592
593                 _changes: _luci2.rpc.declare({
594                         object: 'uci',
595                         method: 'changes',
596                         params: [ 'config' ],
597                         expect: { changes: [ ] }
598                 }),
599
600                 changes: function(config)
601                 {
602                         if (typeof(config) == 'string')
603                                 return this._changes(config);
604
605                         var configlist;
606                         return this.configs().then(function(configs) {
607                                 _luci2.rpc.batch();
608                                 configlist = configs;
609
610                                 for (var i = 0; i < configs.length; i++)
611                                         _luci2.uci._changes(configs[i]);
612
613                                 return _luci2.rpc.flush();
614                         }).then(function(changes) {
615                                 var rv = { };
616
617                                 for (var i = 0; i < configlist.length; i++)
618                                         if (changes[i].length)
619                                                 rv[configlist[i]] = changes[i];
620
621                                 return rv;
622                         });
623                 },
624
625                 commit: _luci2.rpc.declare({
626                         object: 'uci',
627                         method: 'commit',
628                         params: [ 'config' ]
629                 }),
630
631                 _delete_one: _luci2.rpc.declare({
632                         object: 'uci',
633                         method: 'delete',
634                         params: [ 'config', 'section', 'option' ]
635                 }),
636
637                 _delete_multiple: _luci2.rpc.declare({
638                         object: 'uci',
639                         method: 'delete',
640                         params: [ 'config', 'section', 'options' ]
641                 }),
642
643                 'delete': function(config, section, option)
644                 {
645                         if ($.isArray(option))
646                                 return this._delete_multiple(config, section, option);
647                         else
648                                 return this._delete_one(config, section, option);
649                 },
650
651                 delete_all: _luci2.rpc.declare({
652                         object: 'uci',
653                         method: 'delete',
654                         params: [ 'config', 'type', 'match' ]
655                 }),
656
657                 _foreach: _luci2.rpc.declare({
658                         object: 'uci',
659                         method: 'get',
660                         params: [ 'config', 'type' ],
661                         expect: { values: { } }
662                 }),
663
664                 foreach: function(config, type, cb)
665                 {
666                         return this._foreach(config, type).then(function(sections) {
667                                 for (var s in sections)
668                                         cb(sections[s]);
669                         });
670                 },
671
672                 get: _luci2.rpc.declare({
673                         object: 'uci',
674                         method: 'get',
675                         params: [ 'config', 'section', 'option' ],
676                         expect: { '': { } },
677                         filter: function(data, params) {
678                                 if (typeof(params.option) == 'undefined')
679                                         return data.values ? data.values['.type'] : undefined;
680                                 else
681                                         return data.value;
682                         }
683                 }),
684
685                 get_all: _luci2.rpc.declare({
686                         object: 'uci',
687                         method: 'get',
688                         params: [ 'config', 'section' ],
689                         expect: { values: { } },
690                         filter: function(data, params) {
691                                 if (typeof(params.section) == 'string')
692                                         data['.section'] = params.section;
693                                 else if (typeof(params.config) == 'string')
694                                         data['.package'] = params.config;
695                                 return data;
696                         }
697                 }),
698
699                 get_first: function(config, type, option)
700                 {
701                         return this._foreach(config, type).then(function(sections) {
702                                 for (var s in sections)
703                                 {
704                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
705
706                                         if (typeof(val) != 'undefined')
707                                                 return val;
708                                 }
709
710                                 return undefined;
711                         });
712                 },
713
714                 section: _luci2.rpc.declare({
715                         object: 'uci',
716                         method: 'add',
717                         params: [ 'config', 'type', 'name', 'values' ],
718                         expect: { section: '' }
719                 }),
720
721                 _set: _luci2.rpc.declare({
722                         object: 'uci',
723                         method: 'set',
724                         params: [ 'config', 'section', 'values' ]
725                 }),
726
727                 set: function(config, section, option, value)
728                 {
729                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
730                                 return this.section(config, section, option); /* option -> type */
731                         else if ($.isPlainObject(option))
732                                 return this._set(config, section, option); /* option -> values */
733
734                         var values = { };
735                             values[option] = value;
736
737                         return this._set(config, section, values);
738                 },
739
740                 order: _luci2.rpc.declare({
741                         object: 'uci',
742                         method: 'order',
743                         params: [ 'config', 'sections' ]
744                 })
745         };
746
747         this.network = {
748                 listNetworkNames: function() {
749                         return _luci2.rpc.list('network.interface.*').then(function(list) {
750                                 var names = [ ];
751                                 for (var name in list)
752                                         if (name != 'network.interface.loopback')
753                                                 names.push(name.substring(18));
754                                 names.sort();
755                                 return names;
756                         });
757                 },
758
759                 listDeviceNames: _luci2.rpc.declare({
760                         object: 'network.device',
761                         method: 'status',
762                         expect: { '': { } },
763                         filter: function(data) {
764                                 var names = [ ];
765                                 for (var name in data)
766                                         if (name != 'lo')
767                                                 names.push(name);
768                                 names.sort();
769                                 return names;
770                         }
771                 }),
772
773                 getNetworkStatus: function()
774                 {
775                         var nets = [ ];
776                         var devs = { };
777
778                         return this.listNetworkNames().then(function(names) {
779                                 _luci2.rpc.batch();
780
781                                 for (var i = 0; i < names.length; i++)
782                                         _luci2.network.getInterfaceStatus(names[i]);
783
784                                 return _luci2.rpc.flush();
785                         }).then(function(networks) {
786                                 for (var i = 0; i < networks.length; i++)
787                                 {
788                                         var net = nets[i] = networks[i];
789                                         var dev = net.l3_device || net.l2_device;
790                                         if (dev)
791                                                 net.device = devs[dev] || (devs[dev] = { });
792                                 }
793
794                                 _luci2.rpc.batch();
795
796                                 for (var dev in devs)
797                                         _luci2.network.getDeviceStatus(dev);
798
799                                 return _luci2.rpc.flush();
800                         }).then(function(devices) {
801                                 _luci2.rpc.batch();
802
803                                 for (var i = 0; i < devices.length; i++)
804                                 {
805                                         var brm = devices[i]['bridge-members'];
806                                         delete devices[i]['bridge-members'];
807
808                                         $.extend(devs[devices[i]['device']], devices[i]);
809
810                                         if (!brm)
811                                                 continue;
812
813                                         devs[devices[i]['device']].subdevices = [ ];
814
815                                         for (var j = 0; j < brm.length; j++)
816                                         {
817                                                 if (!devs[brm[j]])
818                                                 {
819                                                         devs[brm[j]] = { };
820                                                         _luci2.network.getDeviceStatus(brm[j]);
821                                                 }
822
823                                                 devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
824                                         }
825                                 }
826
827                                 return _luci2.rpc.flush();
828                         }).then(function(subdevices) {
829                                 for (var i = 0; i < subdevices.length; i++)
830                                         $.extend(devs[subdevices[i]['device']], subdevices[i]);
831
832                                 _luci2.rpc.batch();
833
834                                 for (var dev in devs)
835                                         _luci2.wireless.getDeviceStatus(dev);
836
837                                 return _luci2.rpc.flush();
838                         }).then(function(wifidevices) {
839                                 for (var i = 0; i < wifidevices.length; i++)
840                                         if (wifidevices[i])
841                                                 devs[wifidevices[i]['device']].wireless = wifidevices[i];
842
843                                 nets.sort(function(a, b) {
844                                         if (a['interface'] < b['interface'])
845                                                 return -1;
846                                         else if (a['interface'] > b['interface'])
847                                                 return 1;
848                                         else
849                                                 return 0;
850                                 });
851
852                                 return nets;
853                         });
854                 },
855
856                 findWanInterfaces: function(cb)
857                 {
858                         return this.listNetworkNames().then(function(names) {
859                                 _luci2.rpc.batch();
860
861                                 for (var i = 0; i < names.length; i++)
862                                         _luci2.network.getInterfaceStatus(names[i]);
863
864                                 return _luci2.rpc.flush();
865                         }).then(function(interfaces) {
866                                 var rv = [ undefined, undefined ];
867
868                                 for (var i = 0; i < interfaces.length; i++)
869                                 {
870                                         if (!interfaces[i].route)
871                                                 continue;
872
873                                         for (var j = 0; j < interfaces[i].route.length; j++)
874                                         {
875                                                 var rt = interfaces[i].route[j];
876
877                                                 if (typeof(rt.table) != 'undefined')
878                                                         continue;
879
880                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
881                                                         rv[0] = interfaces[i];
882                                                 else if (rt.target == '::' && rt.mask == 0)
883                                                         rv[1] = interfaces[i];
884                                         }
885                                 }
886
887                                 return rv;
888                         });
889                 },
890
891                 getDHCPLeases: _luci2.rpc.declare({
892                         object: 'luci2.network',
893                         method: 'dhcp_leases',
894                         expect: { leases: [ ] }
895                 }),
896
897                 getDHCPv6Leases: _luci2.rpc.declare({
898                         object: 'luci2.network',
899                         method: 'dhcp6_leases',
900                         expect: { leases: [ ] }
901                 }),
902
903                 getRoutes: _luci2.rpc.declare({
904                         object: 'luci2.network',
905                         method: 'routes',
906                         expect: { routes: [ ] }
907                 }),
908
909                 getIPv6Routes: _luci2.rpc.declare({
910                         object: 'luci2.network',
911                         method: 'routes',
912                         expect: { routes: [ ] }
913                 }),
914
915                 getARPTable: _luci2.rpc.declare({
916                         object: 'luci2.network',
917                         method: 'arp_table',
918                         expect: { entries: [ ] }
919                 }),
920
921                 getInterfaceStatus: _luci2.rpc.declare({
922                         object: 'network.interface',
923                         method: 'status',
924                         params: [ 'interface' ],
925                         expect: { '': { } },
926                         filter: function(data, params) {
927                                 data['interface'] = params['interface'];
928                                 data['l2_device'] = data['device'];
929                                 delete data['device'];
930                                 return data;
931                         }
932                 }),
933
934                 getDeviceStatus: _luci2.rpc.declare({
935                         object: 'network.device',
936                         method: 'status',
937                         params: [ 'name' ],
938                         expect: { '': { } },
939                         filter: function(data, params) {
940                                 data['device'] = params['name'];
941                                 return data;
942                         }
943                 }),
944
945                 getConntrackCount: _luci2.rpc.declare({
946                         object: 'luci2.network',
947                         method: 'conntrack_count',
948                         expect: { '': { count: 0, limit: 0 } }
949                 }),
950
951                 listSwitchNames: _luci2.rpc.declare({
952                         object: 'luci2.network',
953                         method: 'switch_list',
954                         expect: { switches: [ ] }
955                 }),
956
957                 getSwitchInfo: _luci2.rpc.declare({
958                         object: 'luci2.network',
959                         method: 'switch_info',
960                         params: [ 'switch' ],
961                         expect: { info: { } },
962                         filter: function(data, params) {
963                                 data['attrs']      = data['switch'];
964                                 data['vlan_attrs'] = data['vlan'];
965                                 data['port_attrs'] = data['port'];
966                                 data['switch']     = params['switch'];
967
968                                 delete data.vlan;
969                                 delete data.port;
970
971                                 return data;
972                         }
973                 }),
974
975                 getSwitchStatus: _luci2.rpc.declare({
976                         object: 'luci2.network',
977                         method: 'switch_status',
978                         params: [ 'switch' ],
979                         expect: { ports: [ ] }
980                 }),
981
982
983                 runPing: _luci2.rpc.declare({
984                         object: 'luci2.network',
985                         method: 'ping',
986                         params: [ 'data' ],
987                         expect: { '': { code: -1 } }
988                 }),
989
990                 runPing6: _luci2.rpc.declare({
991                         object: 'luci2.network',
992                         method: 'ping6',
993                         params: [ 'data' ],
994                         expect: { '': { code: -1 } }
995                 }),
996
997                 runTraceroute: _luci2.rpc.declare({
998                         object: 'luci2.network',
999                         method: 'traceroute',
1000                         params: [ 'data' ],
1001                         expect: { '': { code: -1 } }
1002                 }),
1003
1004                 runTraceroute6: _luci2.rpc.declare({
1005                         object: 'luci2.network',
1006                         method: 'traceroute6',
1007                         params: [ 'data' ],
1008                         expect: { '': { code: -1 } }
1009                 }),
1010
1011                 runNslookup: _luci2.rpc.declare({
1012                         object: 'luci2.network',
1013                         method: 'nslookup',
1014                         params: [ 'data' ],
1015                         expect: { '': { code: -1 } }
1016                 })
1017         };
1018
1019         this.wireless = {
1020                 listDeviceNames: _luci2.rpc.declare({
1021                         object: 'iwinfo',
1022                         method: 'devices',
1023                         expect: { 'devices': [ ] },
1024                         filter: function(data) {
1025                                 data.sort();
1026                                 return data;
1027                         }
1028                 }),
1029
1030                 getDeviceStatus: _luci2.rpc.declare({
1031                         object: 'iwinfo',
1032                         method: 'info',
1033                         params: [ 'device' ],
1034                         expect: { '': { } },
1035                         filter: function(data, params) {
1036                                 if (!$.isEmptyObject(data))
1037                                 {
1038                                         data['device'] = params['device'];
1039                                         return data;
1040                                 }
1041                                 return undefined;
1042                         }
1043                 }),
1044
1045                 getAssocList: _luci2.rpc.declare({
1046                         object: 'iwinfo',
1047                         method: 'assoclist',
1048                         params: [ 'device' ],
1049                         expect: { results: [ ] },
1050                         filter: function(data, params) {
1051                                 for (var i = 0; i < data.length; i++)
1052                                         data[i]['device'] = params['device'];
1053
1054                                 data.sort(function(a, b) {
1055                                         if (a.bssid < b.bssid)
1056                                                 return -1;
1057                                         else if (a.bssid > b.bssid)
1058                                                 return 1;
1059                                         else
1060                                                 return 0;
1061                                 });
1062
1063                                 return data;
1064                         }
1065                 }),
1066
1067                 getWirelessStatus: function() {
1068                         return this.listDeviceNames().then(function(names) {
1069                                 _luci2.rpc.batch();
1070
1071                                 for (var i = 0; i < names.length; i++)
1072                                         _luci2.wireless.getDeviceStatus(names[i]);
1073
1074                                 return _luci2.rpc.flush();
1075                         }).then(function(networks) {
1076                                 var rv = { };
1077
1078                                 var phy_attrs = [
1079                                         'country', 'channel', 'frequency', 'frequency_offset',
1080                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
1081                                 ];
1082
1083                                 var net_attrs = [
1084                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
1085                                         'signal', 'noise', 'bitrate', 'encryption'
1086                                 ];
1087
1088                                 for (var i = 0; i < networks.length; i++)
1089                                 {
1090                                         var phy = rv[networks[i].phy] || (
1091                                                 rv[networks[i].phy] = { networks: [ ] }
1092                                         );
1093
1094                                         var net = {
1095                                                 device: networks[i].device
1096                                         };
1097
1098                                         for (var j = 0; j < phy_attrs.length; j++)
1099                                                 phy[phy_attrs[j]] = networks[i][phy_attrs[j]];
1100
1101                                         for (var j = 0; j < net_attrs.length; j++)
1102                                                 net[net_attrs[j]] = networks[i][net_attrs[j]];
1103
1104                                         phy.networks.push(net);
1105                                 }
1106
1107                                 return rv;
1108                         });
1109                 },
1110
1111                 getAssocLists: function()
1112                 {
1113                         return this.listDeviceNames().then(function(names) {
1114                                 _luci2.rpc.batch();
1115
1116                                 for (var i = 0; i < names.length; i++)
1117                                         _luci2.wireless.getAssocList(names[i]);
1118
1119                                 return _luci2.rpc.flush();
1120                         }).then(function(assoclists) {
1121                                 var rv = [ ];
1122
1123                                 for (var i = 0; i < assoclists.length; i++)
1124                                         for (var j = 0; j < assoclists[i].length; j++)
1125                                                 rv.push(assoclists[i][j]);
1126
1127                                 return rv;
1128                         });
1129                 },
1130
1131                 formatEncryption: function(enc)
1132                 {
1133                         var format_list = function(l, s)
1134                         {
1135                                 var rv = [ ];
1136                                 for (var i = 0; i < l.length; i++)
1137                                         rv.push(l[i].toUpperCase());
1138                                 return rv.join(s ? s : ', ');
1139                         }
1140
1141                         if (!enc || !enc.enabled)
1142                                 return _luci2.tr('None');
1143
1144                         if (enc.wep)
1145                         {
1146                                 if (enc.wep.length == 2)
1147                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1148                                 else if (enc.wep[0] == 'shared')
1149                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1150                                 else
1151                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1152                         }
1153                         else if (enc.wpa)
1154                         {
1155                                 if (enc.wpa.length == 2)
1156                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1157                                                 format_list(enc.authentication, '/'),
1158                                                 format_list(enc.ciphers, ', ')
1159                                         );
1160                                 else if (enc.wpa[0] == 2)
1161                                         return 'WPA2 %s (%s)'.format(
1162                                                 format_list(enc.authentication, '/'),
1163                                                 format_list(enc.ciphers, ', ')
1164                                         );
1165                                 else
1166                                         return 'WPA %s (%s)'.format(
1167                                                 format_list(enc.authentication, '/'),
1168                                                 format_list(enc.ciphers, ', ')
1169                                         );
1170                         }
1171
1172                         return _luci2.tr('Unknown');
1173                 }
1174         };
1175
1176         this.system = {
1177                 getSystemInfo: _luci2.rpc.declare({
1178                         object: 'system',
1179                         method: 'info',
1180                         expect: { '': { } }
1181                 }),
1182
1183                 getBoardInfo: _luci2.rpc.declare({
1184                         object: 'system',
1185                         method: 'board',
1186                         expect: { '': { } }
1187                 }),
1188
1189                 getDiskInfo: _luci2.rpc.declare({
1190                         object: 'luci2.system',
1191                         method: 'diskfree',
1192                         expect: { '': { } }
1193                 }),
1194
1195                 getInfo: function(cb)
1196                 {
1197                         _luci2.rpc.batch();
1198
1199                         this.getSystemInfo();
1200                         this.getBoardInfo();
1201                         this.getDiskInfo();
1202
1203                         return _luci2.rpc.flush().then(function(info) {
1204                                 var rv = { };
1205
1206                                 $.extend(rv, info[0]);
1207                                 $.extend(rv, info[1]);
1208                                 $.extend(rv, info[2]);
1209
1210                                 return rv;
1211                         });
1212                 },
1213
1214                 getProcessList: _luci2.rpc.declare({
1215                         object: 'luci2.system',
1216                         method: 'process_list',
1217                         expect: { processes: [ ] },
1218                         filter: function(data) {
1219                                 data.sort(function(a, b) { return a.pid - b.pid });
1220                                 return data;
1221                         }
1222                 }),
1223
1224                 getSystemLog: _luci2.rpc.declare({
1225                         object: 'luci2.system',
1226                         method: 'syslog',
1227                         expect: { log: '' }
1228                 }),
1229
1230                 getKernelLog: _luci2.rpc.declare({
1231                         object: 'luci2.system',
1232                         method: 'dmesg',
1233                         expect: { log: '' }
1234                 }),
1235
1236                 getZoneInfo: function(cb)
1237                 {
1238                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1239                 },
1240
1241                 sendSignal: _luci2.rpc.declare({
1242                         object: 'luci2.system',
1243                         method: 'process_signal',
1244                         params: [ 'pid', 'signal' ],
1245                         filter: function(data) {
1246                                 return (data == 0);
1247                         }
1248                 }),
1249
1250                 initList: _luci2.rpc.declare({
1251                         object: 'luci2.system',
1252                         method: 'init_list',
1253                         expect: { initscripts: [ ] },
1254                         filter: function(data) {
1255                                 data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1256                                 return data;
1257                         }
1258                 }),
1259
1260                 initEnabled: function(init, cb)
1261                 {
1262                         return this.initList().then(function(list) {
1263                                 for (var i = 0; i < list.length; i++)
1264                                         if (list[i].name == init)
1265                                                 return !!list[i].enabled;
1266
1267                                 return false;
1268                         });
1269                 },
1270
1271                 initRun: _luci2.rpc.declare({
1272                         object: 'luci2.system',
1273                         method: 'init_action',
1274                         params: [ 'name', 'action' ],
1275                         filter: function(data) {
1276                                 return (data == 0);
1277                         }
1278                 }),
1279
1280                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1281                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1282                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1283                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1284                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1285                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1286
1287
1288                 getRcLocal: _luci2.rpc.declare({
1289                         object: 'luci2.system',
1290                         method: 'rclocal_get',
1291                         expect: { data: '' }
1292                 }),
1293
1294                 setRcLocal: _luci2.rpc.declare({
1295                         object: 'luci2.system',
1296                         method: 'rclocal_set',
1297                         params: [ 'data' ]
1298                 }),
1299
1300
1301                 getCrontab: _luci2.rpc.declare({
1302                         object: 'luci2.system',
1303                         method: 'crontab_get',
1304                         expect: { data: '' }
1305                 }),
1306
1307                 setCrontab: _luci2.rpc.declare({
1308                         object: 'luci2.system',
1309                         method: 'crontab_set',
1310                         params: [ 'data' ]
1311                 }),
1312
1313
1314                 getSSHKeys: _luci2.rpc.declare({
1315                         object: 'luci2.system',
1316                         method: 'sshkeys_get',
1317                         expect: { keys: [ ] }
1318                 }),
1319
1320                 setSSHKeys: _luci2.rpc.declare({
1321                         object: 'luci2.system',
1322                         method: 'sshkeys_set',
1323                         params: [ 'keys' ]
1324                 }),
1325
1326
1327                 setPassword: _luci2.rpc.declare({
1328                         object: 'luci2.system',
1329                         method: 'password_set',
1330                         params: [ 'user', 'password' ]
1331                 }),
1332
1333
1334                 listLEDs: _luci2.rpc.declare({
1335                         object: 'luci2.system',
1336                         method: 'led_list',
1337                         expect: { leds: [ ] }
1338                 }),
1339
1340                 listUSBDevices: _luci2.rpc.declare({
1341                         object: 'luci2.system',
1342                         method: 'usb_list',
1343                         expect: { devices: [ ] }
1344                 }),
1345
1346
1347                 testUpgrade: _luci2.rpc.declare({
1348                         object: 'luci2.system',
1349                         method: 'upgrade_test',
1350                         expect: { '': { } }
1351                 }),
1352
1353                 startUpgrade: _luci2.rpc.declare({
1354                         object: 'luci2.system',
1355                         method: 'upgrade_start',
1356                         params: [ 'keep' ]
1357                 }),
1358
1359                 cleanUpgrade: _luci2.rpc.declare({
1360                         object: 'luci2.system',
1361                         method: 'upgrade_clean'
1362                 }),
1363
1364
1365                 restoreBackup: _luci2.rpc.declare({
1366                         object: 'luci2.system',
1367                         method: 'backup_restore'
1368                 }),
1369
1370                 cleanBackup: _luci2.rpc.declare({
1371                         object: 'luci2.system',
1372                         method: 'backup_clean'
1373                 }),
1374
1375
1376                 getBackupConfig: _luci2.rpc.declare({
1377                         object: 'luci2.system',
1378                         method: 'backup_config_get',
1379                         expect: { config: '' }
1380                 }),
1381
1382                 setBackupConfig: _luci2.rpc.declare({
1383                         object: 'luci2.system',
1384                         method: 'backup_config_set',
1385                         params: [ 'data' ]
1386                 }),
1387
1388
1389                 listBackup: _luci2.rpc.declare({
1390                         object: 'luci2.system',
1391                         method: 'backup_list',
1392                         expect: { files: [ ] }
1393                 }),
1394
1395
1396                 testReset: _luci2.rpc.declare({
1397                         object: 'luci2.system',
1398                         method: 'reset_test',
1399                         expect: { supported: false }
1400                 }),
1401
1402                 startReset: _luci2.rpc.declare({
1403                         object: 'luci2.system',
1404                         method: 'reset_start'
1405                 }),
1406
1407
1408                 performReboot: _luci2.rpc.declare({
1409                         object: 'luci2.system',
1410                         method: 'reboot'
1411                 })
1412         };
1413
1414         this.opkg = {
1415                 updateLists: _luci2.rpc.declare({
1416                         object: 'luci2.opkg',
1417                         method: 'update',
1418                         expect: { '': { } }
1419                 }),
1420
1421                 _allPackages: _luci2.rpc.declare({
1422                         object: 'luci2.opkg',
1423                         method: 'list',
1424                         params: [ 'offset', 'limit', 'pattern' ],
1425                         expect: { '': { } }
1426                 }),
1427
1428                 _installedPackages: _luci2.rpc.declare({
1429                         object: 'luci2.opkg',
1430                         method: 'list_installed',
1431                         params: [ 'offset', 'limit', 'pattern' ],
1432                         expect: { '': { } }
1433                 }),
1434
1435                 _findPackages: _luci2.rpc.declare({
1436                         object: 'luci2.opkg',
1437                         method: 'find',
1438                         params: [ 'offset', 'limit', 'pattern' ],
1439                         expect: { '': { } }
1440                 }),
1441
1442                 _fetchPackages: function(action, offset, limit, pattern)
1443                 {
1444                         var packages = [ ];
1445
1446                         return action(offset, limit, pattern).then(function(list) {
1447                                 if (!list.total || !list.packages)
1448                                         return { length: 0, total: 0 };
1449
1450                                 packages.push.apply(packages, list.packages);
1451                                 packages.total = list.total;
1452
1453                                 if (limit <= 0)
1454                                         limit = list.total;
1455
1456                                 if (packages.length >= limit)
1457                                         return packages;
1458
1459                                 _luci2.rpc.batch();
1460
1461                                 for (var i = offset + packages.length; i < limit; i += 100)
1462                                         action(i, (Math.min(i + 100, limit) % 100) || 100, pattern);
1463
1464                                 return _luci2.rpc.flush();
1465                         }).then(function(lists) {
1466                                 for (var i = 0; i < lists.length; i++)
1467                                 {
1468                                         if (!lists[i].total || !lists[i].packages)
1469                                                 continue;
1470
1471                                         packages.push.apply(packages, lists[i].packages);
1472                                         packages.total = lists[i].total;
1473                                 }
1474
1475                                 return packages;
1476                         });
1477                 },
1478
1479                 listPackages: function(offset, limit, pattern)
1480                 {
1481                         return _luci2.opkg._fetchPackages(_luci2.opkg._allPackages, offset, limit, pattern);
1482                 },
1483
1484                 installedPackages: function(offset, limit, pattern)
1485                 {
1486                         return _luci2.opkg._fetchPackages(_luci2.opkg._installedPackages, offset, limit, pattern);
1487                 },
1488
1489                 findPackages: function(offset, limit, pattern)
1490                 {
1491                         return _luci2.opkg._fetchPackages(_luci2.opkg._findPackages, offset, limit, pattern);
1492                 },
1493
1494                 installPackage: _luci2.rpc.declare({
1495                         object: 'luci2.opkg',
1496                         method: 'install',
1497                         params: [ 'package' ],
1498                         expect: { '': { } }
1499                 }),
1500
1501                 removePackage: _luci2.rpc.declare({
1502                         object: 'luci2.opkg',
1503                         method: 'remove',
1504                         params: [ 'package' ],
1505                         expect: { '': { } }
1506                 }),
1507
1508                 getConfig: _luci2.rpc.declare({
1509                         object: 'luci2.opkg',
1510                         method: 'config_get',
1511                         expect: { config: '' }
1512                 }),
1513
1514                 setConfig: _luci2.rpc.declare({
1515                         object: 'luci2.opkg',
1516                         method: 'config_set',
1517                         params: [ 'data' ]
1518                 })
1519         };
1520
1521         this.session = {
1522
1523                 login: _luci2.rpc.declare({
1524                         object: 'session',
1525                         method: 'login',
1526                         params: [ 'username', 'password' ],
1527                         expect: { '': { } }
1528                 }),
1529
1530                 access: _luci2.rpc.declare({
1531                         object: 'session',
1532                         method: 'access',
1533                         params: [ 'scope', 'object', 'function' ],
1534                         expect: { access: false }
1535                 }),
1536
1537                 isAlive: function()
1538                 {
1539                         return _luci2.session.access('ubus', 'session', 'access');
1540                 },
1541
1542                 startHeartbeat: function()
1543                 {
1544                         this._hearbeatInterval = window.setInterval(function() {
1545                                 _luci2.session.isAlive().then(function(alive) {
1546                                         if (!alive)
1547                                         {
1548                                                 _luci2.session.stopHeartbeat();
1549                                                 _luci2.ui.login(true);
1550                                         }
1551
1552                                 });
1553                         }, _luci2.globals.timeout * 2);
1554                 },
1555
1556                 stopHeartbeat: function()
1557                 {
1558                         if (typeof(this._hearbeatInterval) != 'undefined')
1559                         {
1560                                 window.clearInterval(this._hearbeatInterval);
1561                                 delete this._hearbeatInterval;
1562                         }
1563                 }
1564         };
1565
1566         this.ui = {
1567
1568                 saveScrollTop: function()
1569                 {
1570                         this._scroll_top = $(document).scrollTop();
1571                 },
1572
1573                 restoreScrollTop: function()
1574                 {
1575                         if (typeof(this._scroll_top) == 'undefined')
1576                                 return;
1577
1578                         $(document).scrollTop(this._scroll_top);
1579
1580                         delete this._scroll_top;
1581                 },
1582
1583                 loading: function(enable)
1584                 {
1585                         var win = $(window);
1586                         var body = $('body');
1587
1588                         var state = _luci2.ui._loading || (_luci2.ui._loading = {
1589                                 modal: $('<div />')
1590                                         .addClass('cbi-modal-loader')
1591                                         .append($('<div />').text(_luci2.tr('Loading data...')))
1592                                         .appendTo(body)
1593                         });
1594
1595                         if (enable)
1596                         {
1597                                 body.css('overflow', 'hidden');
1598                                 body.css('padding', 0);
1599                                 body.css('width', win.width());
1600                                 body.css('height', win.height());
1601                                 state.modal.css('width', win.width());
1602                                 state.modal.css('height', win.height());
1603                                 state.modal.show();
1604                         }
1605                         else
1606                         {
1607                                 state.modal.hide();
1608                                 body.css('overflow', '');
1609                                 body.css('padding', '');
1610                                 body.css('width', '');
1611                                 body.css('height', '');
1612                         }
1613                 },
1614
1615                 dialog: function(title, content, options)
1616                 {
1617                         var win = $(window);
1618                         var body = $('body');
1619
1620                         var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
1621                                 dialog: $('<div />')
1622                                         .addClass('cbi-modal-dialog')
1623                                         .append($('<div />')
1624                                                 .append($('<div />')
1625                                                         .addClass('cbi-modal-dialog-header'))
1626                                                 .append($('<div />')
1627                                                         .addClass('cbi-modal-dialog-body'))
1628                                                 .append($('<div />')
1629                                                         .addClass('cbi-modal-dialog-footer')
1630                                                         .append($('<button />')
1631                                                                 .addClass('cbi-button')
1632                                                                 .text(_luci2.tr('Close'))
1633                                                                 .click(function() {
1634                                                                         $('body')
1635                                                                                 .css('overflow', '')
1636                                                                                 .css('padding', '')
1637                                                                                 .css('width', '')
1638                                                                                 .css('height', '');
1639
1640                                                                         $(this).parent().parent().parent().hide();
1641                                                                 }))))
1642                                         .appendTo(body)
1643                         });
1644
1645                         if (typeof(options) != 'object')
1646                                 options = { };
1647
1648                         if (title === false)
1649                         {
1650                                 body
1651                                         .css('overflow', '')
1652                                         .css('padding', '')
1653                                         .css('width', '')
1654                                         .css('height', '');
1655
1656                                 state.dialog.hide();
1657
1658                                 return;
1659                         }
1660
1661                         var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
1662                         var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
1663
1664                         ftr.empty();
1665
1666                         if (options.style == 'confirm')
1667                         {
1668                                 ftr.append($('<button />')
1669                                         .addClass('cbi-button')
1670                                         .text(_luci2.tr('Ok'))
1671                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1672
1673                                 ftr.append($('<button />')
1674                                         .addClass('cbi-button')
1675                                         .text(_luci2.tr('Cancel'))
1676                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1677                         }
1678                         else if (options.style == 'close')
1679                         {
1680                                 ftr.append($('<button />')
1681                                         .addClass('cbi-button')
1682                                         .text(_luci2.tr('Close'))
1683                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1684                         }
1685                         else if (options.style == 'wait')
1686                         {
1687                                 ftr.append($('<button />')
1688                                         .addClass('cbi-button')
1689                                         .text(_luci2.tr('Close'))
1690                                         .attr('disabled', true));
1691                         }
1692
1693                         state.dialog.find('div.cbi-modal-dialog-header').text(title);
1694                         state.dialog.show();
1695
1696                         cnt
1697                                 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1698                                 .empty()
1699                                 .append(content);
1700
1701                         state.dialog.children()
1702                                 .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
1703
1704                         body.css('overflow', 'hidden');
1705                         body.css('padding', 0);
1706                         body.css('width', win.width());
1707                         body.css('height', win.height());
1708                         state.dialog.css('width', win.width());
1709                         state.dialog.css('height', win.height());
1710                 },
1711
1712                 upload: function(title, content, options)
1713                 {
1714                         var state = _luci2.ui._upload || (_luci2.ui._upload = {
1715                                 form: $('<form />')
1716                                         .attr('method', 'post')
1717                                         .attr('action', '/cgi-bin/luci-upload')
1718                                         .attr('enctype', 'multipart/form-data')
1719                                         .attr('target', 'cbi-fileupload-frame')
1720                                         .append($('<p />'))
1721                                         .append($('<input />')
1722                                                 .attr('type', 'hidden')
1723                                                 .attr('name', 'sessionid'))
1724                                         .append($('<input />')
1725                                                 .attr('type', 'hidden')
1726                                                 .attr('name', 'filename'))
1727                                         .append($('<input />')
1728                                                 .attr('type', 'file')
1729                                                 .attr('name', 'filedata')
1730                                                 .addClass('cbi-input-file'))
1731                                         .append($('<div />')
1732                                                 .css('width', '100%')
1733                                                 .addClass('progressbar')
1734                                                 .addClass('intermediate')
1735                                                 .append($('<div />')
1736                                                         .css('width', '100%')))
1737                                         .append($('<iframe />')
1738                                                 .attr('name', 'cbi-fileupload-frame')
1739                                                 .css('width', '1px')
1740                                                 .css('height', '1px')
1741                                                 .css('visibility', 'hidden')),
1742
1743                                 finish_cb: function(ev) {
1744                                         $(this).off('load');
1745
1746                                         var body = (this.contentDocument || this.contentWindow.document).body;
1747                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1748                                                 body = body.firstChild;
1749
1750                                         var json;
1751                                         try {
1752                                                 json = $.parseJSON(body.innerHTML);
1753                                         } catch(e) {
1754                                                 json = {
1755                                                         message: _luci2.tr('Invalid server response received'),
1756                                                         error: [ -1, _luci2.tr('Invalid data') ]
1757                                                 };
1758                                         };
1759
1760                                         if (json.error)
1761                                         {
1762                                                 L.ui.dialog(L.tr('File upload'), [
1763                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1764                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1765                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1766                                                 ], { style: 'close' });
1767                                         }
1768                                         else if (typeof(state.success_cb) == 'function')
1769                                         {
1770                                                 state.success_cb(json);
1771                                         }
1772                                 },
1773
1774                                 confirm_cb: function() {
1775                                         var f = state.form.find('.cbi-input-file');
1776                                         var b = state.form.find('.progressbar');
1777                                         var p = state.form.find('p');
1778
1779                                         if (!f.val())
1780                                                 return;
1781
1782                                         state.form.find('iframe').on('load', state.finish_cb);
1783                                         state.form.submit();
1784
1785                                         f.hide();
1786                                         b.show();
1787                                         p.text(_luci2.tr('File upload in progress â€¦'));
1788
1789                                         state.form.parent().parent().find('button').prop('disabled', true);
1790                                 }
1791                         });
1792
1793                         state.form.find('.progressbar').hide();
1794                         state.form.find('.cbi-input-file').val('').show();
1795                         state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1796
1797                         state.form.find('[name=sessionid]').val(_luci2.globals.sid);
1798                         state.form.find('[name=filename]').val(options.filename);
1799
1800                         state.success_cb = options.success;
1801
1802                         _luci2.ui.dialog(title || _luci2.tr('File upload'), state.form, {
1803                                 style: 'confirm',
1804                                 confirm: state.confirm_cb
1805                         });
1806                 },
1807
1808                 reconnect: function()
1809                 {
1810                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1811                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1812                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1813                         var images    = $();
1814                         var interval, timeout;
1815
1816                         _luci2.ui.dialog(
1817                                 _luci2.tr('Waiting for device'), [
1818                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring â€¦')),
1819                                         $('<div />')
1820                                                 .css('width', '100%')
1821                                                 .addClass('progressbar')
1822                                                 .addClass('intermediate')
1823                                                 .append($('<div />')
1824                                                         .css('width', '100%'))
1825                                 ], { style: 'wait' }
1826                         );
1827
1828                         for (var i = 0; i < protocols.length; i++)
1829                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1830
1831                         //_luci2.network.getNetworkStatus(function(s) {
1832                         //      for (var i = 0; i < protocols.length; i++)
1833                         //      {
1834                         //              for (var j = 0; j < s.length; j++)
1835                         //              {
1836                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1837                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1838                         //
1839                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1840                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1841                         //              }
1842                         //      }
1843                         //}).then(function() {
1844                                 images.on('load', function() {
1845                                         var url = this.getAttribute('url');
1846                                         _luci2.session.isAlive().then(function(access) {
1847                                                 if (access)
1848                                                 {
1849                                                         window.clearTimeout(timeout);
1850                                                         window.clearInterval(interval);
1851                                                         _luci2.ui.dialog(false);
1852                                                         images = null;
1853                                                 }
1854                                                 else
1855                                                 {
1856                                                         location.href = url;
1857                                                 }
1858                                         });
1859                                 });
1860
1861                                 interval = window.setInterval(function() {
1862                                         images.each(function() {
1863                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1864                                         });
1865                                 }, 5000);
1866
1867                                 timeout = window.setTimeout(function() {
1868                                         window.clearInterval(interval);
1869                                         images.off('load');
1870
1871                                         _luci2.ui.dialog(
1872                                                 _luci2.tr('Device not responding'),
1873                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1874                                                 { style: 'close' }
1875                                         );
1876                                 }, 180000);
1877                         //});
1878                 },
1879
1880                 login: function(invalid)
1881                 {
1882                         var state = _luci2.ui._login || (_luci2.ui._login = {
1883                                 form: $('<form />')
1884                                         .attr('target', '')
1885                                         .attr('method', 'post')
1886                                         .append($('<p />')
1887                                                 .addClass('alert-message')
1888                                                 .text(_luci2.tr('Wrong username or password given!')))
1889                                         .append($('<p />')
1890                                                 .append($('<label />')
1891                                                         .text(_luci2.tr('Username'))
1892                                                         .append($('<br />'))
1893                                                         .append($('<input />')
1894                                                                 .attr('type', 'text')
1895                                                                 .attr('name', 'username')
1896                                                                 .attr('value', 'root')
1897                                                                 .addClass('cbi-input-text')
1898                                                                 .keypress(function(ev) {
1899                                                                         if (ev.which == 10 || ev.which == 13)
1900                                                                                 state.confirm_cb();
1901                                                                 }))))
1902                                         .append($('<p />')
1903                                                 .append($('<label />')
1904                                                         .text(_luci2.tr('Password'))
1905                                                         .append($('<br />'))
1906                                                         .append($('<input />')
1907                                                                 .attr('type', 'password')
1908                                                                 .attr('name', 'password')
1909                                                                 .addClass('cbi-input-password')
1910                                                                 .keypress(function(ev) {
1911                                                                         if (ev.which == 10 || ev.which == 13)
1912                                                                                 state.confirm_cb();
1913                                                                 }))))
1914                                         .append($('<p />')
1915                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok')))),
1916
1917                                 response_cb: function(response) {
1918                                         if (!response.ubus_rpc_session)
1919                                         {
1920                                                 _luci2.ui.login(true);
1921                                         }
1922                                         else
1923                                         {
1924                                                 _luci2.globals.sid = response.ubus_rpc_session;
1925                                                 _luci2.setHash('id', _luci2.globals.sid);
1926                                                 _luci2.session.startHeartbeat();
1927                                                 _luci2.ui.dialog(false);
1928                                                 state.deferred.resolve();
1929                                         }
1930                                 },
1931
1932                                 confirm_cb: function() {
1933                                         var u = state.form.find('[name=username]').val();
1934                                         var p = state.form.find('[name=password]').val();
1935
1936                                         if (!u)
1937                                                 return;
1938
1939                                         _luci2.ui.dialog(
1940                                                 _luci2.tr('Logging in'), [
1941                                                         $('<p />').text(_luci2.tr('Log in in progress â€¦')),
1942                                                         $('<div />')
1943                                                                 .css('width', '100%')
1944                                                                 .addClass('progressbar')
1945                                                                 .addClass('intermediate')
1946                                                                 .append($('<div />')
1947                                                                         .css('width', '100%'))
1948                                                 ], { style: 'wait' }
1949                                         );
1950
1951                                         _luci2.globals.sid = '00000000000000000000000000000000';
1952                                         _luci2.session.login(u, p).then(state.response_cb);
1953                                 }
1954                         });
1955
1956                         if (!state.deferred || state.deferred.state() != 'pending')
1957                                 state.deferred = $.Deferred();
1958
1959                         /* try to find sid from hash */
1960                         var sid = _luci2.getHash('id');
1961                         if (sid && sid.match(/^[a-f0-9]{32}$/))
1962                         {
1963                                 _luci2.globals.sid = sid;
1964                                 _luci2.session.isAlive().then(function(access) {
1965                                         if (access)
1966                                         {
1967                                                 _luci2.session.startHeartbeat();
1968                                                 state.deferred.resolve();
1969                                         }
1970                                         else
1971                                         {
1972                                                 _luci2.setHash('id', undefined);
1973                                                 _luci2.ui.login();
1974                                         }
1975                                 });
1976
1977                                 return state.deferred;
1978                         }
1979
1980                         if (invalid)
1981                                 state.form.find('.alert-message').show();
1982                         else
1983                                 state.form.find('.alert-message').hide();
1984
1985                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), state.form, {
1986                                 style: 'confirm',
1987                                 confirm: state.confirm_cb
1988                         });
1989
1990                         state.form.find('[name=password]').focus();
1991
1992                         return state.deferred;
1993                 },
1994
1995                 cryptPassword: _luci2.rpc.declare({
1996                         object: 'luci2.ui',
1997                         method: 'crypt',
1998                         params: [ 'data' ],
1999                         expect: { crypt: '' }
2000                 }),
2001
2002
2003                 _acl_merge_scope: function(acl_scope, scope)
2004                 {
2005                         if ($.isArray(scope))
2006                         {
2007                                 for (var i = 0; i < scope.length; i++)
2008                                         acl_scope[scope[i]] = true;
2009                         }
2010                         else if ($.isPlainObject(scope))
2011                         {
2012                                 for (var object_name in scope)
2013                                 {
2014                                         if (!$.isArray(scope[object_name]))
2015                                                 continue;
2016
2017                                         var acl_object = acl_scope[object_name] || (acl_scope[object_name] = { });
2018
2019                                         for (var i = 0; i < scope[object_name].length; i++)
2020                                                 acl_object[scope[object_name][i]] = true;
2021                                 }
2022                         }
2023                 },
2024
2025                 _acl_merge_permission: function(acl_perm, perm)
2026                 {
2027                         if ($.isPlainObject(perm))
2028                         {
2029                                 for (var scope_name in perm)
2030                                 {
2031                                         var acl_scope = acl_perm[scope_name] || (acl_perm[scope_name] = { });
2032                                         this._acl_merge_scope(acl_scope, perm[scope_name]);
2033                                 }
2034                         }
2035                 },
2036
2037                 _acl_merge_group: function(acl_group, group)
2038                 {
2039                         if ($.isPlainObject(group))
2040                         {
2041                                 if (!acl_group.description)
2042                                         acl_group.description = group.description;
2043
2044                                 if (group.read)
2045                                 {
2046                                         var acl_perm = acl_group.read || (acl_group.read = { });
2047                                         this._acl_merge_permission(acl_perm, group.read);
2048                                 }
2049
2050                                 if (group.write)
2051                                 {
2052                                         var acl_perm = acl_group.write || (acl_group.write = { });
2053                                         this._acl_merge_permission(acl_perm, group.write);
2054                                 }
2055                         }
2056                 },
2057
2058                 _acl_merge_tree: function(acl_tree, tree)
2059                 {
2060                         if ($.isPlainObject(tree))
2061                         {
2062                                 for (var group_name in tree)
2063                                 {
2064                                         var acl_group = acl_tree[group_name] || (acl_tree[group_name] = { });
2065                                         this._acl_merge_group(acl_group, tree[group_name]);
2066                                 }
2067                         }
2068                 },
2069
2070                 listAvailableACLs: _luci2.rpc.declare({
2071                         object: 'luci2.ui',
2072                         method: 'acls',
2073                         expect: { acls: [ ] },
2074                         filter: function(trees) {
2075                                 var acl_tree = { };
2076                                 for (var i = 0; i < trees.length; i++)
2077                                         _luci2.ui._acl_merge_tree(acl_tree, trees[i]);
2078                                 return acl_tree;
2079                         }
2080                 }),
2081
2082                 renderMainMenu: _luci2.rpc.declare({
2083                         object: 'luci2.ui',
2084                         method: 'menu',
2085                         expect: { menu: { } },
2086                         filter: function(entries) {
2087                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
2088                                 _luci2.globals.mainMenu.entries(entries);
2089
2090                                 $('#mainmenu')
2091                                         .empty()
2092                                         .append(_luci2.globals.mainMenu.render(0, 1));
2093                         }
2094                 }),
2095
2096                 renderViewMenu: function()
2097                 {
2098                         $('#viewmenu')
2099                                 .empty()
2100                                 .append(_luci2.globals.mainMenu.render(2, 900));
2101                 },
2102
2103                 renderView: function(node)
2104                 {
2105                         var name = node.view.split(/\//).join('.');
2106
2107                         if (_luci2.globals.currentView)
2108                                 _luci2.globals.currentView.finish();
2109
2110                         _luci2.ui.renderViewMenu();
2111
2112                         if (!_luci2._views)
2113                                 _luci2._views = { };
2114
2115                         _luci2.setHash('view', node.view);
2116
2117                         if (_luci2._views[name] instanceof _luci2.ui.view)
2118                         {
2119                                 _luci2.globals.currentView = _luci2._views[name];
2120                                 return _luci2._views[name].render();
2121                         }
2122
2123                         var url = _luci2.globals.resource + '/view/' + name + '.js';
2124
2125                         return $.ajax(url, {
2126                                 method: 'GET',
2127                                 cache: true,
2128                                 dataType: 'text'
2129                         }).then(function(data) {
2130                                 try {
2131                                         var viewConstructorSource = (
2132                                                 '(function(L, $) { ' +
2133                                                         'return %s' +
2134                                                 '})(_luci2, $);\n\n' +
2135                                                 '//@ sourceURL=%s'
2136                                         ).format(data, url);
2137
2138                                         var viewConstructor = eval(viewConstructorSource);
2139
2140                                         _luci2._views[name] = new viewConstructor({
2141                                                 name: name,
2142                                                 acls: node.write || { }
2143                                         });
2144
2145                                         _luci2.globals.currentView = _luci2._views[name];
2146                                         return _luci2._views[name].render();
2147                                 }
2148                                 catch(e) {
2149                                         alert('Unable to instantiate view "%s": %s'.format(url, e));
2150                                 };
2151
2152                                 return $.Deferred().resolve();
2153                         });
2154                 },
2155
2156                 updateHostname: function()
2157                 {
2158                         return _luci2.system.getBoardInfo().then(function(info) {
2159                                 if (info.hostname)
2160                                         $('#hostname').text(info.hostname);
2161                         });
2162                 },
2163
2164                 updateChanges: function()
2165                 {
2166                         return _luci2.uci.changes().then(function(changes) {
2167                                 var n = 0;
2168                                 var html = '';
2169
2170                                 for (var config in changes)
2171                                 {
2172                                         var log = [ ];
2173
2174                                         for (var i = 0; i < changes[config].length; i++)
2175                                         {
2176                                                 var c = changes[config][i];
2177
2178                                                 switch (c[0])
2179                                                 {
2180                                                 case 'order':
2181                                                         break;
2182
2183                                                 case 'remove':
2184                                                         if (c.length < 3)
2185                                                                 log.push('uci delete %s.<del>%s</del>'.format(config, c[1]));
2186                                                         else
2187                                                                 log.push('uci delete %s.%s.<del>%s</del>'.format(config, c[1], c[2]));
2188                                                         break;
2189
2190                                                 case 'rename':
2191                                                         if (c.length < 4)
2192                                                                 log.push('uci rename %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3]));
2193                                                         else
2194                                                                 log.push('uci rename %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2195                                                         break;
2196
2197                                                 case 'add':
2198                                                         log.push('uci add %s <ins>%s</ins> (= <ins><strong>%s</strong></ins>)'.format(config, c[2], c[1]));
2199                                                         break;
2200
2201                                                 case 'list-add':
2202                                                         log.push('uci add_list %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2203                                                         break;
2204
2205                                                 case 'list-del':
2206                                                         log.push('uci del_list %s.%s.<del>%s=<strong>%s</strong></del>'.format(config, c[1], c[2], c[3], c[4]));
2207                                                         break;
2208
2209                                                 case 'set':
2210                                                         if (c.length < 4)
2211                                                                 log.push('uci set %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
2212                                                         else
2213                                                                 log.push('uci set %s.%s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2], c[3], c[4]));
2214                                                         break;
2215                                                 }
2216                                         }
2217
2218                                         html += '<code>/etc/config/%s</code><pre class="uci-changes">%s</pre>'.format(config, log.join('\n'));
2219                                         n += changes[config].length;
2220                                 }
2221
2222                                 if (n > 0)
2223                                         $('#changes')
2224                                                 .empty()
2225                                                 .show()
2226                                                 .append($('<a />')
2227                                                         .attr('href', '#')
2228                                                         .addClass('label')
2229                                                         .addClass('notice')
2230                                                         .text(_luci2.trcp('Pending configuration changes', '1 change', '%d changes', n).format(n))
2231                                                         .click(function(ev) {
2232                                                                 _luci2.ui.dialog(_luci2.tr('Staged configuration changes'), html, { style: 'close' });
2233                                                                 ev.preventDefault();
2234                                                         }));
2235                                 else
2236                                         $('#changes')
2237                                                 .hide();
2238                         });
2239                 },
2240
2241                 init: function()
2242                 {
2243                         _luci2.ui.loading(true);
2244
2245                         $.when(
2246                                 _luci2.ui.updateHostname(),
2247                                 _luci2.ui.updateChanges(),
2248                                 _luci2.ui.renderMainMenu()
2249                         ).then(function() {
2250                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
2251                                         _luci2.ui.loading(false);
2252                                 })
2253                         });
2254                 }
2255         };
2256
2257         var AbstractWidget = Class.extend({
2258                 i18n: function(text) {
2259                         return text;
2260                 },
2261
2262                 toString: function() {
2263                         var x = document.createElement('div');
2264                                 x.appendChild(this.render());
2265
2266                         return x.innerHTML;
2267                 },
2268
2269                 insertInto: function(id) {
2270                         return $(id).empty().append(this.render());
2271                 }
2272         });
2273
2274         this.ui.view = AbstractWidget.extend({
2275                 _fetch_template: function()
2276                 {
2277                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
2278                                 method: 'GET',
2279                                 cache: true,
2280                                 dataType: 'text',
2281                                 success: function(data) {
2282                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
2283                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
2284                                                 switch (p1)
2285                                                 {
2286                                                 case '#':
2287                                                         return '';
2288
2289                                                 case ':':
2290                                                         return _luci2.tr(p2);
2291
2292                                                 case '=':
2293                                                         return _luci2.globals[p2] || '';
2294
2295                                                 default:
2296                                                         return '(?' + match + ')';
2297                                                 }
2298                                         });
2299
2300                                         $('#maincontent').append(data);
2301                                 }
2302                         });
2303                 },
2304
2305                 execute: function()
2306                 {
2307                         throw "Not implemented";
2308                 },
2309
2310                 render: function()
2311                 {
2312                         var container = $('#maincontent');
2313
2314                         container.empty();
2315
2316                         if (this.title)
2317                                 container.append($('<h2 />').append(this.title));
2318
2319                         if (this.description)
2320                                 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
2321
2322                         var self = this;
2323                         return this._fetch_template().then(function() {
2324                                 return _luci2.deferrable(self.execute());
2325                         });
2326                 },
2327
2328                 repeat: function(func, interval)
2329                 {
2330                         var self = this;
2331
2332                         if (!self._timeouts)
2333                                 self._timeouts = [ ];
2334
2335                         var index = self._timeouts.length;
2336
2337                         if (typeof(interval) != 'number')
2338                                 interval = 5000;
2339
2340                         var setTimer, runTimer;
2341
2342                         setTimer = function() {
2343                                 self._timeouts[index] = window.setTimeout(runTimer, interval);
2344                         };
2345
2346                         runTimer = function() {
2347                                 _luci2.deferrable(func.call(self)).then(setTimer);
2348                         };
2349
2350                         runTimer();
2351                 },
2352
2353                 finish: function()
2354                 {
2355                         if ($.isArray(this._timeouts))
2356                         {
2357                                 for (var i = 0; i < this._timeouts.length; i++)
2358                                         window.clearTimeout(this._timeouts[i]);
2359
2360                                 delete this._timeouts;
2361                         }
2362                 }
2363         });
2364
2365         this.ui.menu = AbstractWidget.extend({
2366                 init: function() {
2367                         this._nodes = { };
2368                 },
2369
2370                 entries: function(entries)
2371                 {
2372                         for (var entry in entries)
2373                         {
2374                                 var path = entry.split(/\//);
2375                                 var node = this._nodes;
2376
2377                                 for (i = 0; i < path.length; i++)
2378                                 {
2379                                         if (!node.childs)
2380                                                 node.childs = { };
2381
2382                                         if (!node.childs[path[i]])
2383                                                 node.childs[path[i]] = { };
2384
2385                                         node = node.childs[path[i]];
2386                                 }
2387
2388                                 $.extend(node, entries[entry]);
2389                         }
2390                 },
2391
2392                 _indexcmp: function(a, b)
2393                 {
2394                         var x = a.index || 0;
2395                         var y = b.index || 0;
2396                         return (x - y);
2397                 },
2398
2399                 firstChildView: function(node)
2400                 {
2401                         if (node.view)
2402                                 return node;
2403
2404                         var nodes = [ ];
2405                         for (var child in (node.childs || { }))
2406                                 nodes.push(node.childs[child]);
2407
2408                         nodes.sort(this._indexcmp);
2409
2410                         for (var i = 0; i < nodes.length; i++)
2411                         {
2412                                 var child = this.firstChildView(nodes[i]);
2413                                 if (child)
2414                                 {
2415                                         for (var key in child)
2416                                                 if (!node.hasOwnProperty(key) && child.hasOwnProperty(key))
2417                                                         node[key] = child[key];
2418
2419                                         return node;
2420                                 }
2421                         }
2422
2423                         return undefined;
2424                 },
2425
2426                 _onclick: function(ev)
2427                 {
2428                         _luci2.ui.loading(true);
2429                         _luci2.ui.renderView(ev.data).then(function() {
2430                                 _luci2.ui.loading(false);
2431                         });
2432
2433                         ev.preventDefault();
2434                         this.blur();
2435                 },
2436
2437                 _render: function(childs, level, min, max)
2438                 {
2439                         var nodes = [ ];
2440                         for (var node in childs)
2441                         {
2442                                 var child = this.firstChildView(childs[node]);
2443                                 if (child)
2444                                         nodes.push(childs[node]);
2445                         }
2446
2447                         nodes.sort(this._indexcmp);
2448
2449                         var list = $('<ul />');
2450
2451                         if (level == 0)
2452                                 list.addClass('nav');
2453                         else if (level == 1)
2454                                 list.addClass('dropdown-menu');
2455
2456                         for (var i = 0; i < nodes.length; i++)
2457                         {
2458                                 if (!_luci2.globals.defaultNode)
2459                                 {
2460                                         var v = _luci2.getHash('view');
2461                                         if (!v || v == nodes[i].view)
2462                                                 _luci2.globals.defaultNode = nodes[i];
2463                                 }
2464
2465                                 var item = $('<li />')
2466                                         .append($('<a />')
2467                                                 .attr('href', '#')
2468                                                 .text(_luci2.tr(nodes[i].title))
2469                                                 .click(nodes[i], this._onclick))
2470                                         .appendTo(list);
2471
2472                                 if (nodes[i].childs && level < max)
2473                                 {
2474                                         item.addClass('dropdown');
2475                                         item.find('a').addClass('menu');
2476                                         item.append(this._render(nodes[i].childs, level + 1));
2477                                 }
2478                         }
2479
2480                         return list.get(0);
2481                 },
2482
2483                 render: function(min, max)
2484                 {
2485                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2486                         return this._render(top.childs, 0, min, max);
2487                 },
2488
2489                 getNode: function(path, max)
2490                 {
2491                         var p = path.split(/\//);
2492                         var n = this._nodes;
2493
2494                         if (typeof(max) == 'undefined')
2495                                 max = p.length;
2496
2497                         for (var i = 0; i < max; i++)
2498                         {
2499                                 if (!n.childs[p[i]])
2500                                         return undefined;
2501
2502                                 n = n.childs[p[i]];
2503                         }
2504
2505                         return n;
2506                 }
2507         });
2508
2509         this.ui.table = AbstractWidget.extend({
2510                 init: function()
2511                 {
2512                         this._rows = [ ];
2513                 },
2514
2515                 row: function(values)
2516                 {
2517                         if ($.isArray(values))
2518                         {
2519                                 this._rows.push(values);
2520                         }
2521                         else if ($.isPlainObject(values))
2522                         {
2523                                 var v = [ ];
2524                                 for (var i = 0; i < this.options.columns.length; i++)
2525                                 {
2526                                         var col = this.options.columns[i];
2527
2528                                         if (typeof col.key == 'string')
2529                                                 v.push(values[col.key]);
2530                                         else
2531                                                 v.push(null);
2532                                 }
2533                                 this._rows.push(v);
2534                         }
2535                 },
2536
2537                 rows: function(rows)
2538                 {
2539                         for (var i = 0; i < rows.length; i++)
2540                                 this.row(rows[i]);
2541                 },
2542
2543                 render: function(id)
2544                 {
2545                         var fieldset = document.createElement('fieldset');
2546                                 fieldset.className = 'cbi-section';
2547
2548                         if (this.options.caption)
2549                         {
2550                                 var legend = document.createElement('legend');
2551                                 $(legend).append(this.options.caption);
2552                                 fieldset.appendChild(legend);
2553                         }
2554
2555                         var table = document.createElement('table');
2556                                 table.className = 'cbi-section-table';
2557
2558                         var has_caption = false;
2559                         var has_description = false;
2560
2561                         for (var i = 0; i < this.options.columns.length; i++)
2562                                 if (this.options.columns[i].caption)
2563                                 {
2564                                         has_caption = true;
2565                                         break;
2566                                 }
2567                                 else if (this.options.columns[i].description)
2568                                 {
2569                                         has_description = true;
2570                                         break;
2571                                 }
2572
2573                         if (has_caption)
2574                         {
2575                                 var tr = table.insertRow(-1);
2576                                         tr.className = 'cbi-section-table-titles';
2577
2578                                 for (var i = 0; i < this.options.columns.length; i++)
2579                                 {
2580                                         var col = this.options.columns[i];
2581                                         var th = document.createElement('th');
2582                                                 th.className = 'cbi-section-table-cell';
2583
2584                                         tr.appendChild(th);
2585
2586                                         if (col.width)
2587                                                 th.style.width = col.width;
2588
2589                                         if (col.align)
2590                                                 th.style.textAlign = col.align;
2591
2592                                         if (col.caption)
2593                                                 $(th).append(col.caption);
2594                                 }
2595                         }
2596
2597                         if (has_description)
2598                         {
2599                                 var tr = table.insertRow(-1);
2600                                         tr.className = 'cbi-section-table-descr';
2601
2602                                 for (var i = 0; i < this.options.columns.length; i++)
2603                                 {
2604                                         var col = this.options.columns[i];
2605                                         var th = document.createElement('th');
2606                                                 th.className = 'cbi-section-table-cell';
2607
2608                                         tr.appendChild(th);
2609
2610                                         if (col.width)
2611                                                 th.style.width = col.width;
2612
2613                                         if (col.align)
2614                                                 th.style.textAlign = col.align;
2615
2616                                         if (col.description)
2617                                                 $(th).append(col.description);
2618                                 }
2619                         }
2620
2621                         if (this._rows.length == 0)
2622                         {
2623                                 if (this.options.placeholder)
2624                                 {
2625                                         var tr = table.insertRow(-1);
2626                                         var td = tr.insertCell(-1);
2627                                                 td.className = 'cbi-section-table-cell';
2628
2629                                         td.colSpan = this.options.columns.length;
2630                                         $(td).append(this.options.placeholder);
2631                                 }
2632                         }