Initial commit of LuCI2
[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 alphacmp = function(a, b)
181         {
182                 if (a < b)
183                         return -1;
184                 else if (a > b)
185                         return 1;
186                 else
187                         return 0;
188         };
189
190         var retcb = function(cb, rv)
191         {
192                 if (typeof(cb) == 'function')
193                         cb(rv);
194
195                 return rv;
196         };
197
198         var isa = function(x, t)
199         {
200                 if (typeof(x) != 'string' && typeof(t) == 'string')
201                         return (Object.prototype.toString.call(x) == '[object ' + t + ']');
202
203                 return (Object.prototype.toString.call(x) == Object.prototype.toString.call(t));
204         };
205
206         var rcall = function(obj, func, params, res_attr, res_default, cb, filter)
207         {
208                 if (typeof(params) == 'undefined')
209                         params = { };
210
211                 return _luci2.rpc.call(obj, func, params).then(function(res) {
212                         if (res[0] != 0 || typeof(res[1]) == 'undefined')
213                                 return retcb(cb, res_default);
214
215                         var rv = (typeof(res_attr) != 'undefined') ? res[1][res_attr] : res[1];
216                         if (typeof(rv) == 'undefined' || (typeof(res_default) != 'undefined' && !isa(rv, res_default)))
217                                 return retcb(cb, res_default);
218
219                         if (typeof(filter) == 'function')
220                                 rv = filter(rv);
221
222                         return retcb(cb, rv);
223                 });
224         };
225
226         var Class = function() { };
227
228         Class.extend = function(properties)
229         {
230                 Class.initializing = true;
231
232                 var prototype = new this();
233                 var superprot = this.prototype;
234
235                 Class.initializing = false;
236
237                 $.extend(prototype, properties, {
238                         callSuper: function() {
239                                 var args = [ ];
240                                 var meth = arguments[0];
241
242                                 if (typeof(superprot[meth]) != 'function')
243                                         return undefined;
244
245                                 for (var i = 1; i < arguments.length; i++)
246                                         args.push(arguments[i]);
247
248                                 return superprot[meth].apply(this, args);
249                         }
250                 });
251
252                 function _class()
253                 {
254                         this.options = arguments[0] || { };
255
256                         if (!Class.initializing && typeof(this.init) == 'function')
257                                 this.init.apply(this, arguments);
258                 }
259
260                 _class.prototype = prototype;
261                 _class.prototype.constructor = _class;
262
263                 _class.extend = arguments.callee;
264
265                 return _class;
266         };
267
268         this.defaults = function(obj, def)
269         {
270                 for (var key in def)
271                         if (typeof(obj[key]) == 'undefined')
272                                 obj[key] = def[key];
273
274                 return obj;
275         };
276
277         this.deferred = function(x)
278         {
279                 return (typeof(x) == 'object' &&
280                         typeof(x.then) == 'function' &&
281                         typeof(x.promise) == 'function');
282         };
283
284         this.deferrable = function()
285         {
286                 if (this.deferred(arguments[0]))
287                         return arguments[0];
288
289                 var d = $.Deferred();
290                     d.resolve.apply(d, arguments);
291
292                 return d.promise();
293         };
294
295         this.i18n = {
296
297                 loaded: false,
298                 catalog: { },
299                 plural:  function(n) { return 0 + (n != 1) },
300
301                 init: function() {
302                         if (_luci2.i18n.loaded)
303                                 return;
304
305                         var lang = (navigator.userLanguage || navigator.language || 'en').toLowerCase();
306                         var langs = (lang.indexOf('-') > -1) ? [ lang, lang.split(/-/)[0] ] : [ lang ];
307
308                         for (var i = 0; i < langs.length; i++)
309                                 $.ajax('%s/i18n/base.%s.json'.format(_luci2.globals.resource, langs[i]), {
310                                         async:    false,
311                                         cache:    true,
312                                         dataType: 'json',
313                                         success:  function(data) {
314                                                 $.extend(_luci2.i18n.catalog, data);
315
316                                                 var pe = _luci2.i18n.catalog[''];
317                                                 if (pe)
318                                                 {
319                                                         delete _luci2.i18n.catalog[''];
320                                                         try {
321                                                                 var pf = new Function('n', 'return 0 + (' + pe + ')');
322                                                                 _luci2.i18n.plural = pf;
323                                                         } catch (e) { };
324                                                 }
325                                         }
326                                 });
327
328                         _luci2.i18n.loaded = true;
329                 }
330
331         };
332
333         this.tr = function(msgid)
334         {
335                 _luci2.i18n.init();
336
337                 var msgstr = _luci2.i18n.catalog[msgid];
338
339                 if (typeof(msgstr) == 'undefined')
340                         return msgid;
341                 else if (typeof(msgstr) == 'string')
342                         return msgstr;
343                 else
344                         return msgstr[0];
345         };
346
347         this.trp = function(msgid, msgid_plural, count)
348         {
349                 _luci2.i18n.init();
350
351                 var msgstr = _luci2.i18n.catalog[msgid];
352
353                 if (typeof(msgstr) == 'undefined')
354                         return (count == 1) ? msgid : msgid_plural;
355                 else if (typeof(msgstr) == 'string')
356                         return msgstr;
357                 else
358                         return msgstr[_luci2.i18n.plural(count)];
359         };
360
361         this.trc = function(msgctx, msgid)
362         {
363                 _luci2.i18n.init();
364
365                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
366
367                 if (typeof(msgstr) == 'undefined')
368                         return msgid;
369                 else if (typeof(msgstr) == 'string')
370                         return msgstr;
371                 else
372                         return msgstr[0];
373         };
374
375         this.trcp = function(msgctx, msgid, msgid_plural, count)
376         {
377                 _luci2.i18n.init();
378
379                 var msgstr = _luci2.i18n.catalog[msgid + '\u0004' + msgctx];
380
381                 if (typeof(msgstr) == 'undefined')
382                         return (count == 1) ? msgid : msgid_plural;
383                 else if (typeof(msgstr) == 'string')
384                         return msgstr;
385                 else
386                         return msgstr[_luci2.i18n.plural(count)];
387         };
388
389         this.setHash = function(key, value)
390         {
391                 var h = '';
392                 var data = this.getHash(undefined);
393
394                 if (typeof(value) == 'undefined')
395                         delete data[key];
396                 else
397                         data[key] = value;
398
399                 var keys = [ ];
400                 for (var k in data)
401                         keys.push(k);
402
403                 keys.sort();
404
405                 for (var i = 0; i < keys.length; i++)
406                 {
407                         if (i > 0)
408                                 h += ',';
409
410                         h += keys[i] + ':' + data[keys[i]];
411                 }
412
413                 if (h)
414                         location.hash = '#' + h;
415         };
416
417         this.getHash = function(key)
418         {
419                 var data = { };
420                 var tuples = (location.hash || '#').substring(1).split(/,/);
421
422                 for (var i = 0; i < tuples.length; i++)
423                 {
424                         var tuple = tuples[i].split(/:/);
425                         if (tuple.length == 2)
426                                 data[tuple[0]] = tuple[1];
427                 }
428
429                 if (typeof(key) != 'undefined')
430                         return data[key];
431
432                 return data;
433         };
434
435         this.globals = {
436                 resource: '/luci2'
437         };
438
439         this.rpc = {
440
441                 _msg_id: 1,
442
443                 _wrap_msg: function(method, object, func, args)
444                 {
445                         if (typeof(args) != 'object')
446                                 args = { };
447
448                         return {
449                                 id:      _luci2.rpc._msg_id++,
450                                 jsonrpc: "2.0",
451                                 method:  method,
452                                 params:  (method == 'call') ? [ _luci2.globals.sid, object, func, args ] : object
453                         };
454                 },
455
456                 _parse_response: function(keys, priv)
457                 {
458                         return function(data) {
459                                 var obj;
460                                 try {
461                                         obj = $.parseJSON(data);
462                                 } catch(e) { }
463
464                                 if (typeof(obj) != 'object')
465                                         return undefined;
466
467                                 /* is a batched response */
468                                 if (keys)
469                                 {
470                                         var rv = { };
471                                         for (var i = 0; i < obj.length; i++)
472                                         {
473                                                 var p = (typeof(priv) != 'undefined') ? priv[i] : undefined;
474
475                                                 if ($.isArray(obj[i].result) && typeof(priv) != 'undefined')
476                                                         obj[i].result[2] = p;
477
478                                                 if (obj[i].jsonrpc != '2.0' || obj[i].error || !obj[i].result)
479                                                         rv[keys[i]] = [ 4 /* UBUS_STATUS_NO_DATA */, undefined, p ];
480                                                 else
481                                                         rv[keys[i]] = obj[i].result;
482                                         }
483                                         return rv;
484                                 }
485
486                                 if (obj.jsonrpc != '2.0' || obj.error || !obj.result)
487                                         return [ 4 /* UBUS_STATUS_NO_DATA */, undefined, priv ];
488
489                                 if ($.isArray(obj.result) && typeof(priv) != 'undefined')
490                                         obj.result[2] = priv;
491
492                                 return obj.result;
493                         };
494                 },
495
496                 _post_msg: function(message, cb, keys, priv)
497                 {
498                         return $.ajax('/ubus', {
499                                 cache:       false,
500                                 contentType: 'application/json',
501                                 data:        JSON.stringify(message),
502                                 dataFilter:  _luci2.rpc._parse_response(keys, priv),
503                                 dataType:    'text',
504                                 success:     cb,
505                                 type:        'POST'
506                         });
507                 },
508
509                 _post_single: function(object, method, args, cb, priv)
510                 {
511                         var msg = _luci2.rpc._wrap_msg('call', object, method, args, priv);
512                         return _luci2.rpc._post_msg(msg, cb, undefined, priv);
513                 },
514
515                 _post_batch: function(methods, cb)
516                 {
517                         if (typeof(methods) != 'object')
518                                 return undefined;
519
520                         var msgs = [ ];
521                         var keys = [ ];
522                         var priv = [ ];
523
524                         for (var k in methods)
525                         {
526                                 if (typeof(methods[k]) != 'object' || methods[k].length < 2)
527                                         continue;
528
529                                 keys.push(k);
530                                 priv.push(methods[k][3]);
531                                 msgs.push(_luci2.rpc._wrap_msg('call', methods[k][0], methods[k][1], methods[k][2]));
532                         }
533
534                         if (msgs.length > 0)
535                                 return _luci2.rpc._post_msg(msgs, cb, keys, priv);
536
537                         return _luci2.deferrable([ ]);
538                 },
539
540                 call: function()
541                 {
542                         var a = arguments;
543                         if (typeof a[0] == 'string')
544                                 return _luci2.rpc._post_single(a[0], a[1], a[2], a[3], a[4]);
545                         else
546                                 return _luci2.rpc._post_batch(a[0], a[1]);
547                 },
548
549                 list: function(objects)
550                 {
551                         var msg = _luci2.rpc._wrap_msg('list', objects);
552                         return _luci2.rpc._post_msg(msg);
553                 },
554
555                 access: function(scope, object, method, cb)
556                 {
557                         return _luci2.rpc._post_single('session', 'access', {
558                                 'sid':      _luci2.globals.sid,
559                                 'scope':        scope,
560                                 'object':   object,
561                                 'function': method
562                         }, function(rv) {
563                                 return retcb(cb, (rv[0] == 0 && rv[1] && rv[1].access == true));
564                         });
565                 }
566         };
567
568         this.uci = {
569
570                 writable: function(cb)
571                 {
572                         return _luci2.rpc.access('ubus', 'uci', 'commit', cb);
573                 },
574
575                 add: function(config, type, cb)
576                 {
577                         return rcall('uci', 'add', { config: config, type: type }, 'section', '', cb);
578                 },
579
580                 apply: function()
581                 {
582
583                 },
584
585                 changes: function(config)
586                 {
587                         return rcall('uci', 'changes', { config: config }, 'changes', [ ], cb);
588                 },
589
590                 commit: function(config)
591                 {
592                         return rcall('uci', 'commit', { config: config }, undefined, undefined, cb);
593                 },
594
595                 'delete': function(config, section, option)
596                 {
597                         var req = { config: config, section: section };
598
599                         if (isa(option, 'Array'))
600                                 req.options = option;
601                         else
602                                 req.option = option;
603
604                         return rcall('uci', 'delete', req, undefined, undefined, cb);
605                 },
606
607                 delete_all: function(config, type, matches)
608                 {
609                         return rcall('uci', 'delete', { config: config, type: type, match: matches }, undefined, undefined, cb);
610                 },
611
612                 foreach: function(config, type, cb)
613                 {
614                         return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
615                                 for (var s in sections)
616                                         cb(sections[s]);
617                         });
618                 },
619
620                 get: function(config, section, option, cb)
621                 {
622                         return rcall('uci', 'get', { config: config, section: section, option: option }, undefined, { }, function(res) {
623                                 if (typeof(option) == 'undefined')
624                                         return retcb(cb, (res.values && res.values['.type']) ? res.values['.type'] : undefined);
625
626                                 return retcb(cb, res.value);
627                         });
628                 },
629
630                 get_all: function(config, section, cb)
631                 {
632                         return rcall('uci', 'get', { config: config, section: section }, 'values', { }, cb);
633                 },
634
635                 get_first: function(config, type, option, cb)
636                 {
637                         return rcall('uci', 'get', { config: config, type: type }, 'values', { }, function(sections) {
638                                 for (var s in sections)
639                                 {
640                                         var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
641
642                                         if (typeof(val) != 'undefined')
643                                                 return retcb(cb, val);
644                                 }
645
646                                 return retcb(cb, undefined);
647                         });
648                 },
649
650                 section: function(config, type, name, values, cb)
651                 {
652                         return rcall('uci', 'add', { config: config, type: type, name: name, values: values }, 'section', undefined, cb);
653                 },
654
655                 set: function(config, section, option, value, cb)
656                 {
657                         if (typeof(value) == 'undefined' && typeof(option) == 'string')
658                                 return rcall('uci', 'add', { config: config, section: section, type: option }, undefined, undefined, cb);
659                         else if (isa(option, 'Object'))
660                                 return rcall('uci', 'set', { config: config, section: section, values: option }, undefined, undefined, cb);
661                         else
662
663                         var values = { };
664                             values[option] = value;
665
666                         return rcall('uci', 'set', { config: config, section: section, values: values }, undefined, undefined, cb);
667                 },
668
669                 order: function(config, sections, cb)
670                 {
671                         return rcall('uci', 'order', { config: config, sections: sections }, undefined, undefined, cb);
672                 }
673         };
674
675         this.network = {
676                 getNetworkStatus: function(cb)
677                 {
678                         var ifaces = [ ];
679                         var assign = function(target, key)
680                         {
681                                 return function(value) {
682                                         if (typeof(value) != 'undefined' && !$.isEmptyObject(value))
683                                                 target[key] = value;
684                                 };
685                         };
686
687                         return _luci2.rpc.list().then(function(data) {
688                                 var requests = [ ];
689
690                                 for (var i = 0; i < data.length; i++)
691                                 {
692                                         if (data[i].indexOf('network.interface.') != 0)
693                                                 continue;
694
695                                         var ifname = data[i].substring(18);
696                                         if (ifname == 'loopback')
697                                                 continue;
698
699                                         var iface = { 'name': ifname };
700
701                                         ifaces.push(iface);
702                                         requests.push(['network.interface', 'status', { 'interface': ifname }, iface]);
703                                 }
704
705                                 return _luci2.rpc.call(requests, function(responses) {
706                                         for (var key in responses)
707                                                 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
708                                                         $.extend(responses[key][2], responses[key][1]);
709                                 });
710                         }).then(function() {
711                                 var requests = [ ];
712
713                                 for (var i = 0; i < ifaces.length; i++)
714                                 {
715                                         var iface = ifaces[i];
716
717                                         var dev = iface.l3_device || iface.l2_device;
718                                         if (!dev)
719                                                 continue;
720
721                                         iface.device = { 'name': dev };
722                                         requests[dev] = ['network.device', 'status', { 'name': dev }, iface.device];
723                                 }
724
725                                 return _luci2.rpc.call(requests, function(responses) {
726                                         for (var key in responses)
727                                                 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
728                                                         $.extend(responses[key][2], responses[key][1]);
729                                 });
730                         }).then(function() {
731                                 var requests = [ ];
732
733                                 for (var i = 0; i < ifaces.length; i++)
734                                 {
735                                         var iface = ifaces[i];
736                                         if (!iface.device)
737                                                 continue;
738
739                                         var subdevs = iface.device['bridge-members'];
740                                         if (!subdevs)
741                                                 continue;
742
743                                         iface.subdevices = [ ];
744                                         for (var j = 0; j < subdevs.length; j++)
745                                         {
746                                                 iface.subdevices[j] = { 'name': subdevs[j] };
747                                                 requests.push(['network.device', 'status', { 'name': subdevs[j] }, iface.subdevices[j]]);
748                                         }
749                                 }
750
751                                 return _luci2.rpc.call(requests, function(responses) {
752                                         for (var key in responses)
753                                                 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
754                                                         $.extend(responses[key][2], responses[key][1]);
755                                 });
756                         }).then(function() {
757                                 var requests = [ ];
758
759                                 for (var i = 0; i < ifaces.length; i++)
760                                 {
761                                         var iface = ifaces[i];
762
763                                         if (iface.device)
764                                                 requests.push(['iwinfo', 'info', { 'device': iface.device.name }, iface.device]);
765
766                                         if (iface.subdevices)
767                                                 for (var j = 0; j < iface.subdevices.length; j++)
768                                                         requests.push(['iwinfo', 'info', { 'device': iface.subdevices[j].name }, iface.subdevices[j]]);
769                                 }
770
771                                 return _luci2.rpc.call(requests, function(responses) {
772                                         for (var key in responses)
773                                                 if (responses[key][0] == 0 && responses[key][1] && responses[key][2])
774                                                         if (!$.isEmptyObject(responses[key][1]))
775                                                                 responses[key][2].wireless = responses[key][1];
776                                 });
777                         }).then(function() {
778                                 ifaces.sort(function(a, b) {
779                                         if (a['interface'] < b['interface'])
780                                                 return -1;
781                                         else if (a['interface'] > b['interface'])
782                                                 return 1;
783                                         else
784                                                 return 0;
785                                 });
786                                 return retcb(cb, ifaces);
787                         });
788                 },
789
790                 findWanInterfaces: function(cb)
791                 {
792                         return _luci2.rpc.list().then(function(data) {
793                                 var requests = { };
794                                 for (var i = 0; i < data.length; i++)
795                                 {
796                                         if (data[i].indexOf('network.interface.') == 0)
797                                         {
798                                                 var ifname = data[i].substring(18);
799                                                 requests[ifname] = ['network.interface', 'status', { 'interface': ifname }];
800                                         }
801                                 }
802                                 return _luci2.rpc.call(requests);
803                         }).then(function(responses) {
804                                 var rv = [ ];
805                                 for (var ifname in responses)
806                                 {
807                                         var response = responses[ifname];
808
809                                         if (response[0] != 0 || !response[1] || !response[1].route)
810                                                 continue;
811
812                                         for (var rn = 0, rt = response[1].route[rn];
813                                                  rn < response[1].route.length;
814                                                  rn++, rt = response[1].route[rn])
815                                         {
816                                                 if (typeof(rt.table) != 'undefined')
817                                                         continue;
818
819                                                 if (rt.target == '0.0.0.0' && rt.mask == 0)
820                                                         rv[0] = response[1];
821                                                 else if (rt.target == '::' && rt.mask == 0)
822                                                         rv[1] = response[1];
823                                         }
824                                 }
825
826                                 return retcb(cb, rv);
827                         });
828                 },
829
830                 getDHCPLeases: function(cb)
831                 {
832                         return rcall('luci2.network', 'dhcp_leases', undefined, 'leases', [ ], cb);
833                 },
834
835                 getDHCPv6Leases: function(cb)
836                 {
837                         return rcall('luci2.network', 'dhcp6_leases', undefined, 'leases', [ ], cb);
838                 },
839
840                 getRoutes: function(cb)
841                 {
842                         return rcall('luci2.network', 'routes', undefined, 'routes', [ ], cb);
843                 },
844
845                 getIPv6Routes: function(cb)
846                 {
847                         return rcall('luci2.network', 'routes6', undefined, 'routes', [ ], cb);
848                 },
849
850                 getARPTable: function(cb)
851                 {
852                         return rcall('luci2.network', 'arp_table', undefined, 'entries', [ ], cb);
853                 },
854
855                 getInterfaceStatus: function(iface, cb)
856                 {
857                         return rcall('network.interface', 'status', { 'interface': iface }, undefined, { }, cb, function(rv) {
858                                 rv['interface'] = iface;
859                                 rv['l2_device'] = rv['device'];
860                                 return rv;
861                         });
862                 },
863
864                 getDeviceStatus: function(dev, cb)
865                 {
866                         return rcall('network.device', 'status', { name: dev }, undefined, { }, cb, function(rv) {
867                                 if (typeof(dev) == 'string')
868                                         rv.device = dev;
869                                 return rv;
870                         });
871                 },
872
873                 getConntrackCount: function(cb)
874                 {
875                         return rcall('luci2.network', 'conntrack_count', undefined, undefined, {
876                                 count: 0,
877                                 limit: 0
878                         }, cb);
879                 }
880         };
881
882         this.wireless = {
883                 getDevices: function(cb) {
884                         return rcall('iwinfo', 'devices', undefined, 'devices', [ ], cb, function(rv) {
885                                 rv.sort();
886                                 return rv;
887                         });
888                 },
889
890                 getInfo: function(dev, cb) {
891                         var parse_info = function(device, info, rv)
892                         {
893                                 if (!rv[info.phy])
894                                         rv[info.phy] = {
895                                                 networks: [ ]
896                                         };
897
898                                 var phy = rv[info.phy];
899
900                                 var phy_attrs = [
901                                         'country', 'channel', 'frequency', 'frequency_offset',
902                                         'txpower', 'txpower_offset', 'hwmodes', 'hardware', 'phy'
903                                 ];
904
905                                 var net_attrs = [
906                                         'ssid', 'bssid', 'mode', 'quality', 'quality_max',
907                                         'signal', 'noise', 'bitrate', 'encryption'
908                                 ];
909
910                                 for (var i = 0; i < phy_attrs.length; i++)
911                                         phy[phy_attrs[i]] = info[phy_attrs[i]];
912
913                                 var net = {
914                                         device: device
915                                 };
916
917                                 for (var i = 0; i < net_attrs.length; i++)
918                                         net[net_attrs[i]] = info[net_attrs[i]];
919
920                                 phy.networks.push(net);
921
922                                 return phy;
923                         };
924
925                         if (!dev)
926                         {
927                                 return _luci2.wireless.getDevices().then(function(devices) {
928                                         var requests = [ ];
929
930                                         for (var i = 0; i < devices.length; i++)
931                                         {
932                                                 if (devices[i].indexOf('.sta') >= 0)
933                                                         continue;
934
935                                                 requests[devices[i]] = [ 'iwinfo', 'info', { device: devices[i] } ];
936                                         }
937
938                                         return _luci2.rpc.call(requests);
939                                 }).then(function(responses) {
940                                         var rv = { };
941
942                                         for (var device in responses)
943                                         {
944                                                 var response = responses[device];
945
946                                                 if (response[0] != 0 || !response[1])
947                                                         continue;
948
949                                                 parse_info(device, response[1], rv);
950                                         }
951
952                                         return retcb(cb, rv);
953                                 });
954                         }
955
956                         return _luci2.rpc.call('iwinfo', 'info', { device: dev }).then(function(response) {
957                                 if (response[0] != 0 || !response[1])
958                                         return retcb(cb, { });
959
960                                 return retcb(cb, parse_info(dev, response[1], { }));
961                         });
962                 },
963
964                 getAssocList: function(dev, cb)
965                 {
966                         if (!dev)
967                         {
968                                 return _luci2.wireless.getDevices().then(function(devices) {
969                                         var requests = { };
970
971                                         for (var i = 0; i < devices.length; i++)
972                                         {
973                                                 if (devices[i].indexOf('.sta') >= 0)
974                                                         continue;
975
976                                                 requests[devices[i]] = [ 'iwinfo', 'assoclist', { device: devices[i] } ];
977                                         }
978
979                                         return _luci2.rpc.call(requests);
980                                 }).then(function(responses) {
981                                         var rv = [ ];
982
983                                         for (var device in responses)
984                                         {
985                                                 var response = responses[device];
986
987                                                 if (response[0] != 0 || !response[1] || !response[1].results)
988                                                         continue;
989
990                                                 for (var i = 0; i < response[1].results.length; i++)
991                                                 {
992                                                         var station = response[1].results[i];
993
994                                                         station.device = device;
995                                                         rv.push(station);
996                                                 }
997                                         }
998
999                                         rv.sort(function(a, b) {
1000                                                 return (a.device == b.device)
1001                                                         ? (a.bssid < b.bssid)
1002                                                         : (a.device > b.device)
1003                                                 ;
1004                                         });
1005
1006                                         return retcb(cb, rv);
1007                                 });
1008                         }
1009
1010                         return _luci2.rpc.call('iwinfo', 'assoclist', { device: dev }).then(function(response) {
1011                                 var rv = [ ];
1012
1013                                 if (response[0] != 0 || !response[1] || !response[1].results)
1014                                         return retcb(cb, rv);
1015
1016                                 for (var i = 0; i < response[1].results.length; i++)
1017                                 {
1018                                         var station = response[1].results[i];
1019
1020                                         station.device = dev;
1021                                         rv.push(station);
1022                                 }
1023
1024                                 rv.sort(function(a, b) {
1025                                         return (a.bssid < b.bssid);
1026                                 });
1027
1028                                 return retcb(cb, rv);
1029                         });
1030                 },
1031
1032                 formatEncryption: function(enc)
1033                 {
1034                         var format_list = function(l, s)
1035                         {
1036                                 var rv = [ ];
1037                                 for (var i = 0; i < l.length; i++)
1038                                         rv.push(l[i].toUpperCase());
1039                                 return rv.join(s ? s : ', ');
1040                         }
1041
1042                         if (!enc || !enc.enabled)
1043                                 return _luci2.tr('None');
1044
1045                         if (enc.wep)
1046                         {
1047                                 if (enc.wep.length == 2)
1048                                         return _luci2.tr('WEP Open/Shared') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1049                                 else if (enc.wep[0] == 'shared')
1050                                         return _luci2.tr('WEP Shared Auth') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1051                                 else
1052                                         return _luci2.tr('WEP Open System') + ' (%s)'.format(format_list(enc.ciphers, ', '));
1053                         }
1054                         else if (enc.wpa)
1055                         {
1056                                 if (enc.wpa.length == 2)
1057                                         return _luci2.tr('mixed WPA/WPA2') + ' %s (%s)'.format(
1058                                                 format_list(enc.authentication, '/'),
1059                                                 format_list(enc.ciphers, ', ')
1060                                         );
1061                                 else if (enc.wpa[0] == 2)
1062                                         return 'WPA2 %s (%s)'.format(
1063                                                 format_list(enc.authentication, '/'),
1064                                                 format_list(enc.ciphers, ', ')
1065                                         );
1066                                 else
1067                                         return 'WPA %s (%s)'.format(
1068                                                 format_list(enc.authentication, '/'),
1069                                                 format_list(enc.ciphers, ', ')
1070                                         );
1071                         }
1072
1073                         return _luci2.tr('Unknown');
1074                 }
1075         };
1076
1077         this.system = {
1078                 getInfo: function(cb)
1079                 {
1080                         return _luci2.rpc.call({
1081                                 info:  [ 'system', 'info',  { } ],
1082                                 board: [ 'system', 'board', { } ],
1083                                 disk:  [ 'luci2.system', 'diskfree', { } ]
1084                         }).then(function(responses) {
1085                                 var rv = { };
1086
1087                                 if (responses.info[0] == 0)
1088                                         $.extend(rv, responses.info[1]);
1089
1090                                 if (responses.board[0] == 0)
1091                                         $.extend(rv, responses.board[1]);
1092
1093                                 if (responses.disk[0] == 0)
1094                                         $.extend(rv, responses.disk[1]);
1095
1096                                 return retcb(cb, rv);
1097                         });
1098                 },
1099
1100                 getProcessList: function(cb)
1101                 {
1102                         return rcall('luci2.system', 'process_list', undefined, 'processes', [ ], cb, function(rv) {
1103                                 rv.sort(function(a, b) { return a.pid - b.pid });
1104                                 return rv;
1105                         });
1106                 },
1107
1108                 getSystemLog: function(cb)
1109                 {
1110                         return rcall('luci2.system', 'syslog', undefined, 'log', '', cb);
1111                 },
1112
1113                 getKernelLog: function(cb)
1114                 {
1115                         return rcall('luci2.system', 'dmesg', undefined, 'log', '', cb);
1116                 },
1117
1118                 getZoneInfo: function(cb)
1119                 {
1120                         return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
1121                 },
1122
1123                 canSendSignal: function(cb)
1124                 {
1125                         return _luci2.rpc.access('ubus', 'luci2.system', 'process_signal', cb);
1126                 },
1127
1128                 sendSignal: function(pid, sig, cb)
1129                 {
1130                         return _luci2.rpc.call('luci2.system', 'process_signal', { pid: pid, signal: sig }).then(function(response) {
1131                                 return retcb(cb, response[0] == 0);
1132                         });
1133                 },
1134
1135                 initList: function(cb)
1136                 {
1137                         return rcall('luci2.system', 'init_list', undefined, 'initscripts', [ ], cb, function(rv) {
1138                                 rv.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
1139                                 return rv;
1140                         });
1141                 },
1142
1143                 initEnabled: function(init, cb)
1144                 {
1145                         return this.initList(function(list) {
1146                                 for (var i = 0; i < list.length; i++)
1147                                         if (list[i].name == init)
1148                                                 return retcb(cb, !!list[i].enabled);
1149
1150                                 return retcb(cb, false);
1151                         });
1152                 },
1153
1154                 initRun: function(init, action, cb)
1155                 {
1156                         return _luci2.rpc.call('luci2.system', 'init_action', { name: init, action: action }).then(function(response) {
1157                                 return retcb(cb, response[0] == 0);
1158                         });
1159                 },
1160
1161                 canInitRun: function(cb)
1162                 {
1163                         return _luci2.rpc.access('ubus', 'luci2.system', 'init_action', cb);
1164                 },
1165
1166                 initStart:   function(init, cb) { return _luci2.system.initRun(init, 'start',   cb) },
1167                 initStop:    function(init, cb) { return _luci2.system.initRun(init, 'stop',    cb) },
1168                 initRestart: function(init, cb) { return _luci2.system.initRun(init, 'restart', cb) },
1169                 initReload:  function(init, cb) { return _luci2.system.initRun(init, 'reload',  cb) },
1170                 initEnable:  function(init, cb) { return _luci2.system.initRun(init, 'enable',  cb) },
1171                 initDisable: function(init, cb) { return _luci2.system.initRun(init, 'disable', cb) },
1172
1173
1174                 getRcLocal: function(cb)
1175                 {
1176                         return rcall('luci2.system', 'rclocal_get', undefined, 'data', '', cb);
1177                 },
1178
1179                 setRcLocal: function(data, cb)
1180                 {
1181                         return rcall('luci2.system', 'rclocal_set', { data: data }, undefined, undefined, cb);
1182                 },
1183
1184                 canSetRcLocal: function(cb)
1185                 {
1186                         return _luci2.rpc.access('ubus', 'luci2.system', 'rclocal_set', cb);
1187                 },
1188
1189
1190                 getCrontab: function(cb)
1191                 {
1192                         return rcall('luci2.system', 'crontab_get', undefined, 'data', '', cb);
1193                 },
1194
1195                 setCrontab: function(data, cb)
1196                 {
1197                         return rcall('luci2.system', 'crontab_set', { data: data }, undefined, undefined, cb);
1198                 },
1199
1200                 canSetCrontab: function(cb)
1201                 {
1202                         return _luci2.rpc.access('ubus', 'luci2.system', 'crontab_set', cb);
1203                 },
1204
1205
1206                 getSSHKeys: function(cb)
1207                 {
1208                         return rcall('luci2.system', 'sshkeys_get', undefined, 'keys', [ ], cb);
1209                 },
1210
1211                 setSSHKeys: function(keys, cb)
1212                 {
1213                         return rcall('luci2.system', 'sshkeys_set', { keys: keys }, undefined, undefined, cb);
1214                 },
1215
1216                 canSetSSHKeys: function(cb)
1217                 {
1218                         return _luci2.rpc.access('ubus', 'luci2.system', 'sshkeys_set', cb);
1219                 },
1220
1221
1222                 setPassword: function(user, pass, cb)
1223                 {
1224                         return rcall('luci2.system', 'password_set', { user: user, password: pass }, undefined, undefined, cb);
1225                 },
1226
1227                 canSetPassword: function(cb)
1228                 {
1229                         return _luci2.rpc.access('ubus', 'luci2.system', 'password_set', cb);
1230                 },
1231
1232
1233                 listLEDs: function(cb)
1234                 {
1235                         return rcall('luci2.system', 'led_list', undefined, 'leds', [ ], cb);
1236                 },
1237
1238                 listUSBDevices: function(cb)
1239                 {
1240                         return rcall('luci2.system', 'usb_list', undefined, 'devices', [ ], cb);
1241                 },
1242
1243
1244                 testUpgrade: function(cb)
1245                 {
1246                         return rcall('luci2.system', 'upgrade_test', undefined, undefined, { }, cb);
1247                 },
1248
1249                 startUpgrade: function(keep, cb)
1250                 {
1251                         return rcall('luci2.system', 'upgrade_start', { keep: !!keep }, undefined, undefined, cb);
1252                 },
1253
1254                 cleanUpgrade: function(cb)
1255                 {
1256                         return rcall('luci2.system', 'upgrade_clean', undefined, undefined, undefined, cb);
1257                 },
1258
1259                 canUpgrade: function(cb)
1260                 {
1261                         return _luci2.rpc.access('ubus', 'luci2.system', 'upgrade_start', cb);
1262                 },
1263
1264
1265                 restoreBackup: function(cb)
1266                 {
1267                         return rcall('luci2.system', 'backup_restore', undefined, undefined, undefined, cb);
1268                 },
1269
1270                 cleanBackup: function(cb)
1271                 {
1272                         return rcall('luci2.system', 'backup_clean', undefined, undefined, undefined, cb);
1273                 },
1274
1275                 canRestoreBackup: function(cb)
1276                 {
1277                         return _luci2.rpc.access('ubus', 'luci2.system', 'backup_restore', cb);
1278                 },
1279
1280
1281                 getBackupConfig: function(cb)
1282                 {
1283                         return rcall('luci2.system', 'backup_config_get', undefined, 'config', '', cb);
1284                 },
1285
1286                 setBackupConfig: function(data, cb)
1287                 {
1288                         return rcall('luci2.system', 'backup_config_set', { data: data }, undefined, undefined, cb);
1289                 },
1290
1291                 canSetBackupConfig: function(cb)
1292                 {
1293                         return _luci2.rpc.access('ubus', 'luci2.system', 'backup_config_set', cb);
1294                 },
1295
1296
1297                 listBackup: function(cb)
1298                 {
1299                         return rcall('luci2.system', 'backup_list', undefined, 'files', [ ], cb);
1300                 },
1301
1302
1303                 performReboot: function(cb)
1304                 {
1305                         return rcall('luci2.system', 'reboot', undefined, undefined, undefined, cb);
1306                 },
1307
1308                 canPerformReboot: function(cb)
1309                 {
1310                         return _luci2.rpc.access('ubus', 'luci2.system', 'reboot', cb);
1311                 }
1312         };
1313
1314         this.opkg = {
1315                 updateLists: function(cb)
1316                 {
1317                         return rcall('luci2.opkg', 'update', undefined, undefined, { }, cb);
1318                 },
1319
1320                 _fetchPackages: function(action, offset, limit, pattern, cb)
1321                 {
1322                         var packages = [ ];
1323                         var reqlimit = Math.min(limit, 100);
1324
1325                         if (reqlimit <= 0)
1326                                 reqlimit = 100;
1327
1328                         return _luci2.rpc.call('luci2.opkg', action, { offset: offset, limit: reqlimit, pattern: pattern }).then(function(response) {
1329                                 if (response[0] != 0 || !response[1] || !response[1].total)
1330                                         return retcb(cb, { length: 0, total: 0 });
1331
1332                                 packages.push.apply(packages, response[1].packages);
1333                                 packages.total = response[1].total;
1334
1335                                 if (limit <= 0)
1336                                         limit = response[1].total;
1337
1338                                 if (packages.length >= limit)
1339                                         return retcb(cb, packages);
1340
1341                                 var requests = [ ];
1342                                 for (var i = offset + packages.length; i < limit; i += 100)
1343                                         requests.push(['luci2.opkg', action, { offset: i, limit: (Math.min(i + 100, limit) % 100) || 100, pattern: pattern }]);
1344
1345                                 return _luci2.rpc.call(requests);
1346                         }).then(function(responses) {
1347                                 for (var key in responses)
1348                                 {
1349                                         var response = responses[key];
1350
1351                                         if (response[0] != 0 || !response[1] || !response[1].packages)
1352                                                 continue;
1353
1354                                         packages.push.apply(packages, response[1].packages);
1355                                         packages.total = response[1].total;
1356                                 }
1357
1358                                 return retcb(cb, packages);
1359                         });
1360                 },
1361
1362                 listPackages: function(offset, limit, pattern, cb)
1363                 {
1364                         return _luci2.opkg._fetchPackages('list', offset, limit, pattern, cb);
1365                 },
1366
1367                 installedPackages: function(offset, limit, pattern, cb)
1368                 {
1369                         return _luci2.opkg._fetchPackages('list_installed', offset, limit, pattern, cb);
1370                 },
1371
1372                 findPackages: function(offset, limit, pattern, cb)
1373                 {
1374                         return _luci2.opkg._fetchPackages('find', offset, limit, pattern, cb);
1375                 },
1376
1377                 installPackage: function(name, cb)
1378                 {
1379                         return rcall('luci2.opkg', 'install', { 'package': name }, undefined, { }, cb);
1380                 },
1381
1382                 removePackage: function(name, cb)
1383                 {
1384                         return rcall('luci2.opkg', 'remove', { 'package': name }, undefined, { }, cb);
1385                 },
1386
1387                 getConfig: function(cb)
1388                 {
1389                         return rcall('luci2.opkg', 'config_get', undefined, 'config', '', cb);
1390                 },
1391
1392                 setConfig: function(data, cb)
1393                 {
1394                         return rcall('luci2.opkg', 'config_set', { data: data }, undefined, undefined, cb);
1395                 },
1396
1397                 canInstallPackage: function(cb)
1398                 {
1399                         return _luci2.rpc.access('ubus', 'luci2.opkg', 'install', cb);
1400                 },
1401
1402                 canRemovePackage: function(cb)
1403                 {
1404                         return _luci2.rpc.access('ubus', 'luci2.opkg', 'remove', cb);
1405                 },
1406
1407                 canSetConfig: function(cb)
1408                 {
1409                         return _luci2.rpc.access('ubus', 'luci2.opkg', 'config_set', cb);
1410                 }
1411         };
1412
1413         this.ui = {
1414
1415                 loading: function(enable)
1416                 {
1417                         var win = $(window);
1418                         var body = $('body');
1419                         var div = _luci2._modal || (
1420                                 _luci2._modal = $('<div />')
1421                                         .addClass('cbi-modal-loader')
1422                                         .append($('<div />').text(_luci2.tr('Loading data...')))
1423                                         .appendTo(body)
1424                         );
1425
1426                         if (enable)
1427                         {
1428                                 body.css('overflow', 'hidden');
1429                                 body.css('padding', 0);
1430                                 body.css('width', win.width());
1431                                 body.css('height', win.height());
1432                                 div.css('width', win.width());
1433                                 div.css('height', win.height());
1434                                 div.show();
1435                         }
1436                         else
1437                         {
1438                                 div.hide();
1439                                 body.css('overflow', '');
1440                                 body.css('padding', '');
1441                                 body.css('width', '');
1442                                 body.css('height', '');
1443                         }
1444                 },
1445
1446                 dialog: function(title, content, options)
1447                 {
1448                         var win = $(window);
1449                         var body = $('body');
1450                         var div = _luci2._dialog || (
1451                                 _luci2._dialog = $('<div />')
1452                                         .addClass('cbi-modal-dialog')
1453                                         .append($('<div />')
1454                                                 .append($('<div />')
1455                                                         .addClass('cbi-modal-dialog-header'))
1456                                                 .append($('<div />')
1457                                                         .addClass('cbi-modal-dialog-body'))
1458                                                 .append($('<div />')
1459                                                         .addClass('cbi-modal-dialog-footer')
1460                                                         .append($('<button />')
1461                                                                 .addClass('cbi-button')
1462                                                                 .text(_luci2.tr('Close'))
1463                                                                 .click(function() {
1464                                                                         $('body')
1465                                                                                 .css('overflow', '')
1466                                                                                 .css('padding', '')
1467                                                                                 .css('width', '')
1468                                                                                 .css('height', '');
1469
1470                                                                         $(this).parent().parent().parent().hide();
1471                                                                 }))))
1472                                         .appendTo(body)
1473                         );
1474
1475                         if (typeof(options) != 'object')
1476                                 options = { };
1477
1478                         if (title === false)
1479                         {
1480                                 body
1481                                         .css('overflow', '')
1482                                         .css('padding', '')
1483                                         .css('width', '')
1484                                         .css('height', '');
1485
1486                                 _luci2._dialog.hide();
1487
1488                                 return;
1489                         }
1490
1491                         var cnt = div.children().children('div.cbi-modal-dialog-body');
1492                         var ftr = div.children().children('div.cbi-modal-dialog-footer');
1493
1494                         ftr.empty();
1495
1496                         if (options.style == 'confirm')
1497                         {
1498                                 ftr.append($('<button />')
1499                                         .addClass('cbi-button')
1500                                         .text(_luci2.tr('Ok'))
1501                                         .click(options.confirm || function() { _luci2.ui.dialog(false) }));
1502
1503                                 ftr.append($('<button />')
1504                                         .addClass('cbi-button')
1505                                         .text(_luci2.tr('Cancel'))
1506                                         .click(options.cancel || function() { _luci2.ui.dialog(false) }));
1507                         }
1508                         else if (options.style == 'close')
1509                         {
1510                                 ftr.append($('<button />')
1511                                         .addClass('cbi-button')
1512                                         .text(_luci2.tr('Close'))
1513                                         .click(options.close || function() { _luci2.ui.dialog(false) }));
1514                         }
1515                         else if (options.style == 'wait')
1516                         {
1517                                 ftr.append($('<button />')
1518                                         .addClass('cbi-button')
1519                                         .text(_luci2.tr('Close'))
1520                                         .attr('disabled', true));
1521                         }
1522
1523                         div.find('div.cbi-modal-dialog-header').text(title);
1524                         div.show();
1525
1526                         cnt
1527                                 .css('max-height', Math.floor(win.height() * 0.70) + 'px')
1528                                 .empty()
1529                                 .append(content);
1530
1531                         div.children()
1532                                 .css('margin-top', -Math.floor(div.children().height() / 2) + 'px');
1533
1534                         body.css('overflow', 'hidden');
1535                         body.css('padding', 0);
1536                         body.css('width', win.width());
1537                         body.css('height', win.height());
1538                         div.css('width', win.width());
1539                         div.css('height', win.height());
1540                 },
1541
1542                 upload: function(title, content, options)
1543                 {
1544                         var form = _luci2._upload || (
1545                                 _luci2._upload = $('<form />')
1546                                         .attr('method', 'post')
1547                                         .attr('action', '/cgi-bin/luci-upload')
1548                                         .attr('enctype', 'multipart/form-data')
1549                                         .attr('target', 'cbi-fileupload-frame')
1550                                         .append($('<p />'))
1551                                         .append($('<input />')
1552                                                 .attr('type', 'hidden')
1553                                                 .attr('name', 'sessionid')
1554                                                 .attr('value', _luci2.globals.sid))
1555                                         .append($('<input />')
1556                                                 .attr('type', 'hidden')
1557                                                 .attr('name', 'filename')
1558                                                 .attr('value', options.filename))
1559                                         .append($('<input />')
1560                                                 .attr('type', 'file')
1561                                                 .attr('name', 'filedata')
1562                                                 .addClass('cbi-input-file'))
1563                                         .append($('<div />')
1564                                                 .css('width', '100%')
1565                                                 .addClass('progressbar')
1566                                                 .addClass('intermediate')
1567                                                 .append($('<div />')
1568                                                         .css('width', '100%')))
1569                                         .append($('<iframe />')
1570                                                 .attr('name', 'cbi-fileupload-frame')
1571                                                 .css('width', '1px')
1572                                                 .css('height', '1px')
1573                                                 .css('visibility', 'hidden'))
1574                         );
1575
1576                         var finish = _luci2._upload_finish_cb || (
1577                                 _luci2._upload_finish_cb = function(ev) {
1578                                         $(this).off('load');
1579
1580                                         var body = (this.contentDocument || this.contentWindow.document).body;
1581                                         if (body.firstChild.tagName.toLowerCase() == 'pre')
1582                                                 body = body.firstChild;
1583
1584                                         var json;
1585                                         try {
1586                                                 json = $.parseJSON(body.innerHTML);
1587                                         } catch(e) {
1588                                                 json = {
1589                                                         message: _luci2.tr('Invalid server response received'),
1590                                                         error: [ -1, _luci2.tr('Invalid data') ]
1591                                                 };
1592                                         };
1593
1594                                         if (json.error)
1595                                         {
1596                                                 L.ui.dialog(L.tr('File upload'), [
1597                                                         $('<p />').text(_luci2.tr('The file upload failed with the server response below:')),
1598                                                         $('<pre />').addClass('alert-message').text(json.message || json.error[1]),
1599                                                         $('<p />').text(_luci2.tr('In case of network problems try uploading the file again.'))
1600                                                 ], { style: 'close' });
1601                                         }
1602                                         else if (typeof(ev.data.cb) == 'function')
1603                                         {
1604                                                 ev.data.cb(json);
1605                                         }
1606                                 }
1607                         );
1608
1609                         var confirm = _luci2._upload_confirm_cb || (
1610                                 _luci2._upload_confirm_cb = function() {
1611                                         var d = _luci2._upload;
1612                                         var f = d.find('.cbi-input-file');
1613                                         var b = d.find('.progressbar');
1614                                         var p = d.find('p');
1615
1616                                         if (!f.val())
1617                                                 return;
1618
1619                                         d.find('iframe').on('load', { cb: options.success }, finish);
1620                                         d.submit();
1621
1622                                         f.hide();
1623                                         b.show();
1624                                         p.text(_luci2.tr('File upload in progress â€¦'));
1625
1626                                         _luci2._dialog.find('button').prop('disabled', true);
1627                                 }
1628                         );
1629
1630                         _luci2._upload.find('.progressbar').hide();
1631                         _luci2._upload.find('.cbi-input-file').val('').show();
1632                         _luci2._upload.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
1633
1634                         _luci2.ui.dialog(title || _luci2.tr('File upload'), _luci2._upload, {
1635                                 style: 'confirm',
1636                                 confirm: confirm
1637                         });
1638                 },
1639
1640                 reconnect: function()
1641                 {
1642                         var protocols = (location.protocol == 'https:') ? [ 'http', 'https' ] : [ 'http' ];
1643                         var ports     = (location.protocol == 'https:') ? [ 80, location.port || 443 ] : [ location.port || 80 ];
1644                         var address   = location.hostname.match(/^[A-Fa-f0-9]*:[A-Fa-f0-9:]+$/) ? '[' + location.hostname + ']' : location.hostname;
1645                         var images    = $();
1646                         var interval, timeout;
1647
1648                         _luci2.ui.dialog(
1649                                 _luci2.tr('Waiting for device'), [
1650                                         $('<p />').text(_luci2.tr('Please stand by while the device is reconfiguring â€¦')),
1651                                         $('<div />')
1652                                                 .css('width', '100%')
1653                                                 .addClass('progressbar')
1654                                                 .addClass('intermediate')
1655                                                 .append($('<div />')
1656                                                         .css('width', '100%'))
1657                                 ], { style: 'wait' }
1658                         );
1659
1660                         for (var i = 0; i < protocols.length; i++)
1661                                 images = images.add($('<img />').attr('url', protocols[i] + '://' + address + ':' + ports[i]));
1662
1663                         //_luci2.network.getNetworkStatus(function(s) {
1664                         //      for (var i = 0; i < protocols.length; i++)
1665                         //      {
1666                         //              for (var j = 0; j < s.length; j++)
1667                         //              {
1668                         //                      for (var k = 0; k < s[j]['ipv4-address'].length; k++)
1669                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://' + s[j]['ipv4-address'][k].address + ':' + ports[i]));
1670                         //
1671                         //                      for (var l = 0; l < s[j]['ipv6-address'].length; l++)
1672                         //                              images = images.add($('<img />').attr('url', protocols[i] + '://[' + s[j]['ipv6-address'][l].address + ']:' + ports[i]));
1673                         //              }
1674                         //      }
1675                         //}).then(function() {
1676                                 images.on('load', function() {
1677                                         var url = this.getAttribute('url');
1678                                         _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1679                                                 if (response[0] == 0)
1680                                                 {
1681                                                         window.clearTimeout(timeout);
1682                                                         window.clearInterval(interval);
1683                                                         _luci2.ui.dialog(false);
1684                                                         images = null;
1685                                                 }
1686                                                 else
1687                                                 {
1688                                                         location.href = url;
1689                                                 }
1690                                         });
1691                                 });
1692
1693                                 interval = window.setInterval(function() {
1694                                         images.each(function() {
1695                                                 this.setAttribute('src', this.getAttribute('url') + _luci2.globals.resource + '/icons/loading.gif?r=' + Math.random());
1696                                         });
1697                                 }, 5000);
1698
1699                                 timeout = window.setTimeout(function() {
1700                                         window.clearInterval(interval);
1701                                         images.off('load');
1702
1703                                         _luci2.ui.dialog(
1704                                                 _luci2.tr('Device not responding'),
1705                                                 _luci2.tr('The device was not responding within 180 seconds, you might need to manually reconnect your computer or use SSH to regain access.'),
1706                                                 { style: 'close' }
1707                                         );
1708                                 }, 180000);
1709                         //});
1710                 },
1711
1712                 login: function(invalid)
1713                 {
1714                         if (!_luci2._login_deferred || _luci2._login_deferred.state() != 'pending')
1715                                 _luci2._login_deferred = $.Deferred();
1716
1717                         /* try to find sid from hash */
1718                         var sid = _luci2.getHash('id');
1719                         if (sid && sid.match(/^[a-f0-9]{32}$/))
1720                         {
1721                                 _luci2.globals.sid = sid;
1722                                 _luci2.rpc.access('ubus', 'session', 'access').then(function(response) {
1723                                         if (response[0] == 0)
1724                                         {
1725                                                 _luci2._login_deferred.resolve();
1726                                         }
1727                                         else
1728                                         {
1729                                                 _luci2.setHash('id', undefined);
1730                                                 _luci2.ui.login();
1731                                         }
1732                                 });
1733
1734                                 return _luci2._login_deferred;
1735                         }
1736
1737                         var form = _luci2._login || (
1738                                 _luci2._login = $('<div />')
1739                                         .append($('<p />')
1740                                                 .addClass('alert-message')
1741                                                 .text(_luci2.tr('Wrong username or password given!')))
1742                                         .append($('<p />')
1743                                                 .append($('<label />')
1744                                                         .text(_luci2.tr('Username'))
1745                                                         .append($('<br />'))
1746                                                         .append($('<input />')
1747                                                                 .attr('type', 'text')
1748                                                                 .attr('name', 'username')
1749                                                                 .attr('value', 'root')
1750                                                                 .addClass('cbi-input-text'))))
1751                                         .append($('<p />')
1752                                                 .append($('<label />')
1753                                                         .text(_luci2.tr('Password'))
1754                                                         .append($('<br />'))
1755                                                         .append($('<input />')
1756                                                                 .attr('type', 'password')
1757                                                                 .attr('name', 'password')
1758                                                                 .addClass('cbi-input-password'))))
1759                                         .append($('<p />')
1760                                                 .text(_luci2.tr('Enter your username and password above, then click "%s" to proceed.').format(_luci2.tr('Ok'))))
1761                         );
1762
1763                         var response = _luci2._login_response_cb || (
1764                                 _luci2._login_response_cb = function(data) {
1765                                         if (typeof(data) == 'object' && typeof(data.sessionid) == 'string')
1766                                         {
1767                                                 _luci2.globals.sid = data.sessionid;
1768                                                 _luci2.setHash('id', _luci2.globals.sid);
1769
1770                                                 _luci2.ui.dialog(false);
1771                                                 _luci2._login_deferred.resolve();
1772                                         }
1773                                         else
1774                                         {
1775                                                 _luci2.ui.login(true);
1776                                         }
1777                                 }
1778                         );
1779
1780                         var confirm = _luci2._login_confirm_cb || (
1781                                 _luci2._login_confirm_cb = function() {
1782                                         var d = _luci2._login;
1783                                         var u = d.find('[name=username]').val();
1784                                         var p = d.find('[name=password]').val();
1785
1786                                         if (!u)
1787                                                 return;
1788
1789                                         _luci2.ui.dialog(
1790                                                 _luci2.tr('Logging in'), [
1791                                                         $('<p />').text(_luci2.tr('Log in in progress â€¦')),
1792                                                         $('<div />')
1793                                                                 .css('width', '100%')
1794                                                                 .addClass('progressbar')
1795                                                                 .addClass('intermediate')
1796                                                                 .append($('<div />')
1797                                                                         .css('width', '100%'))
1798                                                 ], { style: 'wait' }
1799                                         );
1800
1801                                         $.ajax('/cgi-bin/luci-login', {
1802                                                 type:        'POST',
1803                                                 cache:       false,
1804                                                 data:        { username: u, password: p },
1805                                                 dataType:    'json',
1806                                                 success:     response,
1807                                                 error:       response
1808                                         });
1809                                 }
1810                         );
1811
1812                         if (invalid)
1813                                 form.find('.alert-message').show();
1814                         else
1815                                 form.find('.alert-message').hide();
1816
1817                         _luci2.ui.dialog(_luci2.tr('Authorization Required'), form, {
1818                                 style: 'confirm',
1819                                 confirm: confirm
1820                         });
1821
1822                         return _luci2._login_deferred;
1823                 },
1824
1825                 renderMainMenu: function()
1826                 {
1827                         return rcall('luci2.ui', 'menu', undefined, 'menu', { }, function(entries) {
1828                                 _luci2.globals.mainMenu = new _luci2.ui.menu();
1829                                 _luci2.globals.mainMenu.entries(entries);
1830
1831                                 $('#mainmenu')
1832                                         .empty()
1833                                         .append(_luci2.globals.mainMenu.render(0, 1));
1834                         });
1835                 },
1836
1837                 renderViewMenu: function()
1838                 {
1839                         $('#viewmenu')
1840                                 .empty()
1841                                 .append(_luci2.globals.mainMenu.render(2, 900));
1842                 },
1843
1844                 renderView: function(node)
1845                 {
1846                         var name = node.view.split(/\//).join('.');
1847
1848                         _luci2.ui.renderViewMenu();
1849
1850                         if (!_luci2._views)
1851                                 _luci2._views = { };
1852
1853                         _luci2.setHash('view', node.view);
1854
1855                         if (_luci2._views[name] instanceof _luci2.ui.view)
1856                                 return _luci2._views[name].render();
1857
1858                         return $.ajax(_luci2.globals.resource + '/view/' + name + '.js', {
1859                                 method: 'GET',
1860                                 cache: true,
1861                                 dataType: 'text'
1862                         }).then(function(data) {
1863                                 try {
1864                                         var viewConstructor = (new Function(['L', '$'], 'return ' + data))(_luci2, $);
1865
1866                                         _luci2._views[name] = new viewConstructor({
1867                                                 name: name,
1868                                                 acls: node.write || { }
1869                                         });
1870
1871                                         return _luci2._views[name].render();
1872                                 }
1873                                 catch(e) { };
1874
1875                                 return $.Deferred().resolve();
1876                         });
1877                 },
1878
1879                 init: function()
1880                 {
1881                         _luci2.ui.loading(true);
1882
1883                         $.when(
1884                                 _luci2.ui.renderMainMenu()
1885                         ).then(function() {
1886                                 _luci2.ui.renderView(_luci2.globals.defaultNode).then(function() {
1887                                         _luci2.ui.loading(false);
1888                                 })
1889                         });
1890                 }
1891         };
1892
1893         var AbstractWidget = Class.extend({
1894                 i18n: function(text) {
1895                         return text;
1896                 },
1897
1898                 toString: function() {
1899                         var x = document.createElement('div');
1900                                 x.appendChild(this.render());
1901
1902                         return x.innerHTML;
1903                 },
1904
1905                 insertInto: function(id) {
1906                         return $(id).empty().append(this.render());
1907                 }
1908         });
1909
1910         this.ui.view = AbstractWidget.extend({
1911                 _fetch_template: function()
1912                 {
1913                         return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
1914                                 method: 'GET',
1915                                 cache: true,
1916                                 dataType: 'text',
1917                                 success: function(data) {
1918                                         data = data.replace(/<%([#:=])?(.+?)%>/g, function(match, p1, p2) {
1919                                                 p2 = p2.replace(/^\s+/, '').replace(/\s+$/, '');
1920                                                 switch (p1)
1921                                                 {
1922                                                 case '#':
1923                                                         return '';
1924
1925                                                 case ':':
1926                                                         return _luci2.tr(p2);
1927
1928                                                 case '=':
1929                                                         return _luci2.globals[p2] || '';
1930
1931                                                 default:
1932                                                         return '(?' + match + ')';
1933                                                 }
1934                                         });
1935
1936                                         $('#maincontent').append(data);
1937                                 }
1938                         });
1939                 },
1940
1941                 execute: function()
1942                 {
1943                         throw "Not implemented";
1944                 },
1945
1946                 render: function()
1947                 {
1948                         var container = $('#maincontent');
1949
1950                         container.empty();
1951
1952                         if (this.title)
1953                                 container.append($('<h2 />').append(this.title));
1954
1955                         if (this.description)
1956                                 container.append($('<div />').addClass('cbi-map-descr').append(this.description));
1957
1958                         var self = this;
1959                         return this._fetch_template().then(function() {
1960                                 return _luci2.deferrable(self.execute());
1961                         });
1962                 }
1963         });
1964
1965         this.ui.menu = AbstractWidget.extend({
1966                 init: function() {
1967                         this._nodes = { };
1968                 },
1969
1970                 entries: function(entries)
1971                 {
1972                         for (var entry in entries)
1973                         {
1974                                 var path = entry.split(/\//);
1975                                 var node = this._nodes;
1976
1977                                 for (i = 0; i < path.length; i++)
1978                                 {
1979                                         if (!node.childs)
1980                                                 node.childs = { };
1981
1982                                         if (!node.childs[path[i]])
1983                                                 node.childs[path[i]] = { };
1984
1985                                         node = node.childs[path[i]];
1986                                 }
1987
1988                                 $.extend(node, entries[entry]);
1989                         }
1990                 },
1991
1992                 _indexcmp: function(a, b)
1993                 {
1994                         var x = a.index || 0;
1995                         var y = b.index || 0;
1996                         return (x - y);
1997                 },
1998
1999                 firstChildView: function(node)
2000                 {
2001                         if (node.view)
2002                                 return node;
2003
2004                         var nodes = [ ];
2005                         for (var child in (node.childs || { }))
2006                                 nodes.push(node.childs[child]);
2007
2008                         nodes.sort(this._indexcmp);
2009
2010                         for (var i = 0; i < nodes.length; i++)
2011                         {
2012                                 var child = this.firstChildView(nodes[i]);
2013                                 if (child)
2014                                 {
2015                                         $.extend(node, child);
2016                                         return node;
2017                                 }
2018                         }
2019
2020                         return undefined;
2021                 },
2022
2023                 _onclick: function(ev)
2024                 {
2025                         _luci2.ui.loading(true);
2026                         _luci2.ui.renderView(ev.data).then(function() {
2027                                 _luci2.ui.loading(false);
2028                         });
2029
2030                         ev.preventDefault();
2031                         this.blur();
2032                 },
2033
2034                 _render: function(childs, level, min, max)
2035                 {
2036                         var nodes = [ ];
2037                         for (var node in childs)
2038                         {
2039                                 var child = this.firstChildView(childs[node]);
2040                                 if (child)
2041                                         nodes.push(childs[node]);
2042                         }
2043
2044                         nodes.sort(this._indexcmp);
2045
2046                         var list = $('<ul />');
2047
2048                         if (level == 0)
2049                                 list.addClass('nav');
2050                         else if (level == 1)
2051                                 list.addClass('dropdown-menu');
2052
2053                         for (var i = 0; i < nodes.length; i++)
2054                         {
2055                                 if (!_luci2.globals.defaultNode)
2056                                 {
2057                                         var v = _luci2.getHash('view');
2058                                         if (!v || v == nodes[i].view)
2059                                                 _luci2.globals.defaultNode = nodes[i];
2060                                 }
2061
2062                                 var item = $('<li />')
2063                                         .append($('<a />')
2064                                                 .attr('href', '#')
2065                                                 .text(_luci2.tr(nodes[i].title))
2066                                                 .click(nodes[i], this._onclick))
2067                                         .appendTo(list);
2068
2069                                 if (nodes[i].childs && level < max)
2070                                 {
2071                                         item.addClass('dropdown');
2072                                         item.find('a').addClass('menu');
2073                                         item.append(this._render(nodes[i].childs, level + 1));
2074                                 }
2075                         }
2076
2077                         return list.get(0);
2078                 },
2079
2080                 render: function(min, max)
2081                 {
2082                         var top = min ? this.getNode(_luci2.globals.defaultNode.view, min) : this._nodes;
2083                         return this._render(top.childs, 0, min, max);
2084                 },
2085
2086                 getNode: function(path, max)
2087                 {
2088                         var p = path.split(/\//);
2089                         var n = this._nodes;
2090
2091                         if (typeof(max) == 'undefined')
2092                                 max = p.length;
2093
2094                         for (var i = 0; i < max; i++)
2095                         {
2096                                 if (!n.childs[p[i]])
2097                                         return undefined;
2098
2099                                 n = n.childs[p[i]];
2100                         }
2101
2102                         return n;
2103                 }
2104         });
2105
2106         this.ui.table = AbstractWidget.extend({
2107                 init: function()
2108                 {
2109                         this._rows = [ ];
2110                 },
2111
2112                 row: function(values)
2113                 {
2114                         if (isa(values, 'Array'))
2115                         {
2116                                 this._rows.push(values);
2117                         }
2118                         else if (isa(values, 'Object'))
2119                         {
2120                                 var v = [ ];
2121                                 for (var i = 0; i < this.options.columns.length; i++)
2122                                 {
2123                                         var col = this.options.columns[i];
2124
2125                                         if (typeof col.key == 'string')
2126                                                 v.push(values[col.key]);
2127                                         else
2128                                                 v.push(null);
2129                                 }
2130                                 this._rows.push(v);
2131                         }
2132                 },
2133
2134                 rows: function(rows)
2135                 {
2136                         for (var i = 0; i < rows.length; i++)
2137                                 this.row(rows[i]);
2138                 },
2139
2140                 render: function(id)
2141                 {
2142                         var fieldset = document.createElement('fieldset');
2143                                 fieldset.className = 'cbi-section';
2144
2145                         if (this.options.caption)
2146                         {
2147                                 var legend = document.createElement('legend');
2148                                 $(legend).append(this.options.caption);
2149                                 fieldset.appendChild(legend);
2150                         }
2151
2152                         var table = document.createElement('table');
2153                                 table.className = 'cbi-section-table';
2154
2155                         var has_caption = false;
2156                         var has_description = false;
2157
2158                         for (var i = 0; i < this.options.columns.length; i++)
2159                                 if (this.options.columns[i].caption)
2160                                 {
2161                                         has_caption = true;
2162                                         break;
2163                                 }
2164                                 else if (this.options.columns[i].description)
2165                                 {
2166                                         has_description = true;
2167                                         break;
2168                                 }
2169
2170                         if (has_caption)
2171                         {
2172                                 var tr = table.insertRow(-1);
2173                                         tr.className = 'cbi-section-table-titles';
2174
2175                                 for (var i = 0; i < this.options.columns.length; i++)
2176                                 {
2177                                         var col = this.options.columns[i];
2178                                         var th = document.createElement('th');
2179                                                 th.className = 'cbi-section-table-cell';
2180
2181                                         tr.appendChild(th);
2182
2183                                         if (col.width)
2184                                                 th.style.width = col.width;
2185
2186                                         if (col.align)
2187                                                 th.style.textAlign = col.align;
2188
2189                                         if (col.caption)
2190                                                 $(th).append(col.caption);
2191                                 }
2192                         }
2193
2194                         if (has_description)
2195                         {
2196                                 var tr = table.insertRow(-1);
2197                                         tr.className = 'cbi-section-table-descr';
2198
2199                                 for (var i = 0; i < this.options.columns.length; i++)
2200                                 {
2201                                         var col = this.options.columns[i];
2202                                         var th = document.createElement('th');
2203                                                 th.className = 'cbi-section-table-cell';
2204
2205                                         tr.appendChild(th);
2206
2207                                         if (col.width)
2208                                                 th.style.width = col.width;
2209
2210                                         if (col.align)
2211                                                 th.style.textAlign = col.align;
2212
2213                                         if (col.description)
2214                                                 $(th).append(col.description);
2215                                 }
2216                         }
2217
2218                         if (this._rows.length == 0)
2219                         {
2220                                 if (this.options.placeholder)
2221                                 {
2222                                         var tr = table.insertRow(-1);
2223                                         var td = tr.insertCell(-1);
2224                                                 td.className = 'cbi-section-table-cell';
2225
2226                                         td.colSpan = this.options.columns.length;
2227                                         $(td).append(this.options.placeholder);
2228                                 }
2229                         }
2230                         else
2231                         {
2232                                 for (var i = 0; i < this._rows.length; i++)
2233                                 {
2234                                         var tr = table.insertRow(-1);
2235
2236                                         for (var j = 0; j < this.options.columns.length; j++)
2237                                         {
2238                                                 var col = this.options.columns[j];
2239                                                 var td = tr.insertCell(-1);
2240
2241                                                 var val = this._rows[i][j];
2242
2243                                                 if (typeof(val) == 'undefined')
2244                                                         val = col.placeholder;
2245
2246                                                 if (typeof(val) == 'undefined')
2247                                                         val = '';
2248
2249                                                 if (col.width)
2250                                                         td.style.width = col.width;
2251
2252                                                 if (col.align)
2253                                                         td.style.textAlign = col.align;
2254
2255                                                 if (typeof col.format == 'string')
2256                                                         $(td).append(col.format.format(val));
2257                                                 else if (typeof col.format == 'function')
2258                                                         $(td).append(col.format(val, i));
2259                                                 else
2260                                                         $(td).append(val);
2261                                         }
2262                                 }
2263                         }
2264
2265                         this._rows = [ ];
2266                         fieldset.appendChild(table);
2267
2268                         return fieldset;
2269                 }
2270         });
2271
2272         this.ui.progress = AbstractWidget.extend({
2273                 render: function()
2274                 {
2275                         var vn = parseInt(this.options.value) || 0;
2276                         var mn = parseInt(this.options.max) || 100;
2277                         var pc = Math.floor((100 / mn) * vn);
2278
2279                         var bar = document.createElement('div');
2280                                 bar.className = 'progressbar';
2281
2282                         bar.appendChild(document.createElement('div'));
2283                         bar.lastChild.appendChild(document.createElement('div'));
2284                         bar.lastChild.style.width = pc + '%';
2285
2286                         if (typeof(this.options.format) == 'string')
2287                                 $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
2288                         else if (typeof(this.options.format) == 'function')
2289                                 $(bar.lastChild.lastChild).append(this.options.format(pc));
2290                         else
2291                                 $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
2292
2293                         return bar;
2294                 }
2295         });
2296
2297         this.ui.devicebadge = AbstractWidget.extend({
2298                 render: function()
2299                 {
2300                         var dev = this.options.l3_device || this.options.device || '?';
2301
2302                         var span = document.createElement('span');
2303                                 span.className = 'ifacebadge';
2304
2305                         if (typeof(this.options.signal) == 'number' ||
2306                                 typeof(this.options.noise) == 'number')
2307                         {
2308                                 var r = 'none';
2309                                 if (typeof(this.options.signal) != 'undefined' &&
2310                                         typeof(this.options.noise) != 'undefined')
2311                                 {
2312                                         var q = (-1 * (this.options.noise - this.options.signal)) / 5;
2313                                         if (q < 1)
2314                                                 r = '0';
2315                                         else if (q < 2)
2316                                                 r = '0-25';
2317                                         else if (q < 3)
2318                                                 r = '25-50';
2319                                         else if (q < 4)
2320                                                 r = '50-75';
2321                                         else
2322                                                 r = '75-100';
2323                                 }
2324
2325                                 span.appendChild(document.createElement('img'));
2326                                 span.lastChild.src = _luci2.globals.resource + '/icons/signal-' + r + '.png';
2327
2328                                 if (r == 'none')
2329                                         span.title = _luci2.tr('No signal');
2330                                 else
2331                                         span.title = '%s: %d %s / %s: %d %s'.format(
2332                                                 _luci2.tr('Signal'), this.options.signal, _luci2.tr('dBm'),
2333                                                 _luci2.tr('Noise'), this.options.noise, _luci2.tr('dBm')
2334                                         );
2335                         }
2336                         else
2337                         {
2338                                 var type = 'ethernet';
2339                                 var desc = _luci2.tr('Ethernet device');
2340
2341                                 if (this.options.l3_device != this.options.device)
2342                                 {
2343                                         type = 'tunnel';
2344                                         desc = _luci2.tr('Tunnel interface');
2345                                 }
2346                                 else if (dev.indexOf('br-') == 0)
2347                                 {
2348                                         type = 'bridge';
2349                                         desc = _luci2.tr('Bridge');
2350                                 }
2351                                 else if (dev.indexOf('.') > 0)
2352                                 {
2353                                         type = 'vlan';
2354                                         desc = _luci2.tr('VLAN interface');
2355                                 }
2356                                 else if (dev.indexOf('wlan') == 0 ||
2357                                                  dev.indexOf('ath') == 0 ||
2358                                                  dev.indexOf('wl') == 0)
2359                                 {
2360                                         type = 'wifi';
2361                                         desc = _luci2.tr('Wireless Network');
2362                                 }
2363
2364                                 span.appendChild(document.createElement('img'));
2365                                 span.lastChild.src = _luci2.globals.resource + '/icons/' + type + (this.options.up ? '' : '_disabled') + '.png';
2366                                 span.title = desc;
2367                         }
2368
2369                         $(span).append(' ');
2370                         $(span).append(dev);
2371
2372                         return span;
2373                 }
2374         });
2375
2376         var type = function(f, l)
2377         {
2378                 f.message = l;
2379                 return f;
2380         };
2381
2382         this.cbi = {
2383                 validation: {
2384                         i18n: function(msg)
2385                         {
2386                                 _luci2.cbi.validation.message = _luci2.tr(msg);
2387                         },
2388
2389                         compile: function(code)
2390                         {
2391                                 var pos = 0;
2392                                 var esc = false;
2393                                 var depth = 0;
2394                                 var types = _luci2.cbi.validation.types;
2395                                 var stack = [ ];
2396
2397                                 code += ',';
2398
2399                                 for (var i = 0; i < code.length; i++)
2400                                 {
2401                                         if (esc)
2402                                         {
2403                                                 esc = false;
2404                                                 continue;
2405                                         }
2406
2407                                         switch (code.charCodeAt(i))
2408                                         {
2409                                         case 92:
2410                                                 esc = true;
2411                                                 break;
2412
2413                                         case 40:
2414                                         case 44:
2415                                                 if (depth <= 0)
2416                                                 {
2417                                                         if (pos < i)
2418                                                         {
2419                                                                 var label = code.substring(pos, i);
2420                                                                         label = label.replace(/\\(.)/g, '$1');
2421                                                                         label = label.replace(/^[ \t]+/g, '');
2422                                                                         label = label.replace(/[ \t]+$/g, '');
2423
2424                                                                 if (label && !isNaN(label))
2425                                                                 {
2426                                                                         stack.push(parseFloat(label));
2427                                                                 }
2428                                                                 else if (label.match(/^(['"]).*\1$/))
2429                                                                 {
2430                                                                         stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
2431                                                                 }
2432                                                                 else if (typeof types[label] == 'function')
2433                                                                 {
2434                                                                         stack.push(types[label]);
2435                                                                         stack.push(null);
2436                                                                 }
2437                                                                 else
2438                                                                 {
2439                                                                         throw "Syntax error, unhandled token '"+label+"'";
2440                                                                 }
2441                                                         }
2442                                                         pos = i+1;
2443                                                 }
2444                                                 depth += (code.charCodeAt(i) == 40);
2445                                                 break;
2446
2447                                         case 41:
2448                                                 if (--depth <= 0)
2449                                                 {
2450                                                         if (typeof stack[stack.length-2] != 'function')
2451                                                                 throw "Syntax error, argument list follows non-function";
2452
2453                                                         stack[stack.length-1] =
2454                                                                 arguments.callee(code.substring(pos, i));
2455
2456                                                         pos = i+1;
2457                                                 }
2458                                                 break;
2459                                         }
2460                                 }
2461
2462                                 return stack;
2463                         }
2464                 }
2465         };
2466
2467         var validation = this.cbi.validation;
2468
2469         validation.types = {
2470                 'integer': function()
2471                 {
2472                         if (this.match(/^-?[0-9]+$/) != null)
2473                                 return true;
2474
2475                         validation.i18n('Must be a valid integer');
2476                         return false;
2477                 },
2478
2479                 'uinteger': function()
2480                 {
2481                         if (validation.types['integer'].apply(this) && (this >= 0))
2482                                 return true;
2483
2484                         validation.i18n('Must be a positive integer');
2485                         return false;
2486                 },
2487
2488                 'float': function()
2489                 {
2490                         if (!isNaN(parseFloat(this)))
2491                                 return true;
2492
2493                         validation.i18n('Must be a valid number');
2494                         return false;
2495                 },
2496
2497                 'ufloat': function()
2498                 {
2499                         if (validation.types['float'].apply(this) && (this >= 0))
2500                                 return true;
2501
2502                         validation.i18n('Must be a positive number');
2503                         return false;
2504                 },
2505
2506                 'ipaddr': function()
2507                 {
2508                         if (validation.types['ip4addr'].apply(this) ||
2509                                 validation.types['ip6addr'].apply(this))
2510                                 return true;
2511
2512                         validation.i18n('Must be a valid IP address');
2513                         return false;
2514                 },
2515
2516                 'ip4addr': function()
2517                 {
2518                         if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
2519                         {
2520                                 if ((RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
2521                                     (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
2522                                     (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
2523                                     (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
2524                                     ((RegExp.$6.indexOf('.') < 0)
2525                                       ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
2526                                       : (validation.types['ip4addr'].apply(RegExp.$6))))
2527                                         return true;
2528                         }
2529
2530                         validation.i18n('Must be a valid IPv4 address');
2531                         return false;
2532                 },
2533
2534                 'ip6addr': function()
2535                 {
2536                         if (this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/))
2537                         {
2538                                 if (!RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)))
2539                                 {
2540                                         var addr = RegExp.$1;
2541
2542                                         if (addr == '::')
2543                                         {
2544                                                 return true;
2545                                         }
2546
2547                                         if (addr.indexOf('.') > 0)
2548                                         {
2549                                                 var off = addr.lastIndexOf(':');
2550
2551                                                 if (!(off && validation.types['ip4addr'].apply(addr.substr(off+1))))
2552                                                 {
2553                                                         validation.i18n('Must be a valid IPv6 address');
2554                                                         return false;
2555                                                 }
2556
2557                                                 addr = addr.substr(0, off) + ':0:0';
2558                                         }
2559
2560                                         if (addr.indexOf('::') >= 0)
2561                                         {
2562                                                 var colons = 0;
2563                                                 var fill = '0';
2564
2565                                                 for (var i = 1; i < (addr.length-1); i++)
2566                                                         if (addr.charAt(i) == ':')
2567                                                                 colons++;
2568
2569                                                 if (colons > 7)
2570                                                 {
2571                                                         validation.i18n('Must be a valid IPv6 address');
2572                                                         return false;
2573                                                 }
2574
2575                                                 for (var i = 0; i < (7 - colons); i++)
2576                                                         fill += ':0';
2577
2578                                                 if (addr.match(/^(.*?)::(.*?)$/))
2579                                                         addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
2580                                                                    (RegExp.$2 ? ':' + RegExp.$2 : '');
2581                                         }
2582
2583                                         if (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null)
2584                                                 return true;
2585
2586                                         validation.i18n('Must be a valid IPv6 address');
2587                                         return false;
2588                                 }
2589                         }
2590
2591                         return false;
2592                 },
2593
2594                 'port': function()
2595                 {
2596                         if (validation.types['integer'].apply(this) &&
2597                                 (this >= 0) && (this <= 65535))
2598                                 return true;
2599
2600                         validation.i18n('Must be a valid port number');
2601                         return false;
2602                 },
2603
2604                 'portrange': function()
2605                 {
2606                         if (this.match(/^(\d+)-(\d+)$/))
2607                         {
2608                                 var p1 = RegExp.$1;
2609                                 var p2 = RegExp.$2;
2610
2611                                 if (validation.types['port'].apply(p1) &&
2612                                     validation.types['port'].apply(p2) &&
2613                                     (parseInt(p1) <= parseInt(p2)))
2614                                         return true;
2615                         }
2616                         else if (validation.types['port'].apply(this))
2617                         {
2618                                 return true;
2619                         }
2620
2621                         validation.i18n('Must be a valid port range');
2622                         return false;
2623                 },
2624
2625                 'macaddr': function()
2626                 {
2627                         if (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null)
2628                                 return true;
2629
2630                         validation.i18n('Must be a valid MAC address');
2631                         return false;
2632                 },
2633
2634                 'host': function()
2635                 {
2636                         if (validation.types['hostname'].apply(this) ||
2637                             validation.types['ipaddr'].apply(this))
2638                                 return true;
2639
2640                         validation.i18n('Must be a valid hostname or IP address');
2641                         return false;
2642                 },
2643
2644                 'hostname': function()
2645                 {
2646                         if ((this.length <= 253) &&
2647                             ((this.match(/^[a-zA-Z0-9]+$/) != null ||
2648                              (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
2649                               this.match(/[^0-9.]/)))))
2650                                 return true;
2651
2652                         validation.i18n('Must be a valid host name');
2653                         return false;
2654                 },
2655
2656                 'network': function()
2657                 {
2658                         if (validation.types['uciname'].apply(this) ||
2659                             validation.types['host'].apply(this))
2660                                 return true;
2661
2662                         validation.i18n('Must be a valid network name');
2663                         return false;
2664                 },
2665
2666                 'wpakey': function()
2667                 {
2668                         var v = this;
2669
2670                         if ((v.length == 64)
2671                               ? (v.match(/^[a-fA-F0-9]{64}$/) != null)
2672                                   : ((v.length >= 8) && (v.length <= 63)))
2673                                 return true;
2674
2675                         validation.i18n('Must be a valid WPA key');
2676                         return false;
2677                 },
2678
2679                 'wepkey': function()
2680                 {
2681                         var v = this;
2682
2683                         if (v.substr(0,2) == 's:')
2684                                 v = v.substr(2);
2685
2686                         if (((v.length == 10) || (v.length == 26))
2687                               ? (v.match(/^[a-fA-F0-9]{10,26}$/) != null)
2688                               : ((v.length == 5) || (v.length == 13)))
2689                                 return true;
2690
2691                         validation.i18n('Must be a valid WEP key');
2692                         return false;
2693                 },
2694
2695                 'uciname': function()
2696                 {
2697                         if (this.match(/^[a-zA-Z0-9_]+$/) != null)
2698                                 return true;
2699
2700                         validation.i18n('Must be a valid UCI identifier');
2701                         return false;
2702                 },
2703
2704                 'range': function(min, max)
2705                 {
2706                         var val = parseFloat(this);
2707
2708                         if (validation.types['integer'].apply(this) &&
2709                             !isNaN(min) && !isNaN(max) && ((val >= min) && (val <= max)))
2710                                 return true;
2711
2712                         validation.i18n('Must be a number between %d and %d');
2713                         return false;
2714                 },
2715
2716                 'min': function(min)
2717                 {
2718                         var val = parseFloat(this);
2719
2720                         if (validation.types['integer'].apply(this) &&
2721                             !isNaN(min) && !isNaN(val) && (val >= min))
2722                                 return true;
2723
2724                         validation.i18n('Must be a number greater or equal to %d');
2725                         return false;
2726                 },
2727
2728                 'max': function(max)
2729                 {
2730                         var val = parseFloat(this);
2731
2732                         if (validation.types['integer'].apply(this) &&
2733                             !isNaN(max) && !isNaN(val) && (val <= max))
2734                                 return true;
2735
2736                         validation.i18n('Must be a number lower or equal to %d');
2737                         return false;
2738                 },
2739
2740                 'rangelength': function(min, max)
2741                 {
2742                         var val = '' + this;
2743
2744                         if (!isNaN(min) && !isNaN(max) &&
2745                             (val.length >= min) && (val.length <= max))
2746                                 return true;
2747
2748                         validation.i18n('Must be between %d and %d characters');
2749                         return false;
2750                 },
2751
2752                 'minlength': function(min)
2753                 {
2754                         var val = '' + this;
2755
2756                         if (!isNaN(min) && (val.length >= min))
2757                                 return true;
2758
2759                         validation.i18n('Must be at least %d characters');
2760                         return false;
2761                 },
2762
2763                 'maxlength': function(max)
2764                 {
2765                         var val = '' + this;
2766
2767                         if (!isNaN(max) && (val.length <= max))
2768                                 return true;
2769
2770                         validation.i18n('Must be at most %d characters');
2771                         return false;
2772                 },
2773
2774                 'or': function()
2775                 {
2776                         var msgs = [ ];
2777
2778                         for (var i = 0; i < arguments.length; i += 2)
2779                         {
2780                                 delete validation.message;
2781
2782                                 if (typeof(arguments[i]) != 'function')
2783                                 {
2784                                         if (arguments[i] == this)
2785                                                 return true;
2786                                         i--;
2787                                 }
2788                                 else if (arguments[i].apply(this, arguments[i+1]))
2789                                 {
2790                                         return true;
2791                                 }
2792
2793                                 if (validation.message)
2794                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2795                         }
2796
2797                         validation.message = msgs.join( _luci2.tr(' - or - '));
2798                         return false;
2799                 },
2800
2801                 'and': function()
2802                 {
2803                         var msgs = [ ];
2804
2805                         for (var i = 0; i < arguments.length; i += 2)
2806                         {
2807                                 delete validation.message;
2808
2809                                 if (typeof arguments[i] != 'function')
2810                                 {
2811                                         if (arguments[i] != this)
2812                                                 return false;
2813                                         i--;
2814                                 }
2815                                 else if (!arguments[i].apply(this, arguments[i+1]))
2816                                 {
2817                                         return false;
2818                                 }
2819
2820                                 if (validation.message)
2821                                         msgs.push(validation.message.format.apply(validation.message, arguments[i+1]));
2822                         }
2823
2824                         validation.message = msgs.join(', ');
2825                         return true;
2826                 },
2827
2828                 'neg': function()
2829                 {
2830                         return validation.types['or'].apply(
2831                                 this.replace(/^[ \t]*![ \t]*/, ''), arguments);
2832                 },
2833
2834                 'list': function(subvalidator, subargs)
2835                 {
2836                         if (typeof subvalidator != 'function')
2837                                 return false;
2838
2839                         var tokens = this.match(/[^ \t]+/g);
2840                         for (var i = 0; i < tokens.length; i++)
2841                                 if (!subvalidator.apply(tokens[i], subargs))
2842                                         return false;
2843
2844                         return true;
2845                 },
2846
2847                 'phonedigit': function()
2848                 {
2849                         if (this.match(/^[0-9\*#!\.]+$/) != null)
2850                                 return true;
2851
2852                         validation.i18n('Must be a valid phone number digit');
2853                         return false;
2854                 },
2855
2856                 'string': function()
2857                 {
2858                         return true;
2859                 }
2860         };
2861
2862
2863         var AbstractValue = AbstractWidget.extend({
2864                 init: function(name, options)
2865                 {
2866                         this.name = name;
2867                         this.instance = { };
2868                         this.dependencies = [ ];
2869                         this.rdependency = { };
2870
2871                         this.options = _luci2.defaults(options, {
2872                                 placeholder: '',
2873                                 datatype: 'string',
2874                                 optional: false,
2875                                 keep: true
2876                         });
2877                 },
2878
2879                 id: function(sid)
2880                 {
2881                         return this.section.id('field', sid || '__unknown__', this.name);
2882                 },
2883
2884                 render: function(sid)
2885                 {
2886                         var i = this.instance[sid] = { };
2887
2888                         i.top = $('<div />').addClass('cbi-value');
2889
2890                         if (typeof(this.options.caption) == 'string')
2891                                 $('<label />')
2892                                         .addClass('cbi-value-title')
2893                                         .attr('for', this.id(sid))
2894                                         .text(this.options.caption)
2895                                         .appendTo(i.top);
2896
2897                         i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
2898                         i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
2899
2900                         if (typeof(this.options.description) == 'string')
2901                                 $('<div />')
2902                                         .addClass('cbi-value-description')
2903                                         .text(this.options.description)
2904                                         .appendTo(i.top);
2905
2906                         return i.top;
2907                 },
2908
2909                 ucipath: function(sid)
2910                 {
2911                         return {
2912                                 config:  (this.options.uci_package || this.map.uci_package),
2913                                 section: (this.options.uci_section || sid),
2914                                 option:  (this.options.uci_option  || this.name)
2915                         };
2916                 },
2917
2918                 ucivalue: function(sid)
2919                 {
2920                         var uci = this.ucipath(sid);
2921                         var val = this.map.get(uci.config, uci.section, uci.option);
2922
2923                         if (typeof(val) == 'undefined')
2924                                 return this.options.initial;
2925
2926                         return val;
2927                 },
2928
2929                 formvalue: function(sid)
2930                 {
2931                         var v = $('#' + this.id(sid)).val();
2932                         return (v === '') ? undefined : v;
2933                 },
2934
2935                 textvalue: function(sid)
2936                 {
2937                         var v = this.formvalue(sid);
2938
2939                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2940                                 v = this.ucivalue(sid);
2941
2942                         if (typeof(v) == 'undefined' || ($.isArray(v) && !v.length))
2943