luci2: implement LuCI2.cbi.SingleSection widget
[project/luci2/ui.git] / luci2 / htdocs / luci2 / luci2.js
index ffa58ea..2d002cb 100644 (file)
@@ -214,7 +214,7 @@ function LuCI2()
                _class.prototype = prototype;
                _class.prototype.constructor = _class;
 
-               _class.extend = arguments.callee;
+               _class.extend = Class.extend;
 
                return _class;
        };
@@ -364,8 +364,10 @@ function LuCI2()
                        h += keys[i] + ':' + data[keys[i]];
                }
 
-               if (h)
+               if (h.length)
                        location.hash = '#' + h;
+               else
+                       location.hash = '';
        };
 
        this.getHash = function(key)
@@ -386,6 +388,103 @@ function LuCI2()
                return data;
        };
 
+       this.toArray = function(x)
+       {
+               switch (typeof(x))
+               {
+               case 'number':
+               case 'boolean':
+                       return [ x ];
+
+               case 'string':
+                       var r = [ ];
+                       var l = x.split(/\s+/);
+                       for (var i = 0; i < l.length; i++)
+                               if (l[i].length > 0)
+                                       r.push(l[i]);
+                       return r;
+
+               case 'object':
+                       if ($.isArray(x))
+                       {
+                               var r = [ ];
+                               for (var i = 0; i < x.length; i++)
+                                       r.push(x[i]);
+                               return r;
+                       }
+                       else if ($.isPlainObject(x))
+                       {
+                               var r = [ ];
+                               for (var k in x)
+                                       if (x.hasOwnProperty(k))
+                                               r.push(k);
+                               return r.sort();
+                       }
+               }
+
+               return [ ];
+       };
+
+       this.toObject = function(x)
+       {
+               switch (typeof(x))
+               {
+               case 'number':
+               case 'boolean':
+                       return { x: true };
+
+               case 'string':
+                       var r = { };
+                       var l = x.split(/\x+/);
+                       for (var i = 0; i < l.length; i++)
+                               if (l[i].length > 0)
+                                       r[l[i]] = true;
+                       return r;
+
+               case 'object':
+                       if ($.isArray(x))
+                       {
+                               var r = { };
+                               for (var i = 0; i < x.length; i++)
+                                       r[x[i]] = true;
+                               return r;
+                       }
+                       else if ($.isPlainObject(x))
+                       {
+                               return x;
+                       }
+               }
+
+               return { };
+       };
+
+       this.filterArray = function(array, item)
+       {
+               if (!$.isArray(array))
+                       return [ ];
+
+               for (var i = 0; i < array.length; i++)
+                       if (array[i] === item)
+                               array.splice(i--, 1);
+
+               return array;
+       };
+
+       this.toClassName = function(str, suffix)
+       {
+               var n = '';
+               var l = str.split(/[\/.]/);
+
+               for (var i = 0; i < l.length; i++)
+                       if (l[i].length > 0)
+                               n += l[i].charAt(0).toUpperCase() + l[i].substr(1).toLowerCase();
+
+               if (typeof(suffix) == 'string')
+                       n += suffix;
+
+               return n;
+       };
+
        this.globals = {
                timeout:  15000,
                resource: '/luci2',
@@ -406,43 +505,48 @@ function LuCI2()
                                data:        JSON.stringify(req),
                                dataType:    'json',
                                type:        'POST',
-                               timeout:     _luci2.globals.timeout
-                       }).then(cb);
+                               timeout:     _luci2.globals.timeout,
+                               _rpc_req:   req
+                       }).then(cb, cb);
                },
 
                _list_cb: function(msg)
                {
+                       var list = msg.result;
+
                        /* verify message frame */
-                       if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id)
-                               throw 'Invalid JSON response';
+                       if (typeof(msg) != 'object' || msg.jsonrpc != '2.0' || !msg.id || !$.isArray(list))
+                               list = [ ];
 
-                       return msg.result;
+                       return $.Deferred().resolveWith(this, [ list ]);
                },
 
                _call_cb: function(msg)
                {
                        var data = [ ];
                        var type = Object.prototype.toString;
+                       var reqs = this._rpc_req;
 
-                       if (!$.isArray(msg))
+                       if (!$.isArray(reqs))
+                       {
                                msg = [ msg ];
+                               reqs = [ reqs ];
+                       }
 
                        for (var i = 0; i < msg.length; i++)
                        {
-                               /* verify message frame */
-                               if (typeof(msg[i]) != 'object' || msg[i].jsonrpc != '2.0' || !msg[i].id)
-                                       throw 'Invalid JSON response';
-
                                /* fetch related request info */
-                               var req = _luci2.rpc._requests[msg[i].id];
+                               var req = _luci2.rpc._requests[reqs[i].id];
                                if (typeof(req) != 'object')
                                        throw 'No related request for JSON response';
 
                                /* fetch response attribute and verify returned type */
                                var ret = undefined;
 
-                               if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
-                                       ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
+                               /* verify message frame */
+                               if (typeof(msg[i]) == 'object' && msg[i].jsonrpc == '2.0')
+                                       if ($.isArray(msg[i].result) && msg[i].result[0] == 0)
+                                               ret = (msg[i].result.length > 1) ? msg[i].result[1] : msg[i].result[0];
 
                                if (req.expect)
                                {
@@ -451,7 +555,7 @@ function LuCI2()
                                                if (typeof(ret) != 'undefined' && key != '')
                                                        ret = ret[key];
 
-                                               if (type.call(ret) != type.call(req.expect[key]))
+                                               if (typeof(ret) == 'undefined' || type.call(ret) != type.call(req.expect[key]))
                                                        ret = req.expect[key];
 
                                                break;
@@ -473,10 +577,10 @@ function LuCI2()
                                        data = ret;
 
                                /* delete request object */
-                               delete _luci2.rpc._requests[msg[i].id];
+                               delete _luci2.rpc._requests[reqs[i].id];
                        }
 
-                       return data;
+                       return $.Deferred().resolveWith(this, [ data ]);
                },
 
                list: function()
@@ -565,456 +669,482 @@ function LuCI2()
                }
        };
 
-       this.uci = {
+       this.UCIContext = Class.extend({
 
-               writable: function()
+               init: function()
                {
-                       return _luci2.session.access('ubus', 'uci', 'commit');
+                       this.state = {
+                               newid:   0,
+                               values:  { },
+                               creates: { },
+                               changes: { },
+                               deletes: { },
+                               reorder: { }
+                       };
                },
 
-               add: _luci2.rpc.declare({
+               _load: _luci2.rpc.declare({
+                       object: 'uci',
+                       method: 'get',
+                       params: [ 'config' ],
+                       expect: { values: { } }
+               }),
+
+               _order: _luci2.rpc.declare({
+                       object: 'uci',
+                       method: 'order',
+                       params: [ 'config', 'sections' ]
+               }),
+
+               _add: _luci2.rpc.declare({
                        object: 'uci',
                        method: 'add',
                        params: [ 'config', 'type', 'name', 'values' ],
                        expect: { section: '' }
                }),
 
-               apply: function()
-               {
-
-               },
-
-               configs: _luci2.rpc.declare({
+               _set: _luci2.rpc.declare({
                        object: 'uci',
-                       method: 'configs',
-                       expect: { configs: [ ] }
+                       method: 'set',
+                       params: [ 'config', 'section', 'values' ]
                }),
 
-               _changes: _luci2.rpc.declare({
+               _delete: _luci2.rpc.declare({
                        object: 'uci',
-                       method: 'changes',
-                       params: [ 'config' ],
-                       expect: { changes: [ ] }
+                       method: 'delete',
+                       params: [ 'config', 'section', 'options' ]
                }),
 
-               changes: function(config)
+               load: function(packages)
                {
-                       if (typeof(config) == 'string')
-                               return this._changes(config);
+                       var self = this;
+                       var seen = { };
+                       var pkgs = [ ];
 
-                       var configlist;
-                       return this.configs().then(function(configs) {
-                               _luci2.rpc.batch();
-                               configlist = configs;
+                       if (!$.isArray(packages))
+                               packages = [ packages ];
 
-                               for (var i = 0; i < configs.length; i++)
-                                       _luci2.uci._changes(configs[i]);
+                       _luci2.rpc.batch();
 
-                               return _luci2.rpc.flush();
-                       }).then(function(changes) {
-                               var rv = { };
+                       for (var i = 0; i < packages.length; i++)
+                               if (!seen[packages[i]])
+                               {
+                                       pkgs.push(packages[i]);
+                                       seen[packages[i]] = true;
+                                       self._load(packages[i]);
+                               }
 
-                               for (var i = 0; i < configlist.length; i++)
-                                       if (changes[i].length)
-                                               rv[configlist[i]] = changes[i];
+                       return _luci2.rpc.flush().then(function(responses) {
+                               for (var i = 0; i < responses.length; i++)
+                                       self.state.values[pkgs[i]] = responses[i];
 
-                               return rv;
+                               return pkgs;
                        });
                },
 
-               commit: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'commit',
-                       params: [ 'config' ]
-               }),
-
-               _delete_one: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'delete',
-                       params: [ 'config', 'section', 'option' ]
-               }),
+               unload: function(packages)
+               {
+                       if (!$.isArray(packages))
+                               packages = [ packages ];
 
-               _delete_multiple: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'delete',
-                       params: [ 'config', 'section', 'options' ]
-               }),
+                       for (var i = 0; i < packages.length; i++)
+                       {
+                               delete this.state.values[packages[i]];
+                               delete this.state.creates[packages[i]];
+                               delete this.state.changes[packages[i]];
+                               delete this.state.deletes[packages[i]];
+                       }
+               },
 
-               'delete': function(config, section, option)
+               add: function(conf, type, name)
                {
-                       if ($.isArray(option))
-                               return this._delete_multiple(config, section, option);
-                       else
-                               return this._delete_one(config, section, option);
-               },
+                       var c = this.state.creates;
+                       var s = '.new.%d'.format(this.state.newid++);
 
-               delete_all: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'delete',
-                       params: [ 'config', 'type', 'match' ]
-               }),
+                       if (!c[conf])
+                               c[conf] = { };
 
-               _foreach: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'get',
-                       params: [ 'config', 'type' ],
-                       expect: { values: { } }
-               }),
+                       c[conf][s] = {
+                               '.type':      type,
+                               '.name':      s,
+                               '.create':    name,
+                               '.anonymous': !name,
+                               '.index':     1000 + this.state.newid
+                       };
 
-               foreach: function(config, type, cb)
-               {
-                       return this._foreach(config, type).then(function(sections) {
-                               for (var s in sections)
-                                       cb(sections[s]);
-                       });
+                       return s;
                },
 
-               get: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'get',
-                       params: [ 'config', 'section', 'option' ],
-                       expect: { '': { } },
-                       filter: function(data, params) {
-                               if (typeof(params.option) == 'undefined')
-                                       return data.values ? data.values['.type'] : undefined;
-                               else
-                                       return data.value;
-                       }
-               }),
+               remove: function(conf, sid)
+               {
+                       var n = this.state.creates;
+                       var c = this.state.changes;
+                       var d = this.state.deletes;
 
-               get_all: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'get',
-                       params: [ 'config', 'section' ],
-                       expect: { values: { } },
-                       filter: function(data, params) {
-                               if (typeof(params.section) == 'string')
-                                       data['.section'] = params.section;
-                               else if (typeof(params.config) == 'string')
-                                       data['.package'] = params.config;
-                               return data;
+                       /* requested deletion of a just created section */
+                       if (sid.indexOf('.new.') == 0)
+                       {
+                               if (n[conf])
+                                       delete n[conf][sid];
                        }
-               }),
-
-               get_first: function(config, type, option)
-               {
-                       return this._foreach(config, type).then(function(sections) {
-                               for (var s in sections)
-                               {
-                                       var val = (typeof(option) == 'string') ? sections[s][option] : sections[s]['.name'];
+                       else
+                       {
+                               if (c[conf])
+                                       delete c[conf][sid];
 
-                                       if (typeof(val) != 'undefined')
-                                               return val;
-                               }
+                               if (!d[conf])
+                                       d[conf] = { };
 
-                               return undefined;
-                       });
+                               d[conf][sid] = true;
+                       }
                },
 
-               section: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'add',
-                       params: [ 'config', 'type', 'name', 'values' ],
-                       expect: { section: '' }
-               }),
-
-               _set: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'set',
-                       params: [ 'config', 'section', 'values' ]
-               }),
-
-               set: function(config, section, option, value)
+               sections: function(conf, type, cb)
                {
-                       if (typeof(value) == 'undefined' && typeof(option) == 'string')
-                               return this.section(config, section, option); /* option -> type */
-                       else if ($.isPlainObject(option))
-                               return this._set(config, section, option); /* option -> values */
+                       var sa = [ ];
+                       var v = this.state.values[conf];
+                       var n = this.state.creates[conf];
+                       var c = this.state.changes[conf];
+                       var d = this.state.deletes[conf];
 
-                       var values = { };
-                           values[option] = value;
+                       if (!v)
+                               return sa;
 
-                       return this._set(config, section, values);
-               },
+                       for (var s in v)
+                               if (!d || d[s] !== true)
+                                       if (!type || v[s]['.type'] == type)
+                                               sa.push($.extend({ }, v[s], c ? c[s] : undefined));
 
-               order: _luci2.rpc.declare({
-                       object: 'uci',
-                       method: 'order',
-                       params: [ 'config', 'sections' ]
-               })
-       };
+                       if (n)
+                               for (var s in n)
+                                       if (!type || n[s]['.type'] == type)
+                                               sa.push(n[s]);
 
-       this.network = {
-               listNetworkNames: function() {
-                       return _luci2.rpc.list('network.interface.*').then(function(list) {
-                               var names = [ ];
-                               for (var name in list)
-                                       if (name != 'network.interface.loopback')
-                                               names.push(name.substring(18));
-                               names.sort();
-                               return names;
+                       sa.sort(function(a, b) {
+                               return a['.index'] - b['.index'];
                        });
-               },
 
-               listDeviceNames: _luci2.rpc.declare({
-                       object: 'network.device',
-                       method: 'status',
-                       expect: { '': { } },
-                       filter: function(data) {
-                               var names = [ ];
-                               for (var name in data)
-                                       if (name != 'lo')
-                                               names.push(name);
-                               names.sort();
-                               return names;
-                       }
-               }),
+                       for (var i = 0; i < sa.length; i++)
+                               sa[i]['.index'] = i;
 
-               getNetworkStatus: function()
-               {
-                       var nets = [ ];
-                       var devs = { };
+                       if (typeof(cb) == 'function')
+                               for (var i = 0; i < sa.length; i++)
+                                       cb.call(this, sa[i], sa[i]['.name']);
 
-                       return this.listNetworkNames().then(function(names) {
-                               _luci2.rpc.batch();
+                       return sa;
+               },
 
-                               for (var i = 0; i < names.length; i++)
-                                       _luci2.network.getInterfaceStatus(names[i]);
+               get: function(conf, sid, opt)
+               {
+                       var v = this.state.values;
+                       var n = this.state.creates;
+                       var c = this.state.changes;
+                       var d = this.state.deletes;
 
-                               return _luci2.rpc.flush();
-                       }).then(function(networks) {
-                               for (var i = 0; i < networks.length; i++)
-                               {
-                                       var net = nets[i] = networks[i];
-                                       var dev = net.l3_device || net.l2_device;
-                                       if (dev)
-                                               net.device = devs[dev] || (devs[dev] = { });
-                               }
+                       if (typeof(sid) == 'undefined')
+                               return undefined;
 
-                               _luci2.rpc.batch();
+                       /* requested option in a just created section */
+                       if (sid.indexOf('.new.') == 0)
+                       {
+                               if (!n[conf])
+                                       return undefined;
 
-                               for (var dev in devs)
-                                       _luci2.network.getDeviceStatus(dev);
+                               if (typeof(opt) == 'undefined')
+                                       return n[conf][sid];
 
-                               return _luci2.rpc.flush();
-                       }).then(function(devices) {
-                               _luci2.rpc.batch();
+                               return n[conf][sid][opt];
+                       }
 
-                               for (var i = 0; i < devices.length; i++)
+                       /* requested an option value */
+                       if (typeof(opt) != 'undefined')
+                       {
+                               /* check whether option was deleted */
+                               if (d[conf] && d[conf][sid])
                                {
-                                       var brm = devices[i]['bridge-members'];
-                                       delete devices[i]['bridge-members'];
-
-                                       $.extend(devs[devices[i]['device']], devices[i]);
-
-                                       if (!brm)
-                                               continue;
-
-                                       devs[devices[i]['device']].subdevices = [ ];
-
-                                       for (var j = 0; j < brm.length; j++)
-                                       {
-                                               if (!devs[brm[j]])
-                                               {
-                                                       devs[brm[j]] = { };
-                                                       _luci2.network.getDeviceStatus(brm[j]);
-                                               }
+                                       if (d[conf][sid] === true)
+                                               return undefined;
 
-                                               devs[devices[i]['device']].subdevices[j] = devs[brm[j]];
-                                       }
+                                       for (var i = 0; i < d[conf][sid].length; i++)
+                                               if (d[conf][sid][i] == opt)
+                                                       return undefined;
                                }
 
-                               return _luci2.rpc.flush();
-                       }).then(function(subdevices) {
-                               for (var i = 0; i < subdevices.length; i++)
-                                       $.extend(devs[subdevices[i]['device']], subdevices[i]);
-
-                               _luci2.rpc.batch();
+                               /* check whether option was changed */
+                               if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
+                                       return c[conf][sid][opt];
 
-                               for (var dev in devs)
-                                       _luci2.wireless.getDeviceStatus(dev);
+                               /* return base value */
+                               if (v[conf] && v[conf][sid])
+                                       return v[conf][sid][opt];
 
-                               return _luci2.rpc.flush();
-                       }).then(function(wifidevices) {
-                               for (var i = 0; i < wifidevices.length; i++)
-                                       if (wifidevices[i])
-                                               devs[wifidevices[i]['device']].wireless = wifidevices[i];
+                               return undefined;
+                       }
 
-                               nets.sort(function(a, b) {
-                                       if (a['interface'] < b['interface'])
-                                               return -1;
-                                       else if (a['interface'] > b['interface'])
-                                               return 1;
-                                       else
-                                               return 0;
-                               });
+                       /* requested an entire section */
+                       if (v[conf])
+                               return v[conf][sid];
 
-                               return nets;
-                       });
+                       return undefined;
                },
 
-               findWanInterfaces: function(cb)
+               set: function(conf, sid, opt, val)
                {
-                       return this.listNetworkNames().then(function(names) {
-                               _luci2.rpc.batch();
-
-                               for (var i = 0; i < names.length; i++)
-                                       _luci2.network.getInterfaceStatus(names[i]);
+                       var n = this.state.creates;
+                       var c = this.state.changes;
+                       var d = this.state.deletes;
 
-                               return _luci2.rpc.flush();
-                       }).then(function(interfaces) {
-                               var rv = [ undefined, undefined ];
+                       if (typeof(sid) == 'undefined' ||
+                           typeof(opt) == 'undefined' ||
+                           opt.charAt(0) == '.')
+                               return;
 
-                               for (var i = 0; i < interfaces.length; i++)
+                       if (sid.indexOf('.new.') == 0)
+                       {
+                               if (n[conf] && n[conf][sid])
                                {
-                                       if (!interfaces[i].route)
-                                               continue;
-
-                                       for (var j = 0; j < interfaces[i].route.length; j++)
-                                       {
-                                               var rt = interfaces[i].route[j];
-
-                                               if (typeof(rt.table) != 'undefined')
-                                                       continue;
-
-                                               if (rt.target == '0.0.0.0' && rt.mask == 0)
-                                                       rv[0] = interfaces[i];
-                                               else if (rt.target == '::' && rt.mask == 0)
-                                                       rv[1] = interfaces[i];
-                                       }
+                                       if (typeof(val) != 'undefined')
+                                               n[conf][sid][opt] = val;
+                                       else
+                                               delete n[conf][sid][opt];
                                }
+                       }
+                       else if (typeof(val) != 'undefined')
+                       {
+                               /* do not set within deleted section */
+                               if (d[conf] && d[conf][sid] === true)
+                                       return;
 
-                               return rv;
-                       });
+                               if (!c[conf])
+                                       c[conf] = { };
+
+                               if (!c[conf][sid])
+                                       c[conf][sid] = { };
+
+                               /* undelete option */
+                               if (d[conf] && d[conf][sid])
+                                       d[conf][sid] = _luci2.filterArray(d[conf][sid], opt);
+
+                               c[conf][sid][opt] = val;
+                       }
+                       else
+                       {
+                               if (!d[conf])
+                                       d[conf] = { };
+
+                               if (!d[conf][sid])
+                                       d[conf][sid] = [ ];
+
+                               if (d[conf][sid] !== true)
+                                       d[conf][sid].push(opt);
+                       }
                },
 
-               getDHCPLeases: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'dhcp_leases',
-                       expect: { leases: [ ] }
-               }),
+               unset: function(conf, sid, opt)
+               {
+                       return this.set(conf, sid, opt, undefined);
+               },
 
-               getDHCPv6Leases: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'dhcp6_leases',
-                       expect: { leases: [ ] }
-               }),
+               _reload: function()
+               {
+                       var pkgs = [ ];
 
-               getRoutes: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'routes',
-                       expect: { routes: [ ] }
-               }),
+                       for (var pkg in this.state.values)
+                               pkgs.push(pkg);
 
-               getIPv6Routes: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'routes',
-                       expect: { routes: [ ] }
-               }),
+                       this.init();
 
-               getARPTable: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'arp_table',
-                       expect: { entries: [ ] }
-               }),
+                       return this.load(pkgs);
+               },
 
-               getInterfaceStatus: _luci2.rpc.declare({
-                       object: 'network.interface',
-                       method: 'status',
-                       params: [ 'interface' ],
-                       expect: { '': { } },
-                       filter: function(data, params) {
-                               data['interface'] = params['interface'];
-                               data['l2_device'] = data['device'];
-                               delete data['device'];
-                               return data;
-                       }
-               }),
+               _reorder: function()
+               {
+                       var v = this.state.values;
+                       var n = this.state.creates;
+                       var r = this.state.reorder;
 
-               getDeviceStatus: _luci2.rpc.declare({
-                       object: 'network.device',
-                       method: 'status',
-                       params: [ 'name' ],
-                       expect: { '': { } },
-                       filter: function(data, params) {
-                               data['device'] = params['name'];
-                               return data;
-                       }
-               }),
+                       if ($.isEmptyObject(r))
+                               return _luci2.deferrable();
 
-               getConntrackCount: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'conntrack_count',
-                       expect: { '': { count: 0, limit: 0 } }
-               }),
+                       _luci2.rpc.batch();
 
-               listSwitchNames: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'switch_list',
-                       expect: { switches: [ ] }
-               }),
+                       /*
+                        gather all created and existing sections, sort them according
+                        to their index value and issue an uci order call
+                       */
+                       for (var c in r)
+                       {
+                               var o = [ ];
 
-               getSwitchInfo: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'switch_info',
-                       params: [ 'switch' ],
-                       expect: { info: { } },
-                       filter: function(data, params) {
-                               data['attrs']      = data['switch'];
-                               data['vlan_attrs'] = data['vlan'];
-                               data['port_attrs'] = data['port'];
-                               data['switch']     = params['switch'];
+                               if (n && n[c])
+                                       for (var s in n[c])
+                                               o.push(n[c][s]);
 
-                               delete data.vlan;
-                               delete data.port;
+                               for (var s in v[c])
+                                       o.push(v[c][s]);
 
-                               return data;
+                               if (o.length > 0)
+                               {
+                                       o.sort(function(a, b) {
+                                               return (a['.index'] - b['.index']);
+                                       });
+
+                                       var sids = [ ];
+
+                                       for (var i = 0; i < o.length; i++)
+                                               sids.push(o[i]['.name']);
+
+                                       this._order(c, sids);
+                               }
                        }
-               }),
 
-               getSwitchStatus: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'switch_status',
-                       params: [ 'switch' ],
-                       expect: { ports: [ ] }
-               }),
+                       this.state.reorder = { };
+                       return _luci2.rpc.flush();
+               },
 
+               swap: function(conf, sid1, sid2)
+               {
+                       var s1 = this.get(conf, sid1);
+                       var s2 = this.get(conf, sid2);
+                       var n1 = s1 ? s1['.index'] : NaN;
+                       var n2 = s2 ? s2['.index'] : NaN;
 
-               runPing: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'ping',
-                       params: [ 'data' ],
-                       expect: { '': { code: -1 } }
-               }),
+                       if (isNaN(n1) || isNaN(n2))
+                               return false;
 
-               runPing6: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'ping6',
-                       params: [ 'data' ],
-                       expect: { '': { code: -1 } }
+                       s1['.index'] = n2;
+                       s2['.index'] = n1;
+
+                       this.state.reorder[conf] = true;
+
+                       return true;
+               },
+
+               save: function()
+               {
+                       _luci2.rpc.batch();
+
+                       var self = this;
+                       var snew = [ ];
+
+                       if (self.state.creates)
+                               for (var c in self.state.creates)
+                                       for (var s in self.state.creates[c])
+                                       {
+                                               var r = {
+                                                       config: c,
+                                                       values: { }
+                                               };
+
+                                               for (var k in self.state.creates[c][s])
+                                               {
+                                                       if (k == '.type')
+                                                               r.type = self.state.creates[c][s][k];
+                                                       else if (k == '.create')
+                                                               r.name = self.state.creates[c][s][k];
+                                                       else if (k.charAt(0) != '.')
+                                                               r.values[k] = self.state.creates[c][s][k];
+                                               }
+
+                                               snew.push(self.state.creates[c][s]);
+
+                                               self._add(r.config, r.type, r.name, r.values);
+                                       }
+
+                       if (self.state.changes)
+                               for (var c in self.state.changes)
+                                       for (var s in self.state.changes[c])
+                                               self._set(c, s, self.state.changes[c][s]);
+
+                       if (self.state.deletes)
+                               for (var c in self.state.deletes)
+                                       for (var s in self.state.deletes[c])
+                                       {
+                                               var o = self.state.deletes[c][s];
+                                               self._delete(c, s, (o === true) ? undefined : o);
+                                       }
+
+                       return _luci2.rpc.flush().then(function(responses) {
+                               /*
+                                array "snew" holds references to the created uci sections,
+                                use it to assign the returned names of the new sections
+                               */
+                               for (var i = 0; i < snew.length; i++)
+                                       snew[i]['.name'] = responses[i];
+
+                               return self._reorder();
+                       });
+               },
+
+               _apply: _luci2.rpc.declare({
+                       object: 'uci',
+                       method: 'apply',
+                       params: [ 'timeout', 'rollback' ]
                }),
 
-               runTraceroute: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'traceroute',
-                       params: [ 'data' ],
-                       expect: { '': { code: -1 } }
+               _confirm: _luci2.rpc.declare({
+                       object: 'uci',
+                       method: 'confirm'
                }),
 
-               runTraceroute6: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'traceroute6',
-                       params: [ 'data' ],
-                       expect: { '': { code: -1 } }
+               apply: function(timeout)
+               {
+                       var self = this;
+                       var date = new Date();
+                       var deferred = $.Deferred();
+
+                       if (typeof(timeout) != 'number' || timeout < 1)
+                               timeout = 10;
+
+                       self._apply(timeout, true).then(function(rv) {
+                               if (rv != 0)
+                               {
+                                       deferred.rejectWith(self, [ rv ]);
+                                       return;
+                               }
+
+                               var try_deadline = date.getTime() + 1000 * timeout;
+                               var try_confirm = function()
+                               {
+                                       return self._confirm().then(function(rv) {
+                                               if (rv != 0)
+                                               {
+                                                       if (date.getTime() < try_deadline)
+                                                               window.setTimeout(try_confirm, 250);
+                                                       else
+                                                               deferred.rejectWith(self, [ rv ]);
+
+                                                       return;
+                                               }
+
+                                               deferred.resolveWith(self, [ rv ]);
+                                       });
+                               };
+
+                               window.setTimeout(try_confirm, 1000);
+                       });
+
+                       return deferred;
+               },
+
+               changes: _luci2.rpc.declare({
+                       object: 'uci',
+                       method: 'changes',
+                       expect: { changes: { } }
                }),
 
-               runNslookup: _luci2.rpc.declare({
-                       object: 'luci2.network',
-                       method: 'nslookup',
-                       params: [ 'data' ],
-                       expect: { '': { code: -1 } }
-               })
-       };
+               readable: function(conf)
+               {
+                       return _luci2.session.hasACL('uci', conf, 'read');
+               },
+
+               writable: function(conf)
+               {
+                       return _luci2.session.hasACL('uci', conf, 'write');
+               }
+       });
+
+       this.uci = new this.UCIContext();
 
        this.wireless = {
                listDeviceNames: _luci2.rpc.declare({
@@ -1173,100 +1303,1564 @@ function LuCI2()
                }
        };
 
-       this.system = {
-               getSystemInfo: _luci2.rpc.declare({
-                       object: 'system',
-                       method: 'info',
-                       expect: { '': { } }
-               }),
+       this.firewall = {
+               getZoneColor: function(zone)
+               {
+                       if ($.isPlainObject(zone))
+                               zone = zone.name;
 
-               getBoardInfo: _luci2.rpc.declare({
-                       object: 'system',
-                       method: 'board',
-                       expect: { '': { } }
-               }),
+                       if (zone == 'lan')
+                               return '#90f090';
+                       else if (zone == 'wan')
+                               return '#f09090';
 
-               getDiskInfo: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'diskfree',
-                       expect: { '': { } }
-               }),
+                       for (var i = 0, hash = 0;
+                                i < zone.length;
+                                hash = zone.charCodeAt(i++) + ((hash << 5) - hash));
 
-               getInfo: function(cb)
+                       for (var i = 0, color = '#';
+                                i < 3;
+                                color += ('00' + ((hash >> i++ * 8) & 0xFF).tostring(16)).slice(-2));
+
+                       return color;
+               },
+
+               findZoneByNetwork: function(network)
                {
-                       _luci2.rpc.batch();
+                       var self = this;
+                       var zone = undefined;
 
-                       this.getSystemInfo();
-                       this.getBoardInfo();
-                       this.getDiskInfo();
+                       return _luci2.uci.sections('firewall', 'zone', function(z) {
+                               if (!z.name || !z.network)
+                                       return;
 
-                       return _luci2.rpc.flush().then(function(info) {
-                               var rv = { };
+                               if (!$.isArray(z.network))
+                                       z.network = z.network.split(/\s+/);
 
-                               $.extend(rv, info[0]);
-                               $.extend(rv, info[1]);
-                               $.extend(rv, info[2]);
+                               for (var i = 0; i < z.network.length; i++)
+                               {
+                                       if (z.network[i] == network)
+                                       {
+                                               zone = z;
+                                               break;
+                                       }
+                               }
+                       }).then(function() {
+                               if (zone)
+                                       zone.color = self.getZoneColor(zone);
 
-                               return rv;
+                               return zone;
                        });
-               },
+               }
+       };
 
-               getProcessList: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'process_list',
-                       expect: { processes: [ ] },
-                       filter: function(data) {
-                               data.sort(function(a, b) { return a.pid - b.pid });
-                               return data;
-                       }
-               }),
+       this.NetworkModel = {
+               _device_blacklist: [
+                       /^gre[0-9]+$/,
+                       /^gretap[0-9]+$/,
+                       /^ifb[0-9]+$/,
+                       /^ip6tnl[0-9]+$/,
+                       /^sit[0-9]+$/,
+                       /^wlan[0-9]+\.sta[0-9]+$/
+               ],
+
+               _cache_functions: [
+                       'protolist', 0, _luci2.rpc.declare({
+                               object: 'network',
+                               method: 'get_proto_handlers',
+                               expect: { '': { } }
+                       }),
+                       'ifstate', 1, _luci2.rpc.declare({
+                               object: 'network.interface',
+                               method: 'dump',
+                               expect: { 'interface': [ ] }
+                       }),
+                       'devstate', 2, _luci2.rpc.declare({
+                               object: 'network.device',
+                               method: 'status',
+                               expect: { '': { } }
+                       }),
+                       'wifistate', 0, _luci2.rpc.declare({
+                               object: 'network.wireless',
+                               method: 'status',
+                               expect: { '': { } }
+                       }),
+                       'bwstate', 2, _luci2.rpc.declare({
+                               object: 'luci2.network.bwmon',
+                               method: 'statistics',
+                               expect: { 'statistics': { } }
+                       }),
+                       'devlist', 2, _luci2.rpc.declare({
+                               object: 'luci2.network',
+                               method: 'device_list',
+                               expect: { 'devices': [ ] }
+                       }),
+                       'swlist', 0, _luci2.rpc.declare({
+                               object: 'luci2.network',
+                               method: 'switch_list',
+                               expect: { 'switches': [ ] }
+                       })
+               ],
+
+               _fetch_protocol: function(proto)
+               {
+                       var url = _luci2.globals.resource + '/proto/' + proto + '.js';
+                       var self = _luci2.NetworkModel;
+
+                       var def = $.Deferred();
+
+                       $.ajax(url, {
+                               method: 'GET',
+                               cache: true,
+                               dataType: 'text'
+                       }).then(function(data) {
+                               try {
+                                       var protoConstructorSource = (
+                                               '(function(L, $) { ' +
+                                                       'return %s' +
+                                               '})(_luci2, $);\n\n' +
+                                               '//@ sourceURL=%s'
+                                       ).format(data, url);
 
-               getSystemLog: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'syslog',
-                       expect: { log: '' }
-               }),
+                                       var protoClass = eval(protoConstructorSource);
 
-               getKernelLog: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'dmesg',
-                       expect: { log: '' }
-               }),
+                                       self._protos[proto] = new protoClass();
+                               }
+                               catch(e) {
+                                       alert('Unable to instantiate proto "%s": %s'.format(url, e));
+                               };
 
-               getZoneInfo: function(cb)
+                               def.resolve();
+                       }).fail(function() {
+                               def.resolve();
+                       });
+
+                       return def;
+               },
+
+               _fetch_protocols: function()
                {
-                       return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
+                       var self = _luci2.NetworkModel;
+                       var deferreds = [ ];
+
+                       for (var proto in self._cache.protolist)
+                               deferreds.push(self._fetch_protocol(proto));
+
+                       return $.when.apply($, deferreds);
                },
 
-               sendSignal: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'process_signal',
-                       params: [ 'pid', 'signal' ],
-                       filter: function(data) {
-                               return (data == 0);
-                       }
+               _fetch_swstate: _luci2.rpc.declare({
+                       object: 'luci2.network',
+                       method: 'switch_info',
+                       params: [ 'switch' ],
+                       expect: { 'info': { } }
                }),
 
-               initList: _luci2.rpc.declare({
-                       object: 'luci2.system',
-                       method: 'init_list',
-                       expect: { initscripts: [ ] },
-                       filter: function(data) {
-                               data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
-                               return data;
-                       }
-               }),
+               _fetch_swstate_cb: function(responses) {
+                       var self = _luci2.NetworkModel;
+                       var swlist = self._cache.swlist;
+                       var swstate = self._cache.swstate = { };
 
-               initEnabled: function(init, cb)
+                       for (var i = 0; i < responses.length; i++)
+                               swstate[swlist[i]] = responses[i];
+               },
+
+               _fetch_cache_cb: function(level)
                {
-                       return this.initList().then(function(list) {
-                               for (var i = 0; i < list.length; i++)
-                                       if (list[i].name == init)
-                                               return !!list[i].enabled;
+                       var self = _luci2.NetworkModel;
+                       var name = '_fetch_cache_cb_' + level;
 
-                               return false;
-                       });
-               },
+                       return self[name] || (
+                               self[name] = function(responses)
+                               {
+                                       for (var i = 0; i < self._cache_functions.length; i += 3)
+                                               if (!level || self._cache_functions[i + 1] == level)
+                                                       self._cache[self._cache_functions[i]] = responses.shift();
+
+                                       if (!level)
+                                       {
+                                               _luci2.rpc.batch();
+
+                                               for (var i = 0; i < self._cache.swlist.length; i++)
+                                                       self._fetch_swstate(self._cache.swlist[i]);
+
+                                               return _luci2.rpc.flush().then(self._fetch_swstate_cb);
+                                       }
+
+                                       return _luci2.deferrable();
+                               }
+                       );
+               },
+
+               _fetch_cache: function(level)
+               {
+                       var self = _luci2.NetworkModel;
+
+                       return _luci2.uci.load(['network', 'wireless']).then(function() {
+                               _luci2.rpc.batch();
+
+                               for (var i = 0; i < self._cache_functions.length; i += 3)
+                                       if (!level || self._cache_functions[i + 1] == level)
+                                               self._cache_functions[i + 2]();
+
+                               return _luci2.rpc.flush().then(self._fetch_cache_cb(level || 0));
+                       });
+               },
+
+               _get: function(pkg, sid, key)
+               {
+                       return _luci2.uci.get(pkg, sid, key);
+               },
+
+               _set: function(pkg, sid, key, val)
+               {
+                       return _luci2.uci.set(pkg, sid, key, val);
+               },
+
+               _is_blacklisted: function(dev)
+               {
+                       for (var i = 0; i < this._device_blacklist.length; i++)
+                               if (dev.match(this._device_blacklist[i]))
+                                       return true;
+
+                       return false;
+               },
+
+               _sort_devices: function(a, b)
+               {
+                       if (a.options.kind < b.options.kind)
+                               return -1;
+                       else if (a.options.kind > b.options.kind)
+                               return 1;
+
+                       if (a.options.name < b.options.name)
+                               return -1;
+                       else if (a.options.name > b.options.name)
+                               return 1;
+
+                       return 0;
+               },
+
+               _get_dev: function(ifname)
+               {
+                       var alias = (ifname.charAt(0) == '@');
+                       return this._devs[ifname] || (
+                               this._devs[ifname] = {
+                                       ifname:  ifname,
+                                       kind:    alias ? 'alias' : 'ethernet',
+                                       type:    alias ? 0 : 1,
+                                       up:      false,
+                                       changed: { }
+                               }
+                       );
+               },
+
+               _get_iface: function(name)
+               {
+                       return this._ifaces[name] || (
+                               this._ifaces[name] = {
+                                       name:    name,
+                                       proto:   this._protos.none,
+                                       changed: { }
+                               }
+                       );
+               },
+
+               _parse_devices: function()
+               {
+                       var self = _luci2.NetworkModel;
+                       var wificount = { };
+
+                       for (var ifname in self._cache.devstate)
+                       {
+                               if (self._is_blacklisted(ifname))
+                                       continue;
+
+                               var dev = self._cache.devstate[ifname];
+                               var entry = self._get_dev(ifname);
+
+                               entry.up = dev.up;
+
+                               switch (dev.type)
+                               {
+                               case 'IP tunnel':
+                                       entry.kind = 'tunnel';
+                                       break;
+
+                               case 'Bridge':
+                                       entry.kind = 'bridge';
+                                       //entry.ports = dev['bridge-members'].sort();
+                                       break;
+                               }
+                       }
+
+                       for (var i = 0; i < self._cache.devlist.length; i++)
+                       {
+                               var dev = self._cache.devlist[i];
+
+                               if (self._is_blacklisted(dev.device))
+                                       continue;
+
+                               var entry = self._get_dev(dev.device);
+
+                               entry.up   = dev.is_up;
+                               entry.type = dev.type;
+
+                               switch (dev.type)
+                               {
+                               case 1: /* Ethernet */
+                                       if (dev.is_bridge)
+                                               entry.kind = 'bridge';
+                                       else if (dev.is_tuntap)
+                                               entry.kind = 'tunnel';
+                                       else if (dev.is_wireless)
+                                               entry.kind = 'wifi';
+                                       break;
+
+                               case 512: /* PPP */
+                               case 768: /* IP-IP Tunnel */
+                               case 769: /* IP6-IP6 Tunnel */
+                               case 776: /* IPv6-in-IPv4 */
+                               case 778: /* GRE over IP */
+                                       entry.kind = 'tunnel';
+                                       break;
+                               }
+                       }
+
+                       var net = _luci2.uci.sections('network');
+                       for (var i = 0; i < net.length; i++)
+                       {
+                               var s = net[i];
+                               var sid = s['.name'];
+
+                               if (s['.type'] == 'device' && s.name)
+                               {
+                                       var entry = self._get_dev(s.name);
+
+                                       switch (s.type)
+                                       {
+                                       case 'macvlan':
+                                       case 'tunnel':
+                                               entry.kind = 'tunnel';
+                                               break;
+                                       }
+
+                                       entry.sid = sid;
+                               }
+                               else if (s['.type'] == 'interface' && !s['.anonymous'] && s.ifname)
+                               {
+                                       var ifnames = _luci2.toArray(s.ifname);
+
+                                       for (var j = 0; j < ifnames.length; j++)
+                                               self._get_dev(ifnames[j]);
+
+                                       if (s['.name'] != 'loopback')
+                                       {
+                                               var entry = self._get_dev('@%s'.format(s['.name']));
+
+                                               entry.type = 0;
+                                               entry.kind = 'alias';
+                                               entry.sid  = sid;
+                                       }
+                               }
+                               else if (s['.type'] == 'switch_vlan' && s.device)
+                               {
+                                       var sw = self._cache.swstate[s.device];
+                                       var vid = parseInt(s.vid || s.vlan);
+                                       var ports = _luci2.toArray(s.ports);
+
+                                       if (!sw || !ports.length || isNaN(vid))
+                                               continue;
+
+                                       var ifname = undefined;
+
+                                       for (var j = 0; j < ports.length; j++)
+                                       {
+                                               var port = parseInt(ports[j]);
+                                               var tag = (ports[j].replace(/[^tu]/g, '') == 't');
+
+                                               if (port == sw.cpu_port)
+                                               {
+                                                       // XXX: need a way to map switch to netdev
+                                                       if (tag)
+                                                               ifname = 'eth0.%d'.format(vid);
+                                                       else
+                                                               ifname = 'eth0';
+
+                                                       break;
+                                               }
+                                       }
+
+                                       if (!ifname)
+                                               continue;
+
+                                       var entry = self._get_dev(ifname);
+
+                                       entry.kind = 'vlan';
+                                       entry.sid  = sid;
+                                       entry.vsw  = sw;
+                                       entry.vid  = vid;
+                               }
+                       }
+
+                       var wifi = _luci2.uci.sections('wireless');
+                       for (var i = 0; i < wifi.length; i++)
+                       {
+                               var s = wifi[i];
+                               var sid = s['.name'];
+
+                               if (s['.type'] == 'wifi-iface' && s.device)
+                               {
+                                       var r = parseInt(s.device.replace(/^[^0-9]+/, ''));
+                                       var n = wificount[s.device] = (wificount[s.device] || 0) + 1;
+                                       var id = 'radio%d.network%d'.format(r, n);
+                                       var ifname = id;
+
+                                       if (self._cache.wifistate[s.device])
+                                       {
+                                               var ifcs = self._cache.wifistate[s.device].interfaces;
+                                               for (var ifc in ifcs)
+                                               {
+                                                       if (ifcs[ifc].section == sid)
+                                                       {
+                                                               ifname = ifcs[ifc].ifname;
+                                                               break;
+                                                       }
+                                               }
+                                       }
+
+                                       var entry = self._get_dev(ifname);
+
+                                       entry.kind   = 'wifi';
+                                       entry.sid    = sid;
+                                       entry.wid    = id;
+                                       entry.wdev   = s.device;
+                                       entry.wmode  = s.mode;
+                                       entry.wssid  = s.ssid;
+                                       entry.wbssid = s.bssid;
+                               }
+                       }
+
+                       for (var i = 0; i < net.length; i++)
+                       {
+                               var s = net[i];
+                               var sid = s['.name'];
+
+                               if (s['.type'] == 'interface' && !s['.anonymous'] && s.type == 'bridge')
+                               {
+                                       var ifnames = _luci2.toArray(s.ifname);
+
+                                       for (var ifname in self._devs)
+                                       {
+                                               var dev = self._devs[ifname];
+
+                                               if (dev.kind != 'wifi')
+                                                       continue;
+
+                                               var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
+                                               if ($.inArray(sid, wnets) > -1)
+                                                       ifnames.push(ifname);
+                                       }
+
+                                       entry = self._get_dev('br-%s'.format(s['.name']));
+                                       entry.type  = 1;
+                                       entry.kind  = 'bridge';
+                                       entry.sid   = sid;
+                                       entry.ports = ifnames.sort();
+                               }
+                       }
+               },
+
+               _parse_interfaces: function()
+               {
+                       var self = _luci2.NetworkModel;
+                       var net = _luci2.uci.sections('network');
+
+                       for (var i = 0; i < net.length; i++)
+                       {
+                               var s = net[i];
+                               var sid = s['.name'];
+
+                               if (s['.type'] == 'interface' && !s['.anonymous'] && s.proto)
+                               {
+                                       var entry = self._get_iface(s['.name']);
+                                       var proto = self._protos[s.proto] || self._protos.none;
+
+                                       var l3dev = undefined;
+                                       var l2dev = undefined;
+
+                                       var ifnames = _luci2.toArray(s.ifname);
+
+                                       for (var ifname in self._devs)
+                                       {
+                                               var dev = self._devs[ifname];
+
+                                               if (dev.kind != 'wifi')
+                                                       continue;
+
+                                               var wnets = _luci2.toArray(_luci2.uci.get('wireless', dev.sid, 'network'));
+                                               if ($.inArray(entry.name, wnets) > -1)
+                                                       ifnames.push(ifname);
+                                       }
+
+                                       if (proto.virtual)
+                                               l3dev = '%s-%s'.format(s.proto, entry.name);
+                                       else if (s.type == 'bridge')
+                                               l3dev = 'br-%s'.format(entry.name);
+                                       else
+                                               l3dev = ifnames[0];
+
+                                       if (!proto.virtual && s.type == 'bridge')
+                                               l2dev = 'br-%s'.format(entry.name);
+                                       else if (!proto.virtual)
+                                               l2dev = ifnames[0];
+
+                                       entry.proto = proto;
+                                       entry.sid   = sid;
+                                       entry.l3dev = l3dev;
+                                       entry.l2dev = l2dev;
+                               }
+                       }
+
+                       for (var i = 0; i < self._cache.ifstate.length; i++)
+                       {
+                               var iface = self._cache.ifstate[i];
+                               var entry = self._get_iface(iface['interface']);
+                               var proto = self._protos[iface.proto] || self._protos.none;
+
+                               /* this is a virtual interface, either deleted from config but
+                                  not applied yet or set up from external tools (6rd) */
+                               if (!entry.sid)
+                               {
+                                       entry.proto = proto;
+                                       entry.l2dev = iface.device;
+                                       entry.l3dev = iface.l3_device;
+                               }
+                       }
+               },
+
+               init: function()
+               {
+                       var self = this;
+
+                       if (self._cache)
+                               return _luci2.deferrable();
+
+                       self._cache  = { };
+                       self._devs   = { };
+                       self._ifaces = { };
+                       self._protos = { };
+
+                       return self._fetch_cache()
+                               .then(self._fetch_protocols)
+                               .then(self._parse_devices)
+                               .then(self._parse_interfaces);
+               },
+
+               update: function()
+               {
+                       delete this._cache;
+                       return this.init();
+               },
+
+               refreshInterfaceStatus: function()
+               {
+                       return this._fetch_cache(1).then(this._parse_interfaces);
+               },
+
+               refreshDeviceStatus: function()
+               {
+                       return this._fetch_cache(2).then(this._parse_devices);
+               },
+
+               refreshStatus: function()
+               {
+                       return this._fetch_cache(1)
+                               .then(this._fetch_cache(2))
+                               .then(this._parse_devices)
+                               .then(this._parse_interfaces);
+               },
+
+               getDevices: function()
+               {
+                       var devs = [ ];
+
+                       for (var ifname in this._devs)
+                               if (ifname != 'lo')
+                                       devs.push(new _luci2.NetworkModel.Device(this._devs[ifname]));
+
+                       return devs.sort(this._sort_devices);
+               },
+
+               getDeviceByInterface: function(iface)
+               {
+                       if (iface instanceof _luci2.NetworkModel.Interface)
+                               iface = iface.name();
+
+                       if (this._ifaces[iface])
+                               return this.getDevice(this._ifaces[iface].l3dev) ||
+                                      this.getDevice(this._ifaces[iface].l2dev);
+
+                       return undefined;
+               },
+
+               getDevice: function(ifname)
+               {
+                       if (this._devs[ifname])
+                               return new _luci2.NetworkModel.Device(this._devs[ifname]);
+
+                       return undefined;
+               },
+
+               createDevice: function(name)
+               {
+                       return new _luci2.NetworkModel.Device(this._get_dev(name));
+               },
+
+               getInterfaces: function()
+               {
+                       var ifaces = [ ];
+
+                       for (var name in this._ifaces)
+                               if (name != 'loopback')
+                                       ifaces.push(this.getInterface(name));
+
+                       ifaces.sort(function(a, b) {
+                               if (a.name() < b.name())
+                                       return -1;
+                               else if (a.name() > b.name())
+                                       return 1;
+                               else
+                                       return 0;
+                       });
+
+                       return ifaces;
+               },
+
+               getInterfacesByDevice: function(dev)
+               {
+                       var ifaces = [ ];
+
+                       if (dev instanceof _luci2.NetworkModel.Device)
+                               dev = dev.name();
+
+                       for (var name in this._ifaces)
+                       {
+                               var iface = this._ifaces[name];
+                               if (iface.l2dev == dev || iface.l3dev == dev)
+                                       ifaces.push(this.getInterface(name));
+                       }
+
+                       ifaces.sort(function(a, b) {
+                               if (a.name() < b.name())
+                                       return -1;
+                               else if (a.name() > b.name())
+                                       return 1;
+                               else
+                                       return 0;
+                       });
+
+                       return ifaces;
+               },
+
+               getInterface: function(iface)
+               {
+                       if (this._ifaces[iface])
+                               return new _luci2.NetworkModel.Interface(this._ifaces[iface]);
+
+                       return undefined;
+               },
+
+               getProtocols: function()
+               {
+                       var rv = [ ];
+
+                       for (var proto in this._protos)
+                       {
+                               var pr = this._protos[proto];
+
+                               rv.push({
+                                       name:        proto,
+                                       description: pr.description,
+                                       virtual:     pr.virtual,
+                                       tunnel:      pr.tunnel
+                               });
+                       }
+
+                       return rv.sort(function(a, b) {
+                               if (a.name < b.name)
+                                       return -1;
+                               else if (a.name > b.name)
+                                       return 1;
+                               else
+                                       return 0;
+                       });
+               },
+
+               _find_wan: function(ipaddr)
+               {
+                       for (var i = 0; i < this._cache.ifstate.length; i++)
+                       {
+                               var ifstate = this._cache.ifstate[i];
+
+                               if (!ifstate.route)
+                                       continue;
+
+                               for (var j = 0; j < ifstate.route.length; j++)
+                                       if (ifstate.route[j].mask == 0 &&
+                                           ifstate.route[j].target == ipaddr &&
+                                           typeof(ifstate.route[j].table) == 'undefined')
+                                       {
+                                               return this.getInterface(ifstate['interface']);
+                                       }
+                       }
+
+                       return undefined;
+               },
+
+               findWAN: function()
+               {
+                       return this._find_wan('0.0.0.0');
+               },
+
+               findWAN6: function()
+               {
+                       return this._find_wan('::');
+               },
+
+               resolveAlias: function(ifname)
+               {
+                       if (ifname instanceof _luci2.NetworkModel.Device)
+                               ifname = ifname.name();
+
+                       var dev = this._devs[ifname];
+                       var seen = { };
+
+                       while (dev && dev.kind == 'alias')
+                       {
+                               // loop
+                               if (seen[dev.ifname])
+                                       return undefined;
+
+                               var ifc = this._ifaces[dev.sid];
+
+                               seen[dev.ifname] = true;
+                               dev = ifc ? this._devs[ifc.l3dev] : undefined;
+                       }
+
+                       return dev ? this.getDevice(dev.ifname) : undefined;
+               }
+       };
+
+       this.NetworkModel.Device = Class.extend({
+               _wifi_modes: {
+                       ap: _luci2.tr('Master'),
+                       sta: _luci2.tr('Client'),
+                       adhoc: _luci2.tr('Ad-Hoc'),
+                       monitor: _luci2.tr('Monitor'),
+                       wds: _luci2.tr('Static WDS')
+               },
+
+               _status: function(key)
+               {
+                       var s = _luci2.NetworkModel._cache.devstate[this.options.ifname];
+
+                       if (s)
+                               return key ? s[key] : s;
+
+                       return undefined;
+               },
+
+               get: function(key)
+               {
+                       var sid = this.options.sid;
+                       var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
+                       return _luci2.NetworkModel._get(pkg, sid, key);
+               },
+
+               set: function(key, val)
+               {
+                       var sid = this.options.sid;
+                       var pkg = (this.options.kind == 'wifi') ? 'wireless' : 'network';
+                       return _luci2.NetworkModel._set(pkg, sid, key, val);
+               },
+
+               init: function()
+               {
+                       if (typeof(this.options.type) == 'undefined')
+                               this.options.type = 1;
+
+                       if (typeof(this.options.kind) == 'undefined')
+                               this.options.kind = 'ethernet';
+
+                       if (typeof(this.options.networks) == 'undefined')
+                               this.options.networks = [ ];
+               },
+
+               name: function()
+               {
+                       return this.options.ifname;
+               },
+
+               description: function()
+               {
+                       switch (this.options.kind)
+                       {
+                       case 'alias':
+                               return _luci2.tr('Alias for network "%s"').format(this.options.ifname.substring(1));
+
+                       case 'bridge':
+                               return _luci2.tr('Network bridge');
+
+                       case 'ethernet':
+                               return _luci2.tr('Network device');
+
+                       case 'tunnel':
+                               switch (this.options.type)
+                               {
+                               case 1: /* tuntap */
+                                       return _luci2.tr('TAP device');
+
+                               case 512: /* PPP */
+                                       return _luci2.tr('PPP tunnel');
+
+                               case 768: /* IP-IP Tunnel */
+                                       return _luci2.tr('IP-in-IP tunnel');
+
+                               case 769: /* IP6-IP6 Tunnel */
+                                       return _luci2.tr('IPv6-in-IPv6 tunnel');
+
+                               case 776: /* IPv6-in-IPv4 */
+                                       return _luci2.tr('IPv6-over-IPv4 tunnel');
+                                       break;
+
+                               case 778: /* GRE over IP */
+                                       return _luci2.tr('GRE-over-IP tunnel');
+
+                               default:
+                                       return _luci2.tr('Tunnel device');
+                               }
+
+                       case 'vlan':
+                               return _luci2.tr('VLAN %d on %s').format(this.options.vid, this.options.vsw.model);
+
+                       case 'wifi':
+                               var o = this.options;
+                               return _luci2.trc('(Wifi-Mode) "(SSID)" on (radioX)', '%s "%h" on %s').format(
+                                       o.wmode ? this._wifi_modes[o.wmode] : _luci2.tr('Unknown mode'),
+                                       o.wssid || '?', o.wdev
+                               );
+                       }
+
+                       return _luci2.tr('Unknown device');
+               },
+
+               icon: function(up)
+               {
+                       var kind = this.options.kind;
+
+                       if (kind == 'alias')
+                               kind = 'ethernet';
+
+                       if (typeof(up) == 'undefined')
+                               up = this.isUp();
+
+                       return _luci2.globals.resource + '/icons/%s%s.png'.format(kind, up ? '' : '_disabled');
+               },
+
+               isUp: function()
+               {
+                       var l = _luci2.NetworkModel._cache.devlist;
+
+                       for (var i = 0; i < l.length; i++)
+                               if (l[i].device == this.options.ifname)
+                                       return (l[i].is_up === true);
+
+                       return false;
+               },
+
+               isAlias: function()
+               {
+                       return (this.options.kind == 'alias');
+               },
+
+               isBridge: function()
+               {
+                       return (this.options.kind == 'bridge');
+               },
+
+               isBridgeable: function()
+               {
+                       return (this.options.type == 1 && this.options.kind != 'bridge');
+               },
+
+               isWireless: function()
+               {
+                       return (this.options.kind == 'wifi');
+               },
+
+               isInNetwork: function(net)
+               {
+                       if (!(net instanceof _luci2.NetworkModel.Interface))
+                               net = _luci2.NetworkModel.getInterface(net);
+
+                       if (net)
+                       {
+                               if (net.options.l3dev == this.options.ifname ||
+                                   net.options.l2dev == this.options.ifname)
+                                       return true;
+
+                               var dev = _luci2.NetworkModel._devs[net.options.l2dev];
+                               if (dev && dev.kind == 'bridge' && dev.ports)
+                                       return ($.inArray(this.options.ifname, dev.ports) > -1);
+                       }
+
+                       return false;
+               },
+
+               getMTU: function()
+               {
+                       var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
+                       if (dev && !isNaN(dev.mtu))
+                               return dev.mtu;
+
+                       return undefined;
+               },
+
+               getMACAddress: function()
+               {
+                       if (this.options.type != 1)
+                               return undefined;
+
+                       var dev = _luci2.NetworkModel._cache.devstate[this.options.ifname];
+                       if (dev && dev.macaddr)
+                               return dev.macaddr.toUpperCase();
+
+                       return undefined;
+               },
+
+               getInterfaces: function()
+               {
+                       return _luci2.NetworkModel.getInterfacesByDevice(this.options.name);
+               },
+
+               getStatistics: function()
+               {
+                       var s = this._status('statistics') || { };
+                       return {
+                               rx_bytes: (s.rx_bytes || 0),
+                               tx_bytes: (s.tx_bytes || 0),
+                               rx_packets: (s.rx_packets || 0),
+                               tx_packets: (s.tx_packets || 0)
+                       };
+               },
+
+               getTrafficHistory: function()
+               {
+                       var def = new Array(120);
+
+                       for (var i = 0; i < 120; i++)
+                               def[i] = 0;
+
+                       var h = _luci2.NetworkModel._cache.bwstate[this.options.ifname] || { };
+                       return {
+                               rx_bytes: (h.rx_bytes || def),
+                               tx_bytes: (h.tx_bytes || def),
+                               rx_packets: (h.rx_packets || def),
+                               tx_packets: (h.tx_packets || def)
+                       };
+               },
+
+               removeFromInterface: function(iface)
+               {
+                       if (!(iface instanceof _luci2.NetworkModel.Interface))
+                               iface = _luci2.NetworkModel.getInterface(iface);
+
+                       if (!iface)
+                               return;
+
+                       var ifnames = _luci2.toArray(iface.get('ifname'));
+                       if ($.inArray(this.options.ifname, ifnames) > -1)
+                               iface.set('ifname', _luci2.filterArray(ifnames, this.options.ifname));
+
+                       if (this.options.kind != 'wifi')
+                               return;
+
+                       var networks = _luci2.toArray(this.get('network'));
+                       if ($.inArray(iface.name(), networks) > -1)
+                               this.set('network', _luci2.filterArray(networks, iface.name()));
+               },
+
+               attachToInterface: function(iface)
+               {
+                       if (!(iface instanceof _luci2.NetworkModel.Interface))
+                               iface = _luci2.NetworkModel.getInterface(iface);
+
+                       if (!iface)
+                               return;
+
+                       if (this.options.kind != 'wifi')
+                       {
+                               var ifnames = _luci2.toArray(iface.get('ifname'));
+                               if ($.inArray(this.options.ifname, ifnames) < 0)
+                               {
+                                       ifnames.push(this.options.ifname);
+                                       iface.set('ifname', (ifnames.length > 1) ? ifnames : ifnames[0]);
+                               }
+                       }
+                       else
+                       {
+                               var networks = _luci2.toArray(this.get('network'));
+                               if ($.inArray(iface.name(), networks) < 0)
+                               {
+                                       networks.push(iface.name());
+                                       this.set('network', (networks.length > 1) ? networks : networks[0]);
+                               }
+                       }
+               }
+       });
+
+       this.NetworkModel.Interface = Class.extend({
+               _status: function(key)
+               {
+                       var s = _luci2.NetworkModel._cache.ifstate;
+
+                       for (var i = 0; i < s.length; i++)
+                               if (s[i]['interface'] == this.options.name)
+                                       return key ? s[i][key] : s[i];
+
+                       return undefined;
+               },
+
+               get: function(key)
+               {
+                       return _luci2.NetworkModel._get('network', this.options.name, key);
+               },
+
+               set: function(key, val)
+               {
+                       return _luci2.NetworkModel._set('network', this.options.name, key, val);
+               },
+
+               name: function()
+               {
+                       return this.options.name;
+               },
+
+               protocol: function()
+               {
+                       return (this.get('proto') || 'none');
+               },
+
+               isUp: function()
+               {
+                       return (this._status('up') === true);
+               },
+
+               isVirtual: function()
+               {
+                       return (typeof(this.options.sid) != 'string');
+               },
+
+               getProtocol: function()
+               {
+                       var prname = this.get('proto') || 'none';
+                       return _luci2.NetworkModel._protos[prname] || _luci2.NetworkModel._protos.none;
+               },
+
+               getUptime: function()
+               {
+                       var uptime = this._status('uptime');
+                       return isNaN(uptime) ? 0 : uptime;
+               },
+
+               getDevice: function(resolveAlias)
+               {
+                       if (this.options.l3dev)
+                               return _luci2.NetworkModel.getDevice(this.options.l3dev);
+
+                       return undefined;
+               },
+
+               getPhysdev: function()
+               {
+                       if (this.options.l2dev)
+                               return _luci2.NetworkModel.getDevice(this.options.l2dev);
+
+                       return undefined;
+               },
+
+               getSubdevices: function()
+               {
+                       var rv = [ ];
+                       var dev = this.options.l2dev ?
+                               _luci2.NetworkModel._devs[this.options.l2dev] : undefined;
+
+                       if (dev && dev.kind == 'bridge' && dev.ports && dev.ports.length)
+                               for (var i = 0; i < dev.ports.length; i++)
+                                       rv.push(_luci2.NetworkModel.getDevice(dev.ports[i]));
+
+                       return rv;
+               },
+
+               getIPv4Addrs: function(mask)
+               {
+                       var rv = [ ];
+                       var addrs = this._status('ipv4-address');
+
+                       if (addrs)
+                               for (var i = 0; i < addrs.length; i++)
+                                       if (!mask)
+                                               rv.push(addrs[i].address);
+                                       else
+                                               rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
+
+                       return rv;
+               },
+
+               getIPv6Addrs: function(mask)
+               {
+                       var rv = [ ];
+                       var addrs;
+
+                       addrs = this._status('ipv6-address');
+
+                       if (addrs)
+                               for (var i = 0; i < addrs.length; i++)
+                                       if (!mask)
+                                               rv.push(addrs[i].address);
+                                       else
+                                               rv.push('%s/%d'.format(addrs[i].address, addrs[i].mask));
+
+                       addrs = this._status('ipv6-prefix-assignment');
+
+                       if (addrs)
+                               for (var i = 0; i < addrs.length; i++)
+                                       if (!mask)
+                                               rv.push('%s1'.format(addrs[i].address));
+                                       else
+                                               rv.push('%s1/%d'.format(addrs[i].address, addrs[i].mask));
+
+                       return rv;
+               },
+
+               getDNSAddrs: function()
+               {
+                       var rv = [ ];
+                       var addrs = this._status('dns-server');
+
+                       if (addrs)
+                               for (var i = 0; i < addrs.length; i++)
+                                       rv.push(addrs[i]);
+
+                       return rv;
+               },
+
+               getIPv4DNS: function()
+               {
+                       var rv = [ ];
+                       var dns = this._status('dns-server');
+
+                       if (dns)
+                               for (var i = 0; i < dns.length; i++)
+                                       if (dns[i].indexOf(':') == -1)
+                                               rv.push(dns[i]);
+
+                       return rv;
+               },
+
+               getIPv6DNS: function()
+               {
+                       var rv = [ ];
+                       var dns = this._status('dns-server');
+
+                       if (dns)
+                               for (var i = 0; i < dns.length; i++)
+                                       if (dns[i].indexOf(':') > -1)
+                                               rv.push(dns[i]);
+
+                       return rv;
+               },
+
+               getIPv4Gateway: function()
+               {
+                       var rt = this._status('route');
+
+                       if (rt)
+                               for (var i = 0; i < rt.length; i++)
+                                       if (rt[i].target == '0.0.0.0' && rt[i].mask == 0)
+                                               return rt[i].nexthop;
+
+                       return undefined;
+               },
+
+               getIPv6Gateway: function()
+               {
+                       var rt = this._status('route');
+
+                       if (rt)
+                               for (var i = 0; i < rt.length; i++)
+                                       if (rt[i].target == '::' && rt[i].mask == 0)
+                                               return rt[i].nexthop;
+
+                       return undefined;
+               },
+
+               getStatistics: function()
+               {
+                       var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
+                       return dev.getStatistics();
+               },
+
+               getTrafficHistory: function()
+               {
+                       var dev = this.getDevice() || new _luci2.NetworkModel.Device({});
+                       return dev.getTrafficHistory();
+               },
+
+               setDevices: function(devs)
+               {
+                       var dev = this.getPhysdev();
+                       var old_devs = [ ];
+                       var changed = false;
+
+                       if (dev && dev.isBridge())
+                               old_devs = this.getSubdevices();
+                       else if (dev)
+                               old_devs = [ dev ];
+
+                       if (old_devs.length != devs.length)
+                               changed = true;
+                       else
+                               for (var i = 0; i < old_devs.length; i++)
+                               {
+                                       var dev = devs[i];
+
+                                       if (dev instanceof _luci2.NetworkModel.Device)
+                                               dev = dev.name();
+
+                                       if (!dev || old_devs[i].name() != dev)
+                                       {
+                                               changed = true;
+                                               break;
+                                       }
+                               }
+
+                       if (changed)
+                       {
+                               for (var i = 0; i < old_devs.length; i++)
+                                       old_devs[i].removeFromInterface(this);
+
+                               for (var i = 0; i < devs.length; i++)
+                               {
+                                       var dev = devs[i];
+
+                                       if (!(dev instanceof _luci2.NetworkModel.Device))
+                                               dev = _luci2.NetworkModel.getDevice(dev);
+
+                                       if (dev)
+                                               dev.attachToInterface(this);
+                               }
+                       }
+               },
+
+               changeProtocol: function(proto)
+               {
+                       var pr = _luci2.NetworkModel._protos[proto];
+
+                       if (!pr)
+                               return;
+
+                       for (var opt in (this.get() || { }))
+                       {
+                               switch (opt)
+                               {
+                               case 'type':
+                               case 'ifname':
+                               case 'macaddr':
+                                       if (pr.virtual)
+                                               this.set(opt, undefined);
+                                       break;
+
+                               case 'auto':
+                               case 'mtu':
+                                       break;
+
+                               case 'proto':
+                                       this.set(opt, pr.protocol);
+                                       break;
+
+                               default:
+                                       this.set(opt, undefined);
+                                       break;
+                               }
+                       }
+               },
+
+               createForm: function(mapwidget)
+               {
+                       var self = this;
+                       var proto = self.getProtocol();
+                       var device = self.getDevice();
+
+                       if (!mapwidget)
+                               mapwidget = _luci2.cbi.Map;
+
+                       var map = new mapwidget('network', {
+                               caption:     _luci2.tr('Configure "%s"').format(self.name())
+                       });
+
+                       var section = map.section(_luci2.cbi.SingleSection, self.name(), {
+                               anonymous:   true
+                       });
+
+                       section.tab({
+                               id:      'general',
+                               caption: _luci2.tr('General Settings')
+                       });
+
+                       section.tab({
+                               id:      'advanced',
+                               caption: _luci2.tr('Advanced Settings')
+                       });
+
+                       section.tab({
+                               id:      'ipv6',
+                               caption: _luci2.tr('IPv6')
+                       });
+
+                       section.tab({
+                               id:      'physical',
+                               caption: _luci2.tr('Physical Settings')
+                       });
+
+
+                       section.taboption('general', _luci2.cbi.CheckboxValue, 'auto', {
+                               caption:     _luci2.tr('Start on boot'),
+                               optional:    true,
+                               initial:     true
+                       });
+
+                       var pr = section.taboption('general', _luci2.cbi.ListValue, 'proto', {
+                               caption:     _luci2.tr('Protocol')
+                       });
+
+                       pr.ucivalue = function(sid) {
+                               return self.get('proto') || 'none';
+                       };
+
+                       var ok = section.taboption('general', _luci2.cbi.ButtonValue, '_confirm', {
+                               caption:     _luci2.tr('Really switch?'),
+                               description: _luci2.tr('Changing the protocol will clear all configuration for this interface!'),
+                               text:        _luci2.tr('Change protocol')
+                       });
+
+                       ok.on('click', function(ev) {
+                               self.changeProtocol(pr.formvalue(ev.data.sid));
+                               self.createForm(mapwidget).show();
+                       });
+
+                       var protos = _luci2.NetworkModel.getProtocols();
+
+                       for (var i = 0; i < protos.length; i++)
+                               pr.value(protos[i].name, protos[i].description);
+
+                       proto.populateForm(section, self);
+
+                       if (!proto.virtual)
+                       {
+                               var br = section.taboption('physical', _luci2.cbi.CheckboxValue, 'type', {
+                                       caption:     _luci2.tr('Network bridge'),
+                                       description: _luci2.tr('Merges multiple devices into one logical bridge'),
+                                       optional:    true,
+                                       enabled:     'bridge',
+                                       disabled:    '',
+                                       initial:     ''
+                               });
+
+                               section.taboption('physical', _luci2.cbi.DeviceList, '__iface_multi', {
+                                       caption:     _luci2.tr('Devices'),
+                                       multiple:    true,
+                                       bridges:     false
+                               }).depends('type', true);
+
+                               section.taboption('physical', _luci2.cbi.DeviceList, '__iface_single', {
+                                       caption:     _luci2.tr('Device'),
+                                       multiple:    false,
+                                       bridges:     true
+                               }).depends('type', false);
+
+                               var mac = section.taboption('physical', _luci2.cbi.InputValue, 'macaddr', {
+                                       caption:     _luci2.tr('Override MAC'),
+                                       optional:    true,
+                                       placeholder: device ? device.getMACAddress() : undefined,
+                                       datatype:    'macaddr'
+                               })
+
+                               mac.ucivalue = function(sid)
+                               {
+                                       if (device)
+                                               return device.get('macaddr');
+
+                                       return this.callSuper('ucivalue', sid);
+                               };
+
+                               mac.save = function(sid)
+                               {
+                                       if (!this.changed(sid))
+                                               return false;
+
+                                       if (device)
+                                               device.set('macaddr', this.formvalue(sid));
+                                       else
+                                               this.callSuper('set', sid);
+
+                                       return true;
+                               };
+                       }
+
+                       section.taboption('physical', _luci2.cbi.InputValue, 'mtu', {
+                               caption:     _luci2.tr('Override MTU'),
+                               optional:    true,
+                               placeholder: device ? device.getMTU() : undefined,
+                               datatype:    'range(1, 9000)'
+                       });
+
+                       section.taboption('physical', _luci2.cbi.InputValue, 'metric', {
+                               caption:     _luci2.tr('Override Metric'),
+                               optional:    true,
+                               placeholder: 0,
+                               datatype:    'uinteger'
+                       });
+
+                       for (var field in section.fields)
+                       {
+                               switch (field)
+                               {
+                               case 'proto':
+                                       break;
+
+                               case '_confirm':
+                                       for (var i = 0; i < protos.length; i++)
+                                               if (protos[i].name != (this.get('proto') || 'none'))
+                                                       section.fields[field].depends('proto', protos[i].name);
+                                       break;
+
+                               default:
+                                       section.fields[field].depends('proto', this.get('proto') || 'none', true);
+                                       break;
+                               }
+                       }
+
+                       return map;
+               }
+       });
+
+       this.NetworkModel.Protocol = this.NetworkModel.Interface.extend({
+               description: '__unknown__',
+               tunnel:      false,
+               virtual:     false,
+
+               populateForm: function(section, iface)
+               {
+
+               }
+       });
+
+       this.system = {
+               getSystemInfo: _luci2.rpc.declare({
+                       object: 'system',
+                       method: 'info',
+                       expect: { '': { } }
+               }),
+
+               getBoardInfo: _luci2.rpc.declare({
+                       object: 'system',
+                       method: 'board',
+                       expect: { '': { } }
+               }),
+
+               getDiskInfo: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'diskfree',
+                       expect: { '': { } }
+               }),
+
+               getInfo: function(cb)
+               {
+                       _luci2.rpc.batch();
+
+                       this.getSystemInfo();
+                       this.getBoardInfo();
+                       this.getDiskInfo();
+
+                       return _luci2.rpc.flush().then(function(info) {
+                               var rv = { };
+
+                               $.extend(rv, info[0]);
+                               $.extend(rv, info[1]);
+                               $.extend(rv, info[2]);
+
+                               return rv;
+                       });
+               },
+
+               getProcessList: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'process_list',
+                       expect: { processes: [ ] },
+                       filter: function(data) {
+                               data.sort(function(a, b) { return a.pid - b.pid });
+                               return data;
+                       }
+               }),
+
+               getSystemLog: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'syslog',
+                       expect: { log: '' }
+               }),
+
+               getKernelLog: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'dmesg',
+                       expect: { log: '' }
+               }),
+
+               getZoneInfo: function(cb)
+               {
+                       return $.getJSON(_luci2.globals.resource + '/zoneinfo.json', cb);
+               },
+
+               sendSignal: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'process_signal',
+                       params: [ 'pid', 'signal' ],
+                       filter: function(data) {
+                               return (data == 0);
+                       }
+               }),
+
+               initList: _luci2.rpc.declare({
+                       object: 'luci2.system',
+                       method: 'init_list',
+                       expect: { initscripts: [ ] },
+                       filter: function(data) {
+                               data.sort(function(a, b) { return (a.start || 0) - (b.start || 0) });
+                               return data;
+                       }
+               }),
+
+               initEnabled: function(init, cb)
+               {
+                       return this.initList().then(function(list) {
+                               for (var i = 0; i < list.length; i++)
+                                       if (list[i].name == init)
+                                               return !!list[i].enabled;
+
+                               return false;
+                       });
+               },
 
                initRun: _luci2.rpc.declare({
                        object: 'luci2.system',
@@ -1560,6 +3154,41 @@ function LuCI2()
                                window.clearInterval(this._hearbeatInterval);
                                delete this._hearbeatInterval;
                        }
+               },
+
+
+               _acls: { },
+
+               _fetch_acls: _luci2.rpc.declare({
+                       object: 'session',
+                       method: 'access',
+                       expect: { '': { } }
+               }),
+
+               _fetch_acls_cb: function(acls)
+               {
+                       _luci2.session._acls = acls;
+               },
+
+               updateACLs: function()
+               {
+                       return _luci2.session._fetch_acls()
+                               .then(_luci2.session._fetch_acls_cb);
+               },
+
+               hasACL: function(scope, object, func)
+               {
+                       var acls = _luci2.session._acls;
+
+                       if (typeof(func) == 'undefined')
+                               return (acls && acls[scope] && acls[scope][object]);
+
+                       if (acls && acls[scope] && acls[scope][object])
+                               for (var i = 0; i < acls[scope][object].length; i++)
+                                       if (acls[scope][object][i] == func)
+                                               return true;
+
+                       return false;
                }
        };
 
@@ -1587,29 +3216,23 @@ function LuCI2()
 
                        var state = _luci2.ui._loading || (_luci2.ui._loading = {
                                modal: $('<div />')
-                                       .addClass('cbi-modal-loader')
-                                       .append($('<div />').text(_luci2.tr('Loading data...')))
+                                       .css('z-index', 2000)
+                                       .addClass('modal fade')
+                                       .append($('<div />')
+                                               .addClass('modal-dialog')
+                                               .append($('<div />')
+                                                       .addClass('modal-content luci2-modal-loader')
+                                                       .append($('<div />')
+                                                               .addClass('modal-body')
+                                                               .text(_luci2.tr('Loading data…')))))
                                        .appendTo(body)
+                                       .modal({
+                                               backdrop: 'static',
+                                               keyboard: false
+                                       })
                        });
 
-                       if (enable)
-                       {
-                               body.css('overflow', 'hidden');
-                               body.css('padding', 0);
-                               body.css('width', win.width());
-                               body.css('height', win.height());
-                               state.modal.css('width', win.width());
-                               state.modal.css('height', win.height());
-                               state.modal.show();
-                       }
-                       else
-                       {
-                               state.modal.hide();
-                               body.css('overflow', '');
-                               body.css('padding', '');
-                               body.css('width', '');
-                               body.css('height', '');
-                       }
+                       state.modal.modal(enable ? 'show' : 'hide');
                },
 
                dialog: function(title, content, options)
@@ -1619,26 +3242,23 @@ function LuCI2()
 
                        var state = _luci2.ui._dialog || (_luci2.ui._dialog = {
                                dialog: $('<div />')
-                                       .addClass('cbi-modal-dialog')
+                                       .addClass('modal fade')
                                        .append($('<div />')
+                                               .addClass('modal-dialog')
                                                .append($('<div />')
-                                                       .addClass('cbi-modal-dialog-header'))
-                                               .append($('<div />')
-                                                       .addClass('cbi-modal-dialog-body'))
-                                               .append($('<div />')
-                                                       .addClass('cbi-modal-dialog-footer')
-                                                       .append($('<button />')
-                                                               .addClass('cbi-button')
-                                                               .text(_luci2.tr('Close'))
-                                                               .click(function() {
-                                                                       $('body')
-                                                                               .css('overflow', '')
-                                                                               .css('padding', '')
-                                                                               .css('width', '')
-                                                                               .css('height', '');
-
-                                                                       $(this).parent().parent().parent().hide();
-                                                               }))))
+                                                       .addClass('modal-content')
+                                                       .append($('<div />')
+                                                               .addClass('modal-header')
+                                                               .append('<h4 />')
+                                                                       .addClass('modal-title'))
+                                                       .append($('<div />')
+                                                               .addClass('modal-body'))
+                                                       .append($('<div />')
+                                                               .addClass('modal-footer')
+                                                               .append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
+                                                                       .click(function() {
+                                                                               $(this).parents('div.modal').modal('hide');
+                                                                       })))))
                                        .appendTo(body)
                        });
 
@@ -1647,66 +3267,50 @@ function LuCI2()
 
                        if (title === false)
                        {
-                               body
-                                       .css('overflow', '')
-                                       .css('padding', '')
-                                       .css('width', '')
-                                       .css('height', '');
-
-                               state.dialog.hide();
+                               state.dialog.modal('hide');
 
-                               return;
+                               return state.dialog;
                        }
 
-                       var cnt = state.dialog.children().children('div.cbi-modal-dialog-body');
-                       var ftr = state.dialog.children().children('div.cbi-modal-dialog-footer');
+                       var cnt = state.dialog.children().children().children('div.modal-body');
+                       var ftr = state.dialog.children().children().children('div.modal-footer');
 
-                       ftr.empty();
+                       ftr.empty().show();
 
                        if (options.style == 'confirm')
                        {
-                               ftr.append($('<button />')
-                                       .addClass('cbi-button')
-                                       .text(_luci2.tr('Ok'))
+                               ftr.append(_luci2.ui.button(_luci2.tr('Ok'), 'primary')
                                        .click(options.confirm || function() { _luci2.ui.dialog(false) }));
 
-                               ftr.append($('<button />')
-                                       .addClass('cbi-button')
-                                       .text(_luci2.tr('Cancel'))
+                               ftr.append(_luci2.ui.button(_luci2.tr('Cancel'), 'default')
                                        .click(options.cancel || function() { _luci2.ui.dialog(false) }));
                        }
                        else if (options.style == 'close')
                        {
-                               ftr.append($('<button />')
-                                       .addClass('cbi-button')
-                                       .text(_luci2.tr('Close'))
+                               ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
                                        .click(options.close || function() { _luci2.ui.dialog(false) }));
                        }
                        else if (options.style == 'wait')
                        {
-                               ftr.append($('<button />')
-                                       .addClass('cbi-button')
-                                       .text(_luci2.tr('Close'))
+                               ftr.append(_luci2.ui.button(_luci2.tr('Close'), 'primary')
                                        .attr('disabled', true));
                        }
 
-                       state.dialog.find('div.cbi-modal-dialog-header').text(title);
-                       state.dialog.show();
+                       if (options.wide)
+                       {
+                               state.dialog.addClass('wide');
+                       }
+                       else
+                       {
+                               state.dialog.removeClass('wide');
+                       }
 
-                       cnt
-                               .css('max-height', Math.floor(win.height() * 0.70) + 'px')
-                               .empty()
-                               .append(content);
+                       state.dialog.find('h4:first').text(title);
+                       state.dialog.modal('show');
 
-                       state.dialog.children()
-                               .css('margin-top', -Math.floor(state.dialog.children().height() / 2) + 'px');
+                       cnt.empty().append(content);
 
-                       body.css('overflow', 'hidden');
-                       body.css('padding', 0);
-                       body.css('width', win.width());
-                       body.css('height', win.height());
-                       state.dialog.css('width', win.width());
-                       state.dialog.css('height', win.height());
+                       return state.dialog;
                },
 
                upload: function(title, content, options)
@@ -1730,11 +3334,12 @@ function LuCI2()
                                                .addClass('cbi-input-file'))
                                        .append($('<div />')
                                                .css('width', '100%')
-                                               .addClass('progressbar')
-                                               .addClass('intermediate')
+                                               .addClass('progress progress-striped active')
                                                .append($('<div />')
+                                                       .addClass('progress-bar')
                                                        .css('width', '100%')))
                                        .append($('<iframe />')
+                                               .addClass('pull-right')
                                                .attr('name', 'cbi-fileupload-frame')
                                                .css('width', '1px')
                                                .css('height', '1px')
@@ -1773,7 +3378,7 @@ function LuCI2()
 
                                confirm_cb: function() {
                                        var f = state.form.find('.cbi-input-file');
-                                       var b = state.form.find('.progressbar');
+                                       var b = state.form.find('.progress');
                                        var p = state.form.find('p');
 
                                        if (!f.val())
@@ -1790,7 +3395,7 @@ function LuCI2()
                                }
                        });
 
-                       state.form.find('.progressbar').hide();
+                       state.form.find('.progress').hide();
                        state.form.find('.cbi-input-file').val('').show();
                        state.form.find('p').text(content || _luci2.tr('Select the file to upload and press "%s" to proceed.').format(_luci2.tr('Ok')));
 
@@ -1894,7 +3499,7 @@ function LuCI2()
                                                                .attr('type', 'text')
                                                                .attr('name', 'username')
                                                                .attr('value', 'root')
-                                                               .addClass('cbi-input-text')
+                                                               .addClass('form-control')
                                                                .keypress(function(ev) {
                                                                        if (ev.which == 10 || ev.which == 13)
                                                                                state.confirm_cb();
@@ -1906,7 +3511,7 @@ function LuCI2()
                                                        .append($('<input />')
                                                                .attr('type', 'password')
                                                                .attr('name', 'password')
-                                                               .addClass('cbi-input-password')
+                                                               .addClass('form-control')
                                                                .keypress(function(ev) {
                                                                        if (ev.which == 10 || ev.which == 13)
                                                                                state.confirm_cb();
@@ -2100,9 +3705,14 @@ function LuCI2()
                                .append(_luci2.globals.mainMenu.render(2, 900));
                },
 
-               renderView: function(node)
+               renderView: function()
                {
+                       var node = arguments[0];
                        var name = node.view.split(/\//).join('.');
+                       var args = [ ];
+
+                       for (var i = 1; i < arguments.length; i++)
+                               args.push(arguments[i]);
 
                        if (_luci2.globals.currentView)
                                _luci2.globals.currentView.finish();
@@ -2117,7 +3727,7 @@ function LuCI2()
                        if (_luci2._views[name] instanceof _luci2.ui.view)
                        {
                                _luci2.globals.currentView = _luci2._views[name];
-                               return _luci2._views[name].render();
+                               return _luci2._views[name].render.apply(_luci2._views[name], args);
                        }
 
                        var url = _luci2.globals.resource + '/view/' + name + '.js';
@@ -2143,7 +3753,7 @@ function LuCI2()
                                        });
 
                                        _luci2.globals.currentView = _luci2._views[name];
-                                       return _luci2._views[name].render();
+                                       return _luci2._views[name].render.apply(_luci2._views[name], args);
                                }
                                catch(e) {
                                        alert('Unable to instantiate view "%s": %s'.format(url, e));
@@ -2178,6 +3788,7 @@ function LuCI2()
                                                switch (c[0])
                                                {
                                                case 'order':
+                                                       log.push('uci reorder %s.<ins>%s=<strong>%s</strong></ins>'.format(config, c[1], c[2]));
                                                        break;
 
                                                case 'remove':
@@ -2251,27 +3862,59 @@ function LuCI2()
                                        _luci2.ui.loading(false);
                                })
                        });
+               },
+
+               button: function(label, style, title)
+               {
+                       style = style || 'default';
+
+                       return $('<button />')
+                               .attr('type', 'button')
+                               .attr('title', title ? title : '')
+                               .addClass('btn btn-' + style)
+                               .text(label);
                }
        };
 
-       var AbstractWidget = Class.extend({
+       this.ui.AbstractWidget = Class.extend({
                i18n: function(text) {
                        return text;
                },
 
-               toString: function() {
-                       var x = document.createElement('div');
-                               x.appendChild(this.render());
+               label: function() {
+                       var key = arguments[0];
+                       var args = [ ];
+
+                       for (var i = 1; i < arguments.length; i++)
+                               args.push(arguments[i]);
+
+                       switch (typeof(this.options[key]))
+                       {
+                       case 'undefined':
+                               return '';
+
+                       case 'function':
+                               return this.options[key].apply(this, args);
+
+                       default:
+                               return ''.format.apply('' + this.options[key], args);
+                       }
+               },
 
-                       return x.innerHTML;
+               toString: function() {
+                       return $('<div />').append(this.render()).html();
                },
 
                insertInto: function(id) {
                        return $(id).empty().append(this.render());
+               },
+
+               appendTo: function(id) {
+                       return $(id).append(this.render());
                }
        });
 
-       this.ui.view = AbstractWidget.extend({
+       this.ui.view = this.ui.AbstractWidget.extend({
                _fetch_template: function()
                {
                        return $.ajax(_luci2.globals.resource + '/template/' + this.options.name + '.htm', {
@@ -2317,11 +3960,16 @@ function LuCI2()
                                container.append($('<h2 />').append(this.title));
 
                        if (this.description)
-                               container.append($('<div />').addClass('cbi-map-descr').append(this.description));
+                               container.append($('<p />').append(this.description));
 
                        var self = this;
+                       var args = [ ];
+
+                       for (var i = 0; i < arguments.length; i++)
+                               args.push(arguments[i]);
+
                        return this._fetch_template().then(function() {
-                               return _luci2.deferrable(self.execute());
+                               return _luci2.deferrable(self.execute.apply(self, args));
                        });
                },
 
@@ -2340,11 +3988,12 @@ function LuCI2()
                        var setTimer, runTimer;
 
                        setTimer = function() {
-                               self._timeouts[index] = window.setTimeout(runTimer, interval);
+                               if (self._timeouts)
+                                       self._timeouts[index] = window.setTimeout(runTimer, interval);
                        };
 
                        runTimer = function() {
-                               _luci2.deferrable(func.call(self)).then(setTimer);
+                               _luci2.deferrable(func.call(self)).then(setTimer, setTimer);
                        };
 
                        runTimer();
@@ -2362,7 +4011,7 @@ function LuCI2()
                }
        });
 
-       this.ui.menu = AbstractWidget.extend({
+       this.ui.menu = this.ui.AbstractWidget.extend({
                init: function() {
                        this._nodes = { };
                },
@@ -2449,9 +4098,9 @@ function LuCI2()
                        var list = $('<ul />');
 
                        if (level == 0)
-                               list.addClass('nav');
+                               list.addClass('nav').addClass('navbar-nav');
                        else if (level == 1)
-                               list.addClass('dropdown-menu');
+                               list.addClass('dropdown-menu').addClass('navbar-inverse');
 
                        for (var i = 0; i < nodes.length; i++)
                        {
@@ -2465,16 +4114,24 @@ function LuCI2()
                                var item = $('<li />')
                                        .append($('<a />')
                                                .attr('href', '#')
-                                               .text(_luci2.tr(nodes[i].title))
-                                               .click(nodes[i], this._onclick))
+                                               .text(_luci2.tr(nodes[i].title)))
                                        .appendTo(list);
 
                                if (nodes[i].childs && level < max)
                                {
                                        item.addClass('dropdown');
-                                       item.find('a').addClass('menu');
+
+                                       item.find('a')
+                                               .addClass('dropdown-toggle')
+                                               .attr('data-toggle', 'dropdown')
+                                               .append('<b class="caret"></b>');
+
                                        item.append(this._render(nodes[i].childs, level + 1));
                                }
+                               else
+                               {
+                                       item.find('a').click(nodes[i], this._onclick);
+                               }
                        }
 
                        return list.get(0);
@@ -2506,7 +4163,7 @@ function LuCI2()
                }
        });
 
-       this.ui.table = AbstractWidget.extend({
+       this.ui.table = this.ui.AbstractWidget.extend({
                init: function()
                {
                        this._rows = [ ];
@@ -2553,7 +4210,7 @@ function LuCI2()
                        }
 
                        var table = document.createElement('table');
-                               table.className = 'cbi-section-table';
+                               table.className = 'table table-condensed table-hover';
 
                        var has_caption = false;
                        var has_description = false;
@@ -2672,32 +4329,34 @@ function LuCI2()
                }
        });
 
-       this.ui.progress = AbstractWidget.extend({
+       this.ui.progress = this.ui.AbstractWidget.extend({
                render: function()
                {
                        var vn = parseInt(this.options.value) || 0;
                        var mn = parseInt(this.options.max) || 100;
                        var pc = Math.floor((100 / mn) * vn);
 
-                       var bar = document.createElement('div');
-                               bar.className = 'progressbar';
-
-                       bar.appendChild(document.createElement('div'));
-                       bar.lastChild.appendChild(document.createElement('div'));
-                       bar.lastChild.style.width = pc + '%';
+                       var text;
 
                        if (typeof(this.options.format) == 'string')
-                               $(bar.lastChild.lastChild).append(this.options.format.format(this.options.value, this.options.max, pc));
+                               text = this.options.format.format(this.options.value, this.options.max, pc);
                        else if (typeof(this.options.format) == 'function')
-                               $(bar.lastChild.lastChild).append(this.options.format(pc));
+                               text = this.options.format(pc);
                        else
-                               $(bar.lastChild.lastChild).append('%.2f%%'.format(pc));
+                               text = '%.2f%%'.format(pc);
 
-                       return bar;
+                       return $('<div />')
+                               .addClass('progress')
+                               .append($('<div />')
+                                       .addClass('progress-bar')
+                                       .addClass('progress-bar-info')
+                                       .css('width', pc + '%'))
+                               .append($('<small />')
+                                       .text(text));
                }
        });
 
-       this.ui.devicebadge = AbstractWidget.extend({
+       this.ui.devicebadge = this.ui.AbstractWidget.extend({
                render: function()
                {
                        var l2dev = this.options.l2_device || this.options.device;
@@ -2705,7 +4364,7 @@ function LuCI2()
                        var dev = l3dev || l2dev || '?';
 
                        var span = document.createElement('span');
-                               span.className = 'ifacebadge';
+                               span.className = 'badge';
 
                        if (typeof(this.options.signal) == 'number' ||
                                typeof(this.options.noise) == 'number')
@@ -2837,7 +4496,7 @@ function LuCI2()
                                                                else if (typeof types[label] == 'function')
                                                                {
                                                                        stack.push(types[label]);
-                                                                       stack.push(null);
+                                                                       stack.push([ ]);
                                                                }
                                                                else
                                                                {
@@ -2856,7 +4515,7 @@ function LuCI2()
                                                                throw "Syntax error, argument list follows non-function";
 
                                                        stack[stack.length-1] =
-                                                               arguments.callee(code.substring(pos, i));
+                                                               _luci2.cbi.validation.compile(code.substring(pos, i));
 
                                                        pos = i+1;
                                                }
@@ -3266,7 +4925,7 @@ function LuCI2()
        };
 
 
-       this.cbi.AbstractValue = AbstractWidget.extend({
+       this.cbi.AbstractValue = this.ui.AbstractWidget.extend({
                init: function(name, options)
                {
                        this.name = name;
@@ -3287,27 +4946,43 @@ function LuCI2()
                        return this.section.id('field', sid || '__unknown__', this.name);
                },
 
-               render: function(sid)
+               render: function(sid, condensed)
                {
                        var i = this.instance[sid] = { };
 
-                       i.top = $('<div />').addClass('cbi-value');
+                       i.top = $('<div />');
 
-                       if (typeof(this.options.caption) == 'string')
-                               $('<label />')
-                                       .addClass('cbi-value-title')
-                                       .attr('for', this.id(sid))
-                                       .text(this.options.caption)
-                                       .appendTo(i.top);
+                       if (!condensed)
+                       {
+                               i.top.addClass('form-group');
 
-                       i.widget = $('<div />').addClass('cbi-value-field').append(this.widget(sid)).appendTo(i.top);
-                       i.error = $('<div />').addClass('cbi-value-error').appendTo(i.top);
+                               if (typeof(this.options.caption) == 'string')
+                                       $('<label />')
+                                               .addClass('col-lg-2 control-label')
+                                               .attr('for', this.id(sid))
+                                               .text(this.options.caption)
+                                               .appendTo(i.top);
+                       }
+
+                       i.error = $('<div />')
+                               .hide()
+                               .addClass('label label-danger');
+
+                       i.widget = $('<div />')
+
+                               .append(this.widget(sid))
+                               .append(i.error)
+                               .appendTo(i.top);
+
+                       if (!condensed)
+                       {
+                               i.widget.addClass('col-lg-5');
 
-                       if (typeof(this.options.description) == 'string')
                                $('<div />')
-                                       .addClass('cbi-value-description')
-                                       .text(this.options.description)
+                                       .addClass('col-lg-5')
+                                       .text((typeof(this.options.description) == 'string') ? this.options.description : '')
                                        .appendTo(i.top);
+                       }
 
                        return i.top;
                },
@@ -3411,6 +5086,52 @@ function LuCI2()
                        return chg;
                },
 
+               _ev_validate: function(ev)
+               {
+                       var d = ev.data;
+                       var rv = true;
+                       var val = d.elem.val();
+                       var vstack = d.vstack;
+
+                       if (vstack && typeof(vstack[0]) == 'function')
+                       {
+                               delete validation.message;
+
+                               if ((val.length == 0 && !d.opt))
+                               {
+                                       d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
+                                       d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
+
+                                       d.inst.error.text(_luci2.tr('Field must not be empty')).show();
+                                       rv = false;
+                               }
+                               else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
+                               {
+                                       d.elem.parents('div.form-group, td').first().addClass('luci2-form-error');
+                                       d.elem.parents('div.input-group, div.form-group, td').first().addClass('has-error');
+
+                                       d.inst.error.text(validation.message.format.apply(validation.message, vstack[1])).show();
+                                       rv = false;
+                               }
+                               else
+                               {
+                                       d.elem.parents('div.form-group, td').first().removeClass('luci2-form-error');
+                                       d.elem.parents('div.input-group, div.form-group, td').first().removeClass('has-error');
+
+                                       if (d.multi && d.inst.widget && d.inst.widget.find('input.error, select.error').length > 0)
+                                               rv = false;
+                                       else
+                                               d.inst.error.text('').hide();
+                               }
+                       }
+
+                       if (rv)
+                               for (var field in d.self.rdependency)
+                                       d.self.rdependency[field].toggle(d.sid);
+
+                       return rv;
+               },
+
                validator: function(sid, elem, multi)
                {
                        if (typeof(this.options.datatype) == 'undefined' && $.isEmptyObject(this.rdependency))
@@ -3424,90 +5145,42 @@ function LuCI2()
                                } catch(e) { };
                        }
                        else if (typeof(this.options.datatype) == 'function')
-                       {
-                               var vfunc = this.options.datatype;
-                               vstack = [ function(elem) {
-                                       var rv = vfunc(this, elem);
-                                       if (rv !== true)
-                                               validation.message = rv;
-                                       return (rv === true);
-                               }, [ elem ] ];
-                       }
-
-                       var evdata = {
-                               self:  this,
-                               sid:   sid,
-                               elem:  elem,
-                               multi: multi,
-                               inst:  this.instance[sid],
-                               opt:   this.options.optional
-                       };
-
-                       var validator = function(ev)
-                       {
-                               var d = ev.data;
-                               var rv = true;
-                               var val = d.elem.val();
-
-                               if (vstack && typeof(vstack[0]) == 'function')
-                               {
-                                       delete validation.message;
-
-                                       if ((val.length == 0 && !d.opt))
-                                       {
-                                               d.elem.addClass('error');
-                                               d.inst.top.addClass('error');
-                                               d.inst.error.text(_luci2.tr('Field must not be empty'));
-                                               rv = false;
-                                       }
-                                       else if (val.length > 0 && !vstack[0].apply(val, vstack[1]))
-                                       {
-                                               d.elem.addClass('error');
-                                               d.inst.top.addClass('error');
-                                               d.inst.error.text(validation.message.format.apply(validation.message, vstack[1]));
-                                               rv = false;
-                                       }
-                                       else
-                                       {
-                                               d.elem.removeClass('error');
-
-                                               if (d.multi && d.inst.widget.find('input.error, select.error').length > 0)
-                                               {
-                                                       rv = false;
-                                               }
-                                               else
-                                               {
-                                                       d.inst.top.removeClass('error');
-                                                       d.inst.error.text('');
-                                               }
-                                       }
-                               }
-
-                               if (rv)
-                               {
-                                       for (var field in d.self.rdependency)
-                                               d.self.rdependency[field].toggle(d.sid);
-                               }
+                       {
+                               var vfunc = this.options.datatype;
+                               vstack = [ function(elem) {
+                                       var rv = vfunc(this, elem);
+                                       if (rv !== true)
+                                               validation.message = rv;
+                                       return (rv === true);
+                               }, [ elem ] ];
+                       }
 
-                               return rv;
+                       var evdata = {
+                               self:   this,
+                               sid:    sid,
+                               elem:   elem,
+                               multi:  multi,
+                               vstack: vstack,
+                               inst:   this.instance[sid],
+                               opt:    this.options.optional
                        };
 
                        if (elem.prop('tagName') == 'SELECT')
                        {
-                               elem.change(evdata, validator);
+                               elem.change(evdata, this._ev_validate);
                        }
                        else if (elem.prop('tagName') == 'INPUT' && elem.attr('type') == 'checkbox')
                        {
-                               elem.click(evdata, validator);
-                               elem.blur(evdata, validator);
+                               elem.click(evdata, this._ev_validate);
+                               elem.blur(evdata, this._ev_validate);
                        }
                        else
                        {
-                               elem.keyup(evdata, validator);
-                               elem.blur(evdata, validator);
+                               elem.keyup(evdata, this._ev_validate);
+                               elem.blur(evdata, this._ev_validate);
                        }
 
-                       elem.attr('cbi-validate', true).on('validate', evdata, validator);
+                       elem.attr('cbi-validate', true).on('validate', evdata, this._ev_validate);
 
                        return elem;
                },
@@ -3657,7 +5330,9 @@ function LuCI2()
                                .attr('type', 'checkbox')
                                .prop('checked', this.ucivalue(sid));
 
-                       return this.validator(sid, i);
+                       return $('<div />')
+                               .addClass('checkbox')
+                               .append(this.validator(sid, i));
                },
 
                ucivalue: function(sid)
@@ -3711,6 +5386,7 @@ function LuCI2()
                widget: function(sid)
                {
                        var i = $('<input />')
+                               .addClass('form-control')
                                .attr('id', this.id(sid))
                                .attr('type', 'text')
                                .attr('placeholder', this.options.placeholder)
@@ -3724,26 +5400,28 @@ function LuCI2()
                widget: function(sid)
                {
                        var i = $('<input />')
+                               .addClass('form-control')
                                .attr('id', this.id(sid))
                                .attr('type', 'password')
                                .attr('placeholder', this.options.placeholder)
                                .val(this.ucivalue(sid));
 
-                       var t = $('<img />')
-                               .attr('src', _luci2.globals.resource + '/icons/cbi/reload.gif')
-                               .attr('title', _luci2.tr('Reveal or hide password'))
-                               .addClass('cbi-button')
-                               .click(function(ev) {
-                                       var i = $(this).prev();
-                                       var t = i.attr('type');
-                                       i.attr('type', (t == 'password') ? 'text' : 'password');
-                                       i = t = null;
-                               });
+                       var t = $('<span />')
+                               .addClass('input-group-btn')
+                               .append(_luci2.ui.button(_luci2.tr('Reveal'), 'default')
+                                       .click(function(ev) {
+                                               var b = $(this);
+                                               var i = b.parent().prev();
+                                               var t = i.attr('type');
+                                               b.text(t == 'password' ? _luci2.tr('Hide') : _luci2.tr('Reveal'));
+                                               i.attr('type', (t == 'password') ? 'text' : 'password');
+                                               b = i = t = null;
+                                       }));
 
                        this.validator(sid, i);
 
                        return $('<div />')
-                               .addClass('cbi-input-password')
+                               .addClass('input-group')
                                .append(i)
                                .append(t);
                }
@@ -3752,7 +5430,8 @@ function LuCI2()
        this.cbi.ListValue = this.cbi.AbstractValue.extend({
                widget: function(sid)
                {
-                       var s = $('<select />');
+                       var s = $('<select />')
+                               .addClass('form-control');
 
                        if (this.options.optional)
                                $('<option />')
@@ -3799,16 +5478,13 @@ function LuCI2()
                                for (var i = 0; i < this.choices.length; i++)
                                {
                                        $('<label />')
+                                               .addClass('checkbox')
                                                .append($('<input />')
-                                                       .addClass('cbi-input-checkbox')
                                                        .attr('type', 'checkbox')
                                                        .attr('value', this.choices[i][0])
                                                        .prop('checked', s[this.choices[i][0]]))
                                                .append(this.choices[i][1])
                                                .appendTo(t);
-
-                                       $('<br />')
-                                               .appendTo(t);
                                }
 
                        return t;
@@ -3971,7 +5647,7 @@ function LuCI2()
                        var v = s.values || [ ];
                        delete s.values;
 
-                       $(s.parent).children('input').each(function(i) {
+                       $(s.parent).children('div.input-group').children('input').each(function(i) {
                                if (i != del)
                                        v.push(this.value || '');
                        });
@@ -3995,17 +5671,33 @@ function LuCI2()
                                        sid: s.sid,
                                        self: s.self,
                                        parent: s.parent,
-                                       index: i
+                                       index: i,
+                                       remove: ((i+1) < v.length)
                                };
 
+                               var btn;
+                               if (evdata.remove)
+                                       btn = _luci2.ui.button('–', 'danger').click(evdata, this._btnclick);
+                               else
+                                       btn = _luci2.ui.button('+', 'success').click(evdata, this._btnclick);
+
                                if (this.choices)
                                {
                                        var txt = $('<input />')
+                                               .addClass('form-control')
                                                .attr('type', 'text')
-                                               .hide()
-                                               .appendTo(s.parent);
+                                               .hide();
 
                                        var sel = $('<select />')
+                                               .addClass('form-control');
+
+                                       $('<div />')
+                                               .addClass('input-group')
+                                               .append(txt)
+                                               .append(sel)
+                                               .append($('<span />')
+                                                       .addClass('input-group-btn')
+                                                       .append(btn))
                                                .appendTo(s.parent);
 
                                        evdata.input = this.validator(s.sid, txt, true);
@@ -4029,12 +5721,18 @@ function LuCI2()
                                                .attr('type', 'text')
                                                .attr('index', i)
                                                .attr('placeholder', (i == 0) ? this.options.placeholder : '')
-                                               .addClass('cbi-input-text')
+                                               .addClass('form-control')
                                                .keydown(evdata, this._keydown)
                                                .keypress(evdata, this._keypress)
                                                .val(v[i]);
 
-                                       f.appendTo(s.parent);
+                                       $('<div />')
+                                               .addClass('input-group')
+                                               .append(f)
+                                               .append($('<span />')
+                                                       .addClass('input-group-btn')
+                                                       .append(btn))
+                                               .appendTo(s.parent);
 
                                        if (i == focus)
                                        {
@@ -4055,16 +5753,6 @@ function LuCI2()
                                        f = null;
                                }
 
-                               $('<img />')
-                                       .attr('src', _luci2.globals.resource + ((i+1) < v.length ? '/icons/cbi/remove.gif' : '/icons/cbi/add.gif'))
-                                       .attr('title', (i+1) < v.length ? _luci2.tr('Remove entry') : _luci2.tr('Add entry'))
-                                       .addClass('cbi-button')
-                                       .click(evdata, this._btnclick)
-                                       .appendTo(s.parent);
-
-                               $('<br />')
-                                       .appendTo(s.parent);
-
                                evdata = null;
                        }
 
@@ -4129,7 +5817,7 @@ function LuCI2()
 
                                /* arrow up */
                                case 38:
-                                       var prev = input.prevAll('input:first');
+                                       var prev = input.parent().prevAll('div.input-group:first').children('input');
                                        if (prev.is(':visible'))
                                                prev.focus();
                                        else
@@ -4138,7 +5826,7 @@ function LuCI2()
 
                                /* arrow down */
                                case 40:
-                                       var next = input.nextAll('input:first');
+                                       var next = input.parent().nextAll('div.input-group:first').children('input');
                                        if (next.is(':visible'))
                                                next.focus();
                                        else
@@ -4153,7 +5841,7 @@ function LuCI2()
                {
                        if (!this.getAttribute('disabled'))
                        {
-                               if (ev.target.src.indexOf('remove') > -1)
+                               if (ev.data.remove)
                                {
                                        var index = ev.data.index;
                                        ev.data.self._redraw(-index, -1, index, ev.data);
@@ -4217,7 +5905,7 @@ function LuCI2()
                widget: function(sid)
                {
                        return $('<div />')
-                               .addClass('cbi-value-dummy')
+                               .addClass('form-control-static')
                                .attr('id', this.id(sid))
                                .html(this.ucivalue(sid));
                },
@@ -4228,52 +5916,32 @@ function LuCI2()
                }
        });
 
-       this.cbi.NetworkList = this.cbi.AbstractValue.extend({
-               load: function(sid)
+       this.cbi.ButtonValue = this.cbi.AbstractValue.extend({
+               widget: function(sid)
                {
-                       var self = this;
+                       this.options.optional = true;
 
-                       if (!self.interfaces)
-                       {
-                               self.interfaces = [ ];
-                               return _luci2.network.getNetworkStatus().then(function(ifaces) {
-                                       self.interfaces = ifaces;
-                                       self = null;
-                               });
-                       }
+                       var btn = $('<button />')
+                               .addClass('btn btn-default')
+                               .attr('id', this.id(sid))
+                               .attr('type', 'button')
+                               .text(this.label('text'));
 
-                       return undefined;
+                       return this.validator(sid, btn);
+               }
+       });
+
+       this.cbi.NetworkList = this.cbi.AbstractValue.extend({
+               load: function(sid)
+               {
+                       return _luci2.NetworkModel.init();
                },
 
                _device_icon: function(dev)
                {
-                       var type = 'ethernet';
-                       var desc = _luci2.tr('Ethernet device');
-
-                       if (dev.type == 'IP tunnel')
-                       {
-                               type = 'tunnel';
-                               desc = _luci2.tr('Tunnel interface');
-                       }
-                       else if (dev['bridge-members'])
-                       {
-                               type = 'bridge';
-                               desc = _luci2.tr('Bridge');
-                       }
-                       else if (dev.wireless)
-                       {
-                               type = 'wifi';
-                               desc = _luci2.tr('Wireless Network');
-                       }
-                       else if (dev.device.indexOf('.') > 0)
-                       {
-                               type = 'vlan';
-                               desc = _luci2.tr('VLAN interface');
-                       }
-
                        return $('<img />')
-                               .attr('src', _luci2.globals.resource + '/icons/' + type + (dev.up ? '' : '_disabled') + '.png')
-                               .attr('title', '%s (%s)'.format(desc, dev.device));
+                               .attr('src', dev.icon())
+                               .attr('title', '%s (%s)'.format(dev.description(), dev.name() || '?'));
                },
 
                widget: function(sid)
@@ -4281,7 +5949,7 @@ function LuCI2()
                        var id = this.id(sid);
                        var ul = $('<ul />')
                                .attr('id', id)
-                               .addClass('cbi-input-networks');
+                               .addClass('list-unstyled');
 
                        var itype = this.options.multiple ? 'checkbox' : 'radio';
                        var value = this.ucivalue(sid);
@@ -4293,46 +5961,48 @@ function LuCI2()
                                for (var i = 0; i < value.length; i++)
                                        check[value[i]] = true;
 
-                       if (this.interfaces)
+                       var interfaces = _luci2.NetworkModel.getInterfaces();
+
+                       for (var i = 0; i < interfaces.length; i++)
                        {
-                               for (var i = 0; i < this.interfaces.length; i++)
-                               {
-                                       var iface = this.interfaces[i];
-                                       var badge = $('<span />')
-                                               .addClass('ifacebadge')
-                                               .text('%s: '.format(iface['interface']));
-
-                                       if (iface.device && iface.device.subdevices)
-                                               for (var j = 0; j < iface.device.subdevices.length; j++)
-                                                       badge.append(this._device_icon(iface.device.subdevices[j]));
-                                       else if (iface.device)
-                                               badge.append(this._device_icon(iface.device));
-                                       else
-                                               badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
+                               var iface = interfaces[i];
+                               var badge = $('<span />')
+                                       .addClass('badge')
+                                       .text('%s: '.format(iface.name()));
 
-                                       $('<li />')
-                                               .append($('<label />')
-                                                       .append($('<input />')
-                                                               .attr('name', itype + id)
-                                                               .attr('type', itype)
-                                                               .attr('value', iface['interface'])
-                                                               .prop('checked', !!check[iface['interface']])
-                                                               .addClass('cbi-input-' + itype))
-                                                       .append(badge))
-                                               .appendTo(ul);
-                               }
+                               var dev = iface.getDevice();
+                               var subdevs = iface.getSubdevices();
+
+                               if (subdevs.length)
+                                       for (var j = 0; j < subdevs.length; j++)
+                                               badge.append(this._device_icon(subdevs[j]));
+                               else if (dev)
+                                       badge.append(this._device_icon(dev));
+                               else
+                                       badge.append($('<em />').text(_luci2.tr('(No devices attached)')));
+
+                               $('<li />')
+                                       .append($('<label />')
+                                               .addClass(itype + ' inline')
+                                               .append($('<input />')
+                                                       .attr('name', itype + id)
+                                                       .attr('type', itype)
+                                                       .attr('value', iface.name())
+                                                       .prop('checked', !!check[iface.name()]))
+                                               .append(badge))
+                                       .appendTo(ul);
                        }
 
                        if (!this.options.multiple)
                        {
                                $('<li />')
                                        .append($('<label />')
+                                               .addClass(itype + ' inline text-muted')
                                                .append($('<input />')
                                                        .attr('name', itype + id)
                                                        .attr('type', itype)
                                                        .attr('value', '')
-                                                       .prop('checked', !value)
-                                                       .addClass('cbi-input-' + itype))
+                                                       .prop('checked', $.isEmptyObject(check)))
                                                .append(_luci2.tr('unspecified')))
                                        .appendTo(ul);
                        }
@@ -4391,7 +6061,7 @@ function LuCI2()
        });
 
 
-       this.cbi.AbstractSection = AbstractWidget.extend({
+       this.cbi.AbstractSection = this.ui.AbstractWidget.extend({
                id: function()
                {
                        var s = [ arguments[0], this.map.uci_package, this.uci_type ];
@@ -4480,60 +6150,66 @@ function LuCI2()
                        return rv;
                },
 
-               validate: function(sid)
+               validate_section: function(sid)
                {
-                       var rv = true;
-
-                       if (!sid)
-                       {
-                               var as = this.sections();
-                               for (var i = 0; i < as.length; i++)
-                                       if (!this.validate(as[i]['.name']))
-                                               rv = false;
-                               return rv;
-                       }
-
                        var inst = this.instance[sid];
-                       var sv = rv[sid] || (rv[sid] = { });
 
                        var invals = 0;
-                       var legend = $('#' + this.id('sort', sid)).find('legend:first');
-
-                       legend.children('span').detach();
+                       var badge = $('#' + this.id('teaser', sid)).children('span:first');
 
                        for (var i = 0; i < this.tabs.length; i++)
                        {
                                var inval = 0;
-                               var tab = $('#' + this.id('tabhead', sid, this.tabs[i].id));
-
-                               tab.children('span').detach();
+                               var stbadge = $('#' + this.id('nodetab', sid, this.tabs[i].id)).children('span:first');
 
                                for (var j = 0; j < this.tabs[i].fields.length; j++)
                                        if (!this.tabs[i].fields[j].validate(sid))
                                                inval++;
 
                                if (inval > 0)
-                               {
-                                       $('<span />')
-                                               .addClass('badge')
-                                               .attr('title', _luci2.tr('%d Errors'.format(inval)))
+                                       stbadge.show()
                                                .text(inval)
-                                               .appendTo(tab);
+                                               .attr('title', _luci2.trp('1 Error', '%d Errors', inval).format(inval));
+                               else
+                                       stbadge.hide();
 
-                                       invals += inval;
-                                       tab = null;
-                                       rv = false;
-                               }
+                               invals += inval;
                        }
 
                        if (invals > 0)
-                               $('<span />')
-                                       .addClass('badge')
-                                       .attr('title', _luci2.tr('%d Errors'.format(invals)))
+                               badge.show()
                                        .text(invals)
-                                       .appendTo(legend);
+                                       .attr('title', _luci2.trp('1 Error', '%d Errors', invals).format(invals));
+                       else
+                               badge.hide();
 
-                       return rv;
+                       return invals;
+               },
+
+               validate: function()
+               {
+                       this.error_count = 0;
+
+                       var as = this.sections();
+
+                       for (var i = 0; i < as.length; i++)
+                       {
+                               var invals = this.validate_section(as[i]['.name']);
+
+                               if (invals > 0)
+                                       this.error_count += invals;
+                       }
+
+                       var badge = $('#' + this.id('sectiontab')).children('span:first');
+
+                       if (this.error_count > 0)
+                               badge.show()
+                                       .text(this.error_count)
+                                       .attr('title', _luci2.trp('1 Error', '%d Errors', this.error_count).format(this.error_count));
+                       else
+                               badge.hide();
+
+                       return (this.error_count == 0);
                }
        });
 
@@ -4544,6 +6220,7 @@ function LuCI2()
                        this.options  = options;
                        this.tabs     = [ ];
                        this.fields   = { };
+                       this.error_count  = 0;
                        this.active_panel = 0;
                        this.active_tab   = { };
                },
@@ -4555,7 +6232,7 @@ function LuCI2()
 
                sections: function(cb)
                {
-                       var s1 = this.map.ucisections(this.map.uci_package);
+                       var s1 = _luci2.uci.sections(this.map.uci_package);
                        var s2 = [ ];
 
                        for (var i = 0; i < s1.length; i++)
@@ -4580,7 +6257,7 @@ function LuCI2()
                        this.map.remove(this.map.uci_package, sid);
                },
 
-               _add: function(ev)
+               _ev_add: function(ev)
                {
                        var addb = $(this);
                        var name = undefined;
@@ -4602,14 +6279,11 @@ function LuCI2()
                        _luci2.ui.restoreScrollTop();
                },
 
-               _remove: function(ev)
+               _ev_remove: function(ev)
                {
                        var self = ev.data.self;
                        var sid  = ev.data.sid;
 
-                       if (ev.data.index == (self.sections().length - 1))
-                               self.active_panel = -1;
-
                        _luci2.ui.saveScrollTop();
 
                        self.map.save();
@@ -4621,14 +6295,13 @@ function LuCI2()
                        ev.stopPropagation();
                },
 
-               _sid: function(ev)
+               _ev_sid: function(ev)
                {
                        var self = ev.data.self;
                        var text = $(this);
                        var addb = text.next();
                        var errt = addb.next();
                        var name = text.val();
-                       var used = false;
 
                        if (!/^[a-zA-Z0-9_]*$/.test(name))
                        {
@@ -4638,21 +6311,7 @@ function LuCI2()
                                return false;
                        }
 
-                       for (var sid in self.map.uci.values[self.map.uci_package])
-                               if (sid == name)
-                               {
-                                       used = true;
-                                       break;
-                               }
-
-                       for (var sid in self.map.uci.creates[self.map.uci_package])
-                               if (sid == name)
-                               {
-                                       used = true;
-                                       break;
-                               }
-
-                       if (used)
+                       if (_luci2.uci.get(self.map.uci_package, name))
                        {
                                errt.text(_luci2.tr('Name already used')).show();
                                text.addClass('error');
@@ -4666,6 +6325,70 @@ function LuCI2()
                        return true;
                },
 
+               _ev_tab: function(ev)
+               {
+                       var self = ev.data.self;
+                       var sid  = ev.data.sid;
+
+                       self.validate();
+                       self.active_tab[sid] = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
+               },
+
+               _ev_panel_collapse: function(ev)
+               {
+                       var self = ev.data.self;
+
+                       var this_panel = $(ev.target);
+                       var this_toggle = this_panel.prevAll('[data-toggle="collapse"]:first');
+
+                       var prev_toggle = $($(ev.delegateTarget).find('[data-toggle="collapse"]:eq(%d)'.format(self.active_panel)));
+                       var prev_panel = $(prev_toggle.attr('data-target'));
+
+                       prev_panel
+                               .removeClass('in')
+                               .addClass('collapse');
+
+                       prev_toggle.find('.luci2-section-teaser')
+                               .show()
+                               .children('span:last')
+                               .empty()
+                               .append(self.teaser(prev_panel.attr('data-luci2-sid')));
+
+                       this_toggle.find('.luci2-section-teaser')
+                               .hide();
+
+                       self.active_panel = parseInt(this_panel.attr('data-luci2-panel-index'));
+                       self.validate();
+               },
+
+               _ev_panel_open: function(ev)
+               {
+                       var self  = ev.data.self;
+                       var panel = $($(this).attr('data-target'));
+                       var index = parseInt(panel.attr('data-luci2-panel-index'));
+
+                       if (index == self.active_panel)
+                               ev.stopPropagation();
+               },
+
+               _ev_sort: function(ev)
+               {
+                       var self    = ev.data.self;
+                       var cur_idx = ev.data.index;
+                       var new_idx = cur_idx + (ev.data.up ? -1 : 1);
+                       var s       = self.sections();
+
+                       if (new_idx >= 0 && new_idx < s.length)
+                       {
+                               _luci2.uci.swap(self.map.uci_package, s[cur_idx]['.name'], s[new_idx]['.name']);
+
+                               self.map.save();
+                               self.map.redraw();
+                       }
+
+                       ev.stopPropagation();
+               },
+
                teaser: function(sid)
                {
                        var tf = this.teaser_fields;
@@ -4714,6 +6437,9 @@ function LuCI2()
 
                _render_add: function()
                {
+                       if (!this.options.addremove)
+                               return null;
+
                        var text = _luci2.tr('Add section');
                        var ttip = _luci2.tr('Create new section...');
 
@@ -4722,7 +6448,7 @@ function LuCI2()
                        else if (typeof(this.options.add_caption) == 'string')
                                text = this.options.add_caption, ttip = '';
 
-                       var add = $('<div />').addClass('cbi-section-add');
+                       var add = $('<div />');
 
                        if (this.options.anonymous === false)
                        {
@@ -4730,15 +6456,15 @@ function LuCI2()
                                        .addClass('cbi-input-text')
                                        .attr('type', 'text')
                                        .attr('placeholder', ttip)
-                                       .blur({ self: this }, this._sid)
-                                       .keyup({ self: this }, this._sid)
+                                       .blur({ self: this }, this._ev_sid)
+                                       .keyup({ self: this }, this._ev_sid)
                                        .appendTo(add);
 
                                $('<img />')
                                        .attr('src', _luci2.globals.resource + '/icons/cbi/add.gif')
                                        .attr('title', text)
                                        .addClass('cbi-button')
-                                       .click({ self: this }, this._add)
+                                       .click({ self: this }, this._ev_add)
                                        .appendTo(add);
 
                                $('<div />')
@@ -4748,13 +6474,9 @@ function LuCI2()
                        }
                        else
                        {
-                               $('<input />')
-                                       .attr('type', 'button')
-                                       .addClass('cbi-button')
-                                       .addClass('cbi-button-add')
-                                       .val(text).attr('title', ttip)
-                                       .click({ self: this }, this._add)
-                                       .appendTo(add)
+                               _luci2.ui.button(text, 'success', ttip)
+                                       .click({ self: this }, this._ev_add)
+                                       .appendTo(add);
                        }
 
                        return add;
@@ -4762,6 +6484,9 @@ function LuCI2()
 
                _render_remove: function(sid, index)
                {
+                       if (!this.options.addremove)
+                               return null;
+
                        var text = _luci2.tr('Remove');
                        var ttip = _luci2.tr('Remove this section');
 
@@ -4770,228 +6495,236 @@ function LuCI2()
                        else if (typeof(this.options.remove_caption) == 'string')
                                text = this.options.remove_caption, ttip = '';
 
-                       return $('<input />')
-                               .attr('type', 'button')
-                               .addClass('cbi-button')
-                               .addClass('cbi-button-remove')
-                               .val(text).attr('title', ttip)
-                               .click({ self: this, sid: sid, index: index }, this._remove);
+                       return _luci2.ui.button(text, 'danger', ttip)
+                               .click({ self: this, sid: sid, index: index }, this._ev_remove);
                },
 
-               _render_caption: function(sid)
+               _render_sort: function(sid, index)
                {
-                       if (typeof(this.options.caption) == 'string')
-                       {
-                               return $('<legend />')
-                                       .text(this.options.caption.format(sid));
-                       }
-                       else if (typeof(this.options.caption) == 'function')
-                       {
-                               return $('<legend />')
-                                       .text(this.options.caption.call(this, sid));
-                       }
+                       if (!this.options.sortable)
+                               return null;
 
-                       return '';
+                       var b1 = _luci2.ui.button('↑', 'info', _luci2.tr('Move up'))
+                               .click({ self: this, index: index, up: true }, this._ev_sort);
+
+                       var b2 = _luci2.ui.button('↓', 'info', _luci2.tr('Move down'))
+                               .click({ self: this, index: index, up: false }, this._ev_sort);
+
+                       return b1.add(b2);
                },
 
-               render: function()
+               _render_caption: function()
                {
-                       var allsections = $();
-                       var panel_index = 0;
+                       return $('<h3 />')
+                               .addClass('panel-title')
+                               .append(this.label('caption') || this.uci_type);
+               },
 
-                       this.instance = { };
+               _render_description: function()
+               {
+                       var text = this.label('description');
 
-                       var s = this.sections();
+                       if (text)
+                               return $('<div />')
+                                       .addClass('luci2-section-description')
+                                       .text(text);
 
-                       if (s.length == 0)
+                       return null;
+               },
+
+               _render_teaser: function(sid, index)
+               {
+                       if (this.options.collabsible || this.map.options.collabsible)
                        {
-                               var fieldset = $('<fieldset />')
-                                       .addClass('cbi-section');
+                               return $('<div />')
+                                       .attr('id', this.id('teaser', sid))
+                                       .addClass('luci2-section-teaser well well-sm')
+                                       .append($('<span />')
+                                               .addClass('badge'))
+                                       .append($('<span />'));
+                       }
 
-                               var head = $('<div />')
-                                       .addClass('cbi-section-head')
-                                       .appendTo(fieldset);
+                       return null;
+               },
 
-                               head.append(this._render_caption(undefined));
+               _render_head: function(condensed)
+               {
+                       if (condensed)
+                               return null;
 
-                               if (typeof(this.options.description) == 'string')
-                               {
-                                       $('<div />')
-                                               .addClass('cbi-section-descr')
-                                               .text(this.options.description)
-                                               .appendTo(head);
-                               }
+                       return $('<div />')
+                               .addClass('panel-heading')
+                               .append(this._render_caption())
+                               .append(this._render_description());
+               },
 
-                               allsections = allsections.add(fieldset);
-                       }
+               _render_tab_description: function(sid, index, tab_index)
+               {
+                       var tab = this.tabs[tab_index];
 
-                       for (var i = 0; i < s.length; i++)
+                       if (typeof(tab.description) == 'string')
                        {
-                               var sid = s[i]['.name'];
-                               var inst = this.instance[sid] = { tabs: [ ] };
-
-                               var fieldset = $('<fieldset />')
-                                       .attr('id', this.id('sort', sid))
-                                       .addClass('cbi-section');
+                               return $('<div />')
+                                       .addClass('cbi-tab-descr')
+                                       .text(tab.description);
+                       }
 
-                               var head = $('<div />')
-                                       .addClass('cbi-section-head')
-                                       .attr('cbi-section-num', this.index)
-                                       .attr('cbi-section-id', sid);
+                       return null;
+               },
 
-                               head.append(this._render_caption(sid));
+               _render_tab_head: function(sid, index, tab_index)
+               {
+                       var tab = this.tabs[tab_index];
+                       var cur = this.active_tab[sid] || 0;
 
-                               if (typeof(this.options.description) == 'string')
-                               {
-                                       $('<div />')
-                                               .addClass('cbi-section-descr')
-                                               .text(this.options.description)
-                                               .appendTo(head);
-                               }
+                       var tabh = $('<li />')
+                               .append($('<a />')
+                                       .attr('id', this.id('nodetab', sid, tab.id))
+                                       .attr('href', '#' + this.id('node', sid, tab.id))
+                                       .attr('data-toggle', 'tab')
+                                       .attr('data-luci2-tab-index', tab_index)
+                                       .text((tab.caption ? tab.caption.format(tab.id) : tab.id) + ' ')
+                                       .append($('<span />')
+                                               .addClass('badge'))
+                                       .on('shown.bs.tab', { self: this, sid: sid }, this._ev_tab));
 
-                               var teaser;
-                               if ((s.length > 1 && this.options.collabsible) || this.map.options.collabsible)
-                                       teaser = $('<div />')
-                                               .addClass('cbi-section-teaser')
-                                               .appendTo(head);
+                       if (cur == tab_index)
+                               tabh.addClass('active');
 
-                               if (this.options.addremove)
-                                       $('<div />')
-                                               .addClass('cbi-section-remove')
-                                               .addClass('right')
-                                               .append(this._render_remove(sid, panel_index))
-                                               .appendTo(head);
+                       return tabh;
+               },
 
-                               var body = $('<div />')
-                                       .attr('index', panel_index++);
+               _render_tab_body: function(sid, index, tab_index)
+               {
+                       var tab = this.tabs[tab_index];
+                       var cur = this.active_tab[sid] || 0;
 
-                               var fields = $('<fieldset />')
-                                       .addClass('cbi-section-node');
+                       var tabb = $('<div />')
+                               .addClass('tab-pane')
+                               .attr('id', this.id('node', sid, tab.id))
+                               .attr('data-luci2-tab-index', tab_index)
+                               .append(this._render_tab_description(sid, index, tab_index));
 
-                               if (this.tabs.length > 1)
-                               {
-                                       var menu = $('<ul />')
-                                               .addClass('cbi-tabmenu');
+                       if (cur == tab_index)
+                               tabb.addClass('active');
 
-                                       for (var j = 0; j < this.tabs.length; j++)
-                                       {
-                                               var tabid = this.id('tab', sid, this.tabs[j].id);
-                                               var theadid = this.id('tabhead', sid, this.tabs[j].id);
+                       for (var i = 0; i < tab.fields.length; i++)
+                               tabb.append(tab.fields[i].render(sid));
 
-                                               var tabc = $('<div />')
-                                                       .addClass('cbi-tabcontainer')
-                                                       .attr('id', tabid)
-                                                       .attr('index', j);
+                       return tabb;
+               },
 
-                                               if (typeof(this.tabs[j].description) == 'string')
-                                               {
-                                                       $('<div />')
-                                                               .addClass('cbi-tab-descr')
-                                                               .text(this.tabs[j].description)
-                                                               .appendTo(tabc);
-                                               }
+               _render_section_head: function(sid, index)
+               {
+                       var head = $('<div />')
+                               .addClass('luci2-section-header')
+                               .append(this._render_teaser(sid, index))
+                               .append($('<div />')
+                                       .addClass('btn-group')
+                                       .append(this._render_sort(sid, index))
+                                       .append(this._render_remove(sid, index)));
 
-                                               for (var k = 0; k < this.tabs[j].fields.length; k++)
-                                                       this.tabs[j].fields[k].render(sid).appendTo(tabc);
+                       if (this.options.collabsible)
+                       {
+                               head.attr('data-toggle', 'collapse')
+                                       .attr('data-parent', this.id('sectiongroup'))
+                                       .attr('data-target', '#' + this.id('panel', sid))
+                                       .on('click', { self: this }, this._ev_panel_open);
+                       }
 
-                                               tabc.appendTo(fields);
-                                               tabc = null;
+                       return head;
+               },
 
-                                               $('<li />').attr('id', theadid).append(
-                                                       $('<a />')
-                                                               .text(this.tabs[j].caption.format(this.tabs[j].id))
-                                                               .attr('href', '#' + tabid)
-                                               ).appendTo(menu);
-                                       }
+               _render_section_body: function(sid, index)
+               {
+                       var body = $('<div />')
+                               .attr('id', this.id('panel', sid))
+                               .attr('data-luci2-panel-index', index)
+                               .attr('data-luci2-sid', sid);
 
-                                       menu.appendTo(body);
-                                       menu = null;
+                       if (this.options.collabsible || this.map.options.collabsible)
+                       {
+                               body.addClass('panel-collapse collapse');
 
-                                       fields.appendTo(body);
-                                       fields = null;
+                               if (index == this.active_panel)
+                                       body.addClass('in');
+                       }
 
-                                       var t = body.tabs({ active: this.active_tab[sid] });
+                       var tab_heads = $('<ul />')
+                               .addClass('nav nav-tabs');
 
-                                       t.on('tabsactivate', { self: this, sid: sid }, function(ev, ui) {
-                                               var d = ev.data;
-                                               d.self.validate();
-                                               d.self.active_tab[d.sid] = parseInt(ui.newPanel.attr('index'));
-                                       });
-                               }
-                               else
-                               {
-                                       for (var j = 0; j < this.tabs[0].fields.length; j++)
-                                               this.tabs[0].fields[j].render(sid).appendTo(fields);
+                       var tab_bodies = $('<div />')
+                               .addClass('form-horizontal tab-content')
+                               .append(tab_heads);
 
-                                       fields.appendTo(body);
-                                       fields = null;
-                               }
+                       for (var j = 0; j < this.tabs.length; j++)
+                       {
+                               tab_heads.append(this._render_tab_head(sid, index, j));
+                               tab_bodies.append(this._render_tab_body(sid, index, j));
+                       }
 
-                               head.appendTo(fieldset);
-                               head = null;
+                       body.append(tab_bodies);
 
-                               body.appendTo(fieldset);
-                               body = null;
+                       if (this.tabs.length <= 1)
+                               tab_heads.hide();
 
-                               allsections = allsections.add(fieldset);
-                               fieldset = null;
+                       return body;
+               },
 
-                               //this.validate(sid);
-                               //
-                               //if (teaser)
-                               //      teaser.append(this.teaser(sid));
-                       }
+               _render_body: function(condensed)
+               {
+                       var s = this.sections();
 
-                       if (this.options.collabsible && s.length > 1)
-                       {
-                               var a = $('<div />').append(allsections).accordion({
-                                       header: '> fieldset > div.cbi-section-head',
-                                       heightStyle: 'content',
-                                       active: this.active_panel
-                               });
+                       if (this.active_panel < 0)
+                               this.active_panel += s.length;
+                       else if (this.active_panel >= s.length)
+                               this.active_panel = s.length - 1;
 
-                               a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
-                                       var h = ui.oldHeader;
-                                       var s = ev.data.self;
-                                       var i = h.attr('cbi-section-id');
+                       var body = $('<ul />')
+                               .addClass('list-group');
 
-                                       h.children('.cbi-section-teaser').empty().append(s.teaser(i));
-                                       s.validate();
-                               });
+                       if (this.options.collabsible)
+                       {
+                               body.attr('id', this.id('sectiongroup'))
+                                       .on('show.bs.collapse', { self: this }, this._ev_panel_collapse);
+                       }
 
-                               a.on('accordionactivate', { self: this }, function(ev, ui) {
-                                       ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
-                               });
+                       if (s.length == 0)
+                       {
+                               body.append($('<li />')
+                                       .addClass('list-group-item text-muted')
+                                       .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.')))
+                       }
 
-                               if (this.options.sortable)
-                               {
-                                       var s = a.sortable({
-                                               axis: 'y',
-                                               handle: 'div.cbi-section-head'
-                                       });
+                       for (var i = 0; i < s.length; i++)
+                       {
+                               var sid = s[i]['.name'];
+                               var inst = this.instance[sid] = { tabs: [ ] };
 
-                                       s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
-                                               var sections = [ ];
-                                               for (var i = 0; i < ev.data.ids.length; i++)
-                                                       sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
-                                               _luci2.uci.order(ev.data.self.map.uci_package, sections);
-                                       });
+                               body.append($('<li />')
+                                       .addClass('list-group-item')
+                                       .append(this._render_section_head(sid, i))
+                                       .append(this._render_section_body(sid, i)));
+                       }
 
-                                       s.on('sortstop', function(ev, ui) {
-                                               ui.item.children('div.cbi-section-head').triggerHandler('focusout');
-                                       });
-                               }
+                       return body;
+               },
 
-                               if (this.options.addremove)
-                                       this._render_add().appendTo(a);
+               render: function(condensed)
+               {
+                       this.instance = { };
 
-                               return a;
-                       }
+                       var panel = $('<div />')
+                               .addClass('panel panel-default')
+                               .append(this._render_head(condensed))
+                               .append(this._render_body(condensed));
 
                        if (this.options.addremove)
-                               allsections = allsections.add(this._render_add());
+                               panel.append($('<div />')
+                                       .addClass('panel-footer')
+                                       .append(this._render_add()));
 
-                       return allsections;
+                       return panel;
                },
 
                finish: function()
@@ -5002,146 +6735,101 @@ function LuCI2()
                        {
                                var sid = s[i]['.name'];
 
-                               this.validate(sid);
+                               this.validate_section(sid);
 
-                               $('#' + this.id('sort', sid))
-                                       .children('.cbi-section-head')
-                                       .children('.cbi-section-teaser')
-                                       .append(this.teaser(sid));
+                               if (i != this.active_panel)
+                                       $('#' + this.id('teaser', sid)).children('span:last')
+                                               .append(this.teaser(sid));
+                               else
+                                       $('#' + this.id('teaser', sid))
+                                               .hide();
                        }
                }
        });
 
        this.cbi.TableSection = this.cbi.TypedSection.extend({
-               render: function()
+               _render_table_head: function()
                {
-                       var allsections = $();
-                       var panel_index = 0;
-
-                       this.instance = { };
-
-                       var s = this.sections();
-
-                       var fieldset = $('<fieldset />')
-                               .addClass('cbi-section');
-
-                       fieldset.append(this._render_caption(sid));
-
-                       if (typeof(this.options.description) == 'string')
-                       {
-                               $('<div />')
-                                       .addClass('cbi-section-descr')
-                                       .text(this.options.description)
-                                       .appendTo(fieldset);
-                       }
-
-                       var fields = $('<div />')
-                               .addClass('cbi-section-node')
-                               .appendTo(fieldset);
-
-                       var table = $('<table />')
-                               .addClass('cbi-section-table')
-                               .appendTo(fields);
-
                        var thead = $('<thead />')
-                               .append($('<tr />').addClass('cbi-section-table-titles'))
-                               .appendTo(table);
+                               .append($('<tr />')
+                                       .addClass('cbi-section-table-titles'));
 
                        for (var j = 0; j < this.tabs[0].fields.length; j++)
-                               $('<th />')
+                               thead.children().append($('<th />')
                                        .addClass('cbi-section-table-cell')
                                        .css('width', this.tabs[0].fields[j].options.width || '')
-                                       .append(this.tabs[0].fields[j].options.caption)
-                                       .appendTo(thead.children());
+                                       .append(this.tabs[0].fields[j].label('caption')));
 
-                       if (this.options.sortable)
-                               $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
+                       if (this.options.addremove !== false || this.options.sortable)
+                               thead.children().append($('<th />')
+                                       .addClass('cbi-section-table-cell')
+                                       .text(' '));
 
-                       if (this.options.addremove !== false)
-                               $('<th />').addClass('cbi-section-table-cell').text(' ').appendTo(thead.children());
+                       return thead;
+               },
 
-                       var tbody = $('<tbody />')
-                               .appendTo(table);
+               _render_table_row: function(sid, index)
+               {
+                       var row = $('<tr />')
+                               .attr('data-luci2-sid', sid);
 
-                       if (s.length == 0)
+                       for (var j = 0; j < this.tabs[0].fields.length; j++)
                        {
-                               $('<tr />')
-                                       .addClass('cbi-section-table-row')
-                                       .append(
-                                               $('<td />')
-                                                       .addClass('cbi-section-table-cell')
-                                                       .addClass('cbi-section-table-placeholder')
-                                                       .attr('colspan', thead.children().children().length)
-                                                       .text(this.options.placeholder || _luci2.tr('This section contains no values yet')))
-                                       .appendTo(tbody);
+                               row.append($('<td />')
+                                       .css('width', this.tabs[0].fields[j].options.width || '')
+                                       .append(this.tabs[0].fields[j].render(sid, true)));
                        }
 
-                       for (var i = 0; i < s.length; i++)
+                       if (this.options.addremove !== false || this.options.sortable)
                        {
-                               var sid = s[i]['.name'];
-                               var inst = this.instance[sid] = { tabs: [ ] };
+                               row.append($('<td />')
+                                       .addClass('text-right')
+                                       .append($('<div />')
+                                               .addClass('btn-group')
+                                               .append(this._render_sort(sid, index))
+                                               .append(this._render_remove(sid, index))));
+                       }
 
-                               var row = $('<tr />')
-                                       .addClass('cbi-section-table-row')
-                                       .appendTo(tbody);
+                       return row;
+               },
 
-                               for (var j = 0; j < this.tabs[0].fields.length; j++)
-                               {
-                                       $('<td />')
-                                               .addClass('cbi-section-table-cell')
-                                               .css('width', this.tabs[0].fields[j].options.width || '')
-                                               .append(this.tabs[0].fields[j].render(sid, true))
-                                               .appendTo(row);
-                               }
+               _render_table_body: function()
+               {
+                       var s = this.sections();
 
-                               if (this.options.sortable)
-                               {
-                                       $('<td />')
-                                               .addClass('cbi-section-table-cell')
-                                               .addClass('cbi-section-table-sort')
-                                               .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/up.gif').attr('title', _luci2.tr('Drag to sort')))
-                                               .append($('<br />'))
-                                               .append($('<img />').attr('src', _luci2.globals.resource + '/icons/cbi/down.gif').attr('title', _luci2.tr('Drag to sort')))
-                                               .appendTo(row);
-                               }
+                       var tbody = $('<tbody />');
 
-                               if (this.options.addremove !== false)
-                               {
-                                       $('<td />')
-                                               .addClass('cbi-section-table-cell')
-                                               .append(this._render_remove(sid))
-                                               .appendTo(row);
-                               }
+                       if (s.length == 0)
+                       {
+                               var cols = this.tabs[0].fields.length;
 
-                               this.validate(sid);
+                               if (this.options.addremove !== false || this.options.sortable)
+                                       cols++;
 
-                               row = null;
+                               tbody.append($('<tr />')
+                                       .append($('<td />')
+                                               .addClass('text-muted')
+                                               .attr('colspan', cols)
+                                               .text(this.label('placeholder') || _luci2.tr('There are no entries defined yet.'))));
                        }
 
-                       if (this.options.sortable)
+                       for (var i = 0; i < s.length; i++)
                        {
-                               var s = tbody.sortable({
-                                       handle: 'td.cbi-section-table-sort'
-                               });
-
-                               s.on('sortupdate', { self: this, ids: s.sortable('toArray') }, function(ev, ui) {
-                                       var sections = [ ];
-                                       for (var i = 0; i < ev.data.ids.length; i++)
-                                               sections.push(ev.data.ids[i].substring(ev.data.ids[i].lastIndexOf('.') + 1));
-                                       _luci2.uci.order(ev.data.self.map.uci_package, sections);
-                               });
+                               var sid = s[i]['.name'];
+                               var inst = this.instance[sid] = { tabs: [ ] };
 
-                               s.on('sortstop', function(ev, ui) {
-                                       ui.item.children('div.cbi-section-head').triggerHandler('focusout');
-                               });
+                               tbody.append(this._render_table_row(sid, i));
                        }
 
-                       if (this.options.addremove)
-                               this._render_add().appendTo(fieldset);
-
-                       fields = table = thead = tbody = null;
+                       return tbody;
+               },
 
-                       return fieldset;
+               _render_body: function(condensed)
+               {
+                       return $('<table />')
+                               .addClass('table table-condensed table-hover')
+                               .append(this._render_table_head())
+                               .append(this._render_table_body());
                }
        });
 
@@ -5149,22 +6837,32 @@ function LuCI2()
                sections: function(cb)
                {
                        var sa = [ ];
-                       var pkg = this.map.uci.values[this.map.uci_package];
+                       var sl = _luci2.uci.sections(this.map.uci_package);
 
-                       for (var s in pkg)
-                               if (pkg[s]['.name'] == this.uci_type)
+                       for (var i = 0; i < sl.length; i++)
+                               if (sl[i]['.name'] == this.uci_type)
                                {
-                                       sa.push(pkg[s]);
+                                       sa.push(sl[i]);
                                        break;
                                }
 
                        if (typeof(cb) == 'function' && sa.length > 0)
-                               cb.apply(this, [ sa[0] ]);
+                               cb.call(this, sa[0]);
 
                        return sa;
                }
        });
 
+       this.cbi.SingleSection = this.cbi.NamedSection.extend({
+               render: function()
+               {
+                       this.instance = { };
+                       this.instance[this.uci_type] = { tabs: [ ] };
+
+                       return this._render_section_body(this.uci_type, 0);
+               }
+       });
+
        this.cbi.DummySection = this.cbi.TypedSection.extend({
                sections: function(cb)
                {
@@ -5175,7 +6873,7 @@ function LuCI2()
                }
        });
 
-       this.cbi.Map = AbstractWidget.extend({
+       this.cbi.Map = this.ui.AbstractWidget.extend({
                init: function(uci_package, options)
                {
                        var self = this;
@@ -5184,27 +6882,37 @@ function LuCI2()
                        this.sections = [ ];
                        this.options = _luci2.defaults(options, {
                                save:    function() { },
-                               prepare: function() {
-                                       return _luci2.uci.writable(function(writable) {
-                                               self.options.readonly = !writable;
-                                       });
-                               }
+                               prepare: function() { }
                        });
                },
 
-               load: function()
+               _load_cb: function()
                {
-                       this.uci = {
-                               newid:   0,
-                               values:  { },
-                               creates: { },
-                               changes: { },
-                               deletes: { }
-                       };
+                       var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
+
+                       for (var i = 0; i < this.sections.length; i++)
+                       {
+                               for (var f in this.sections[i].fields)
+                               {
+                                       if (typeof(this.sections[i].fields[f].load) != 'function')
+                                               continue;
+
+                                       var s = this.sections[i].sections();
+                                       for (var j = 0; j < s.length; j++)
+                                       {
+                                               var rv = this.sections[i].fields[f].load(s[j]['.name']);
+                                               if (_luci2.isDeferred(rv))
+                                                       deferreds.push(rv);
+                                       }
+                               }
+                       }
 
-                       if (typeof(this.active_panel) == 'undefined')
-                               this.active_panel = 0;
+                       return $.when.apply($, deferreds);
+               },
 
+               load: function()
+               {
+                       var self = this;
                        var packages = { };
 
                        for (var i = 0; i < this.sections.length; i++)
@@ -5212,126 +6920,124 @@ function LuCI2()
 
                        packages[this.uci_package] = true;
 
-                       var load_cb = this._load_cb || (this._load_cb = $.proxy(function(packages) {
-                               for (var i = 0; i < packages.length; i++)
-                               {
-                                       this.uci.values[packages[i]['.package']] = packages[i];
-                                       delete packages[i]['.package'];
-                               }
+                       for (var pkg in packages)
+                               if (!_luci2.uci.writable(pkg))
+                                       this.options.readonly = true;
 
-                               var deferreds = [ _luci2.deferrable(this.options.prepare()) ];
+                       return _luci2.uci.load(_luci2.toArray(packages)).then(function() {
+                               return self._load_cb();
+                       });
+               },
 
-                               for (var i = 0; i < this.sections.length; i++)
-                               {
-                                       for (var f in this.sections[i].fields)
-                                       {
-                                               if (typeof(this.sections[i].fields[f].load) != 'function')
-                                                       continue;
+               _ev_tab: function(ev)
+               {
+                       var self = ev.data.self;
 
-                                               var s = this.sections[i].sections();
-                                               for (var j = 0; j < s.length; j++)
-                                               {
-                                                       var rv = this.sections[i].fields[f].load(s[j]['.name']);
-                                                       if (_luci2.isDeferred(rv))
-                                                               deferreds.push(rv);
-                                               }
-                                       }
-                               }
+                       self.validate();
+                       self.active_tab = parseInt(ev.target.getAttribute('data-luci2-tab-index'));
+               },
 
-                               return $.when.apply($, deferreds);
-                       }, this));
+               _render_tab_head: function(tab_index)
+               {
+                       var section = this.sections[tab_index];
+                       var cur = this.active_tab || 0;
 
-                       _luci2.rpc.batch();
+                       var tabh = $('<li />')
+                               .append($('<a />')
+                                       .attr('id', section.id('sectiontab'))
+                                       .attr('href', '#' + section.id('section'))
+                                       .attr('data-toggle', 'tab')
+                                       .attr('data-luci2-tab-index', tab_index)
+                                       .text(section.label('caption') + ' ')
+                                       .append($('<span />')
+                                               .addClass('badge'))
+                                       .on('shown.bs.tab', { self: this }, this._ev_tab));
 
-                       for (var pkg in packages)
-                               _luci2.uci.get_all(pkg);
+                       if (cur == tab_index)
+                               tabh.addClass('active');
 
-                       return _luci2.rpc.flush().then(load_cb);
+                       return tabh;
                },
 
-               render: function()
+               _render_tab_body: function(tab_index)
                {
-                       var map = $('<div />').addClass('cbi-map');
-
-                       if (typeof(this.options.caption) == 'string')
-                               $('<h2 />').text(this.options.caption).appendTo(map);
-
-                       if (typeof(this.options.description) == 'string')
-                               $('<div />').addClass('cbi-map-descr').text(this.options.description).appendTo(map);
+                       var section = this.sections[tab_index];
+                       var desc = section.label('description');
+                       var cur = this.active_tab || 0;
 
-                       var sections = $('<div />').appendTo(map);
+                       var tabb = $('<div />')
+                               .addClass('tab-pane')
+                               .attr('id', section.id('section'))
+                               .attr('data-luci2-tab-index', tab_index);
 
-                       for (var i = 0; i < this.sections.length; i++)
-                       {
-                               var s = this.sections[i].render();
+                       if (cur == tab_index)
+                               tabb.addClass('active');
 
-                               if (this.options.readonly || this.sections[i].options.readonly)
-                                       s.find('input, select, button, img.cbi-button').attr('disabled', true);
+                       if (desc)
+                               tabb.append($('<p />')
+                                       .text(desc));
 
-                               s.appendTo(sections);
+                       var s = section.render(this.options.tabbed);
 
-                               if (this.sections[i].options.active)
-                                       this.active_panel = i;
-                       }
+                       if (this.options.readonly || section.options.readonly)
+                               s.find('input, select, button, img.cbi-button').attr('disabled', true);
 
-                       if (this.options.collabsible)
-                       {
-                               var a = sections.accordion({
-                                       header: '> fieldset > div.cbi-section-head',
-                                       heightStyle: 'content',
-                                       active: this.active_panel
-                               });
+                       tabb.append(s);
 
-                               a.on('accordionbeforeactivate', { self: this }, function(ev, ui) {
-                                       var h = ui.oldHeader;
-                                       var s = ev.data.self.sections[parseInt(h.attr('cbi-section-num'))];
-                                       var i = h.attr('cbi-section-id');
+                       return tabb;
+               },
 
-                                       h.children('.cbi-section-teaser').empty().append(s.teaser(i));
+               _render_body: function()
+               {
+                       var tabs = $('<ul />')
+                               .addClass('nav nav-tabs');
 
-                                       for (var i = 0; i < ev.data.self.sections.length; i++)
-                                               ev.data.self.sections[i].validate();
-                               });
+                       var body = $('<div />')
+                               .append(tabs);
 
-                               a.on('accordionactivate', { self: this }, function(ev, ui) {
-                                       ev.data.self.active_panel = parseInt(ui.newPanel.attr('index'));
-                               });
+                       for (var i = 0; i < this.sections.length; i++)
+                       {
+                               tabs.append(this._render_tab_head(i));
+                               body.append(this._render_tab_body(i));
                        }
 
-                       if (this.options.pageaction !== false)
-                       {
-                               var a = $('<div />')
-                                       .addClass('cbi-page-actions')
-                                       .appendTo(map);
+                       if (this.options.tabbed)
+                               body.addClass('tab-content');
+                       else
+                               tabs.hide();
 
-                               $('<input />')
-                                       .addClass('cbi-button').addClass('cbi-button-apply')
-                                       .attr('type', 'button')
-                                       .val(_luci2.tr('Save & Apply'))
-                                       .appendTo(a);
+                       return body;
+               },
 
-                               $('<input />')
-                                       .addClass('cbi-button').addClass('cbi-button-save')
-                                       .attr('type', 'button')
-                                       .val(_luci2.tr('Save'))
-                                       .click({ self: this }, function(ev) { ev.data.self.send(); })
-                                       .appendTo(a);
+               render: function()
+               {
+                       var map = $('<form />');
 
-                               $('<input />')
-                                       .addClass('cbi-button').addClass('cbi-button-reset')
-                                       .attr('type', 'button')
-                                       .val(_luci2.tr('Reset'))
-                                       .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); })
-                                       .appendTo(a);
+                       if (typeof(this.options.caption) == 'string')
+                               map.append($('<h2 />')
+                                       .text(this.options.caption));
 
-                               a = null;
-                       }
+                       if (typeof(this.options.description) == 'string')
+                               map.append($('<p />')
+                                       .text(this.options.description));
 
-                       var top = $('<form />').append(map);
+                       map.append(this._render_body());
 
-                       map = null;
+                       if (this.options.pageaction !== false)
+                       {
+                               map.append($('<div />')
+                                       .addClass('panel panel-default panel-body text-right')
+                                       .append($('<div />')
+                                               .addClass('btn-group')
+                                               .append(_luci2.ui.button(_luci2.tr('Save & Apply'), 'primary')
+                                                       .click({ self: this }, function(ev) {  }))
+                                               .append(_luci2.ui.button(_luci2.tr('Save'), 'default')
+                                                       .click({ self: this }, function(ev) { ev.data.self.send(); }))
+                                               .append(_luci2.ui.button(_luci2.tr('Reset'), 'default')
+                                                       .click({ self: this }, function(ev) { ev.data.self.insertInto(ev.data.self.target); }))));
+                       }
 
-                       return top;
+                       return map;
                },
 
                finish: function()
@@ -5382,160 +7088,22 @@ function LuCI2()
 
                add: function(conf, type, name)
                {
-                       var c = this.uci.creates;
-                       var s = '.new.%d'.format(this.uci.newid++);
-
-                       if (!c[conf])
-                               c[conf] = { };
-
-                       c[conf][s] = {
-                               '.type':      type,
-                               '.name':      s,
-                               '.create':    name,
-                               '.anonymous': !name
-                       };
-
-                       return s;
+                       return _luci2.uci.add(conf, type, name);
                },
 
                remove: function(conf, sid)
                {
-                       var n = this.uci.creates;
-                       var c = this.uci.changes;
-                       var d = this.uci.deletes;
-
-                       /* requested deletion of a just created section */
-                       if (sid.indexOf('.new.') == 0)
-                       {
-                               if (n[conf])
-                                       delete n[conf][sid];
-                       }
-                       else
-                       {
-                               if (c[conf])
-                                       delete c[conf][sid];
-
-                               if (!d[conf])
-                                       d[conf] = { };
-
-                               d[conf][sid] = true;
-                       }
-               },
-
-               ucisections: function(conf, cb)
-               {
-                       var sa = [ ];
-                       var pkg = this.uci.values[conf];
-                       var crt = this.uci.creates[conf];
-                       var del = this.uci.deletes[conf];
-
-                       if (!pkg)
-                               return sa;
-
-                       for (var s in pkg)
-                               if (!del || del[s] !== true)
-                                       sa.push(pkg[s]);
-
-                       sa.sort(function(a, b) { return a['.index'] - b['.index'] });
-
-                       if (crt)
-                               for (var s in crt)
-                                       sa.push(crt[s]);
-
-                       if (typeof(cb) == 'function')
-                               for (var i = 0; i < sa.length; i++)
-                                       cb.apply(this, [ sa[i] ]);
-
-                       return sa;
+                       return _luci2.uci.remove(conf, sid);
                },
 
                get: function(conf, sid, opt)
                {
-                       var v = this.uci.values;
-                       var n = this.uci.creates;
-                       var c = this.uci.changes;
-                       var d = this.uci.deletes;
-
-                       /* requested option in a just created section */
-                       if (sid.indexOf('.new.') == 0)
-                       {
-                               if (!n[conf])
-                                       return undefined;
-
-                               if (typeof(opt) == 'undefined')
-                                       return (n[conf][sid] || { });
-
-                               return n[conf][sid][opt];
-                       }
-
-                       /* requested an option value */
-                       if (typeof(opt) != 'undefined')
-                       {
-                               /* check whether option was deleted */
-                               if (d[conf] && d[conf][sid])
-                               {
-                                       if (d[conf][sid] === true)
-                                               return undefined;
-
-                                       for (var i = 0; i < d[conf][sid].length; i++)
-                                               if (d[conf][sid][i] == opt)
-                                                       return undefined;
-                               }
-
-                               /* check whether option was changed */
-                               if (c[conf] && c[conf][sid] && typeof(c[conf][sid][opt]) != 'undefined')
-                                       return c[conf][sid][opt];
-
-                               /* return base value */
-                               if (v[conf] && v[conf][sid])
-                                       return v[conf][sid][opt];
-
-                               return undefined;
-                       }
-
-                       /* requested an entire section */
-                       if (v[conf])
-                               return (v[conf][sid] || { });
-
-                       return undefined;
+                       return _luci2.uci.get(conf, sid, opt);
                },
 
                set: function(conf, sid, opt, val)
                {
-                       var n = this.uci.creates;
-                       var c = this.uci.changes;
-                       var d = this.uci.deletes;
-
-                       if (sid.indexOf('.new.') == 0)
-                       {
-                               if (n[conf] && n[conf][sid])
-                               {
-                                       if (typeof(val) != 'undefined')
-                                               n[conf][sid][opt] = val;
-                                       else
-                                               delete n[conf][sid][opt];
-                               }
-                       }
-                       else if (typeof(val) != 'undefined')
-                       {
-                               if (!c[conf])
-                                       c[conf] = { };
-
-                               if (!c[conf][sid])
-                                       c[conf][sid] = { };
-
-                               c[conf][sid][opt] = val;
-                       }
-                       else
-                       {
-                               if (!d[conf])
-                                       d[conf] = { };
-
-                               if (!d[conf][sid])
-                                       d[conf][sid] = [ ];
-
-                               d[conf][sid].push(opt);
-                       }
+                       return _luci2.uci.set(conf, sid, opt, val);
                },
 
                validate: function()
@@ -5543,40 +7111,46 @@ function LuCI2()
                        var rv = true;
 
                        for (var i = 0; i < this.sections.length; i++)
+                       {
                                if (!this.sections[i].validate())
                                        rv = false;
+                       }
 
                        return rv;
                },
 
                save: function()
                {
-                       if (this.options.readonly)
+                       var self = this;
+
+                       if (self.options.readonly)
                                return _luci2.deferrable();
 
-                       var deferreds = [ _luci2.deferrable(this.options.save()) ];
+                       var deferreds = [ ];
 
-                       for (var i = 0; i < this.sections.length; i++)
+                       for (var i = 0; i < self.sections.length; i++)
                        {
-                               if (this.sections[i].options.readonly)
+                               if (self.sections[i].options.readonly)
                                        continue;
 
-                               for (var f in this.sections[i].fields)
+                               for (var f in self.sections[i].fields)
                                {
-                                       if (typeof(this.sections[i].fields[f].save) != 'function')
+                                       if (typeof(self.sections[i].fields[f].save) != 'function')
                                                continue;
 
-                                       var s = this.sections[i].sections();
+                                       var s = self.sections[i].sections();
                                        for (var j = 0; j < s.length; j++)
                                        {
-                                               var rv = this.sections[i].fields[f].save(s[j]['.name']);
+                                               var rv = self.sections[i].fields[f].save(s[j]['.name']);
                                                if (_luci2.isDeferred(rv))
                                                        deferreds.push(rv);
                                        }
                                }
                        }
 
-                       return $.when.apply($, deferreds);
+                       return $.when.apply($, deferreds).then(function() {
+                               return _luci2.deferrable(self.options.save());
+                       });
                },
 
                send: function()
@@ -5584,55 +7158,16 @@ function LuCI2()
                        if (!this.validate())
                                return _luci2.deferrable();
 
-                       var send_cb = this._send_cb || (this._send_cb = $.proxy(function() {
-                               _luci2.rpc.batch();
-
-                               if (this.uci.creates)
-                                       for (var c in this.uci.creates)
-                                               for (var s in this.uci.creates[c])
-                                               {
-                                                       var r = {
-                                                               config: c,
-                                                               values: { }
-                                                       };
-
-                                                       for (var k in this.uci.creates[c][s])
-                                                       {
-                                                               if (k == '.type')
-                                                                       r.type = this.uci.creates[c][s][k];
-                                                               else if (k == '.create')
-                                                                       r.name = this.uci.creates[c][s][k];
-                                                               else if (k.charAt(0) != '.')
-                                                                       r.values[k] = this.uci.creates[c][s][k];
-                                                       }
-
-                                                       _luci2.uci.add(r.config, r.type, r.name, r.values);
-                                               }
-
-                               if (this.uci.changes)
-                                       for (var c in this.uci.changes)
-                                               for (var s in this.uci.changes[c])
-                                                       _luci2.uci.set(c, s, this.uci.changes[c][s]);
-
-                               if (this.uci.deletes)
-                                       for (var c in this.uci.deletes)
-                                               for (var s in this.uci.deletes[c])
-                                               {
-                                                       var o = this.uci.deletes[c][s];
-                                                       _luci2.uci['delete'](c, s, (o === true) ? undefined : o);
-                                               }
-
-                               return _luci2.rpc.flush().then(function() {
-                                       return _luci2.ui.updateChanges();
-                               });
-                       }, this));
-
                        var self = this;
 
                        _luci2.ui.saveScrollTop();
                        _luci2.ui.loading(true);
 
-                       return this.save().then(send_cb).then(function() {
+                       return this.save().then(function() {
+                               return _luci2.uci.save();
+                       }).then(function() {
+                               return _luci2.ui.updateChanges();
+                       }).then(function() {
                                return self.load();
                        }).then(function() {
                                self.redraw();