wl dual-band: get the available bands list from the driver
[tomato.git] / release / src / router / www / tomato.js
blob9e3e1b30961b6b4942bedbc90e74a7f7909bbec0
1 /*
2         Tomato GUI
3         Copyright (C) 2006-2010 Jonathan Zarate
4         http://www.polarcloud.com/tomato/
6         For use with Tomato Firmware only.
7         No part of this file may be used without permission.
8 */
10 // -----------------------------------------------------------------------------
12 Array.prototype.find = function(v) {
13         for (var i = 0; i < this.length; ++i)
14                 if (this[i] == v) return i;
15         return -1;
18 Array.prototype.remove = function(v) {
19         for (var i = 0; i < this.length; ++i) {
20                 if (this[i] == v) {
21                         this.splice(i, 1);
22                         return true;
23                 }
24         }
25         return false;
28 // -----------------------------------------------------------------------------
30 String.prototype.trim = function() {
31         return this.replace(/^\s+/, '').replace(/\s+$/, '');
34 // -----------------------------------------------------------------------------
36 Number.prototype.pad = function(min) {
37         var s = this.toString();
38         while (s.length < min) s = '0' + s;
39         return s;
42 Number.prototype.hex = function(min)
44         var h = '0123456789ABCDEF';
45         var n = this;
46         var s = '';
47         do {
48                 s = h.charAt(n & 15) + s;
49                 n = n >>> 4;
50         } while ((--min > 0) || (n > 0));
51         return s;
54 // -----------------------------------------------------------------------------
56 // ---- Element.protoype. doesn't work with all browsers
58 var elem = {
59         getOffset: function(e) {
60                 var r = { x: 0, y: 0 };
61                 e = E(e);
62                 while (e.offsetParent) {
63                         r.x += e.offsetLeft;
64                         r.y += e.offsetTop;
65                         e = e.offsetParent;
66                 }
67                 return r;
68         },
70         addClass: function(e, name) {
71                 if ((e = E(e)) == null) return;
72                 var a = e.className.split(/\s+/);
73                 var k = 0;
74                 for (var i = 1; i < arguments.length; ++i) {
75                         if (a.find(arguments[i]) == -1) {
76                                 a.push(arguments[i]);
77                                 k = 1;
78                         }
79                 }
80                 if (k) e.className = a.join(' ');
81         },
83         removeClass: function(e, name) {
84                 if ((e = E(e)) == null) return;
85                 var a = e.className.split(/\s+/);
86                 var k = 0;
87                 for (var i = 1; i < arguments.length; ++i)
88                         k |= a.remove(arguments[i]);
89                 if (k) e.className = a.join(' ');
90         },
92         remove: function(e) {
93                  if ((e = E(e)) != null) e.parentNode.removeChild(e);
94         },
96     parentElem: function(e, tagName) {
97                 e = E(e);
98                 tagName = tagName.toUpperCase();
99                 while (e.parentNode) {
100                         e = e.parentNode;
101                         if (e.tagName == tagName) return e;
102                 }
103                 return null;
104         },
106         display: function() {
107                 var enable = arguments[arguments.length - 1];
108                 for (var i = 0; i < arguments.length - 1; ++i) {
109                         E(arguments[i]).style.display = enable ? '' : 'none';
110                 }
111         },
113         isVisible: function(e) {
114                 e = E(e);
115                 while (e) {
116                         if ((e.style.visibility != 'visible') || (e.style.display == 'none')) return false;
117                         e = e.parentNode;
118                 }
119                 return true;
120         },
122         setInnerHTML: function(e, html) {
123                  e = E(e);
124                  if (e.innerHTML != html) e.innerHTML = html;   // reduce flickering
125         }
128 // -----------------------------------------------------------------------------
130 var docu = {
131         getViewSize: function() {
132                 if (window.innerHeight) {
133                         return { width: window.innerWidth, height: window.innerHeight };
134                 }
135                 else if (document.documentElement && document.documentElement.clientHeight) {
136                         return { width: document.documentElement.clientWidth, height: document.documentElement.clientHeight };
137                 }
138                 return { width: document.body.clientWidth, height: document.body.clientHeight };
139         },
141         getPageOffset: function()
142         {
143                 if (typeof(window.pageYOffset) != 'undefined') {
144                         return { x: window.pageXOffset, y: window.pageYOffset };
145                 }
146                 else if ((document.documentElement) && (typeof(document.documentElement.scrollTop) != 'undefined')) {
147                         return { x: document.documentElement.scrollLeft, y: document.documentElement.scrollTop };
148                 }
149                 return { x: document.body.scrollLeft, y: document.body.scrollTop };
150         }
153 // -----------------------------------------------------------------------------
155 var fields = {
156         getAll: function(e) {
157                 var a = [];
158                 switch (e.tagName) {
159                 case 'INPUT':
160                 case 'SELECT':
161                         a.push(e);
162                         break;
163                 default:
164                         if (e.childNodes) {
165                                 for (var i = 0; i < e.childNodes.length; ++i) {
166                                         a = a.concat(fields.getAll(e.childNodes[i]));
167                                 }
168                         }
169                 }
170                 return a;
171         },
172         disableAll: function(e, d) {
173                 var i;
175                 if ((typeof(e.tagName) == 'undefined') && (typeof(e) != 'string')) {
176                         for (i = e.length - 1; i >= 0; --i) {
177                                 e[i].disabled = d;
178                         }
179                 }
180                 else {
181                         var a = this.getAll(E(e));
182                         for (var i = a.length - 1; i >= 0; --i) {
183                                 a[i].disabled = d;
184                         }
185                 }
186         },
187         radio: {
188                 selected: function(e) {
189                         for (var i = 0; i < e.length; ++i) {
190                                 if (e[i].checked) return e[i];
191                         }
192                         return null;
193                 },
194                 find: function(e, value) {
195                         for (var i = 0; i < e.length; ++i) {
196                                 if (e[i].value == value) return e[i];
197                         }
198                         return null;
199                 }
200         }
203 // -----------------------------------------------------------------------------
205 var form = {
206         submitHidden: function(url, fields) {
207                 var fom, body;
209                 fom = document.createElement('FORM');
210                 fom.action = url;
211                 fom.method = 'post';
212                 for (var f in fields) {
213                         var e = document.createElement('INPUT');
214                         e.type = 'hidden';
215                         e.name = f;
216                         e.value = fields[f];
217                         fom.appendChild(e);
218                 }
219                 body = document.getElementsByTagName('body')[0];
220                 fom = body.appendChild(fom);
221                 this.submit(fom);
222                 body.removeChild(fom);
223         },
225         submit: function(fom, async, url) {
226                 var e, v, f, i, wait, msg, sb, cb;
228                 fom = E(fom);
230                 if (isLocal()) {
231                         this.dump(fom, async, url);
232                         return;
233                 }
235                 if (this.xhttp) return;
237                 if ((sb = E('save-button')) != null) sb.disabled = 1;
238                 if ((cb = E('cancel-button')) != null) cb.disabled = 1;
240                 if ((!async) || (!useAjax())) {
241                         this.addId(fom);
242                         if (url) fom.action = url;
243                         fom.submit();
244                         return;
245                 }
247                 v = ['_ajax=1'];
248                 wait = 5;
249                 for (var i = 0; i < fom.elements.length; ++i) {
250                         f = fom.elements[i];
251                         if ((f.disabled) || (f.name == '') || (f.name.substr(0, 2) == 'f_')) continue;
252                         if ((f.tagName == 'INPUT') && ((f.type == 'CHECKBOX') || (f.type == 'RADIO')) && (!f.checked)) continue;
253                         if (f.name == '_nextwait') {
254                                 wait = f.value * 1;
255                                 if (isNaN(wait)) wait = 5;
256                                         else wait = Math.abs(wait);
257                         }
258                         v.push(escapeCGI(f.name) + '=' + escapeCGI(f.value));
259                 }
261                 if ((msg = E('footer-msg')) != null) {
262                         msg.innerHTML = 'Saving...';
263                         msg.style.visibility = 'visible';
264                 }
266                 this.xhttp = new XmlHttp();
267                 this.xhttp.onCompleted = function(text, xml) {
268                         if (msg) {
269                                 if (text.match(/@msg:(.+)/)) msg.innerHTML = escapeHTML(RegExp.$1);
270                                         else msg.innerHTML = 'Saved';
271                         }
272                         setTimeout(
273                                 function() {
274                                         if (sb) sb.disabled = 0;
275                                         if (cb) cb.disabled = 0;
276                                         if (msg) msg.style.visibility = 'hidden';
277                                         if (typeof(submit_complete) != 'undefined') submit_complete();
278                                 }, wait * 1100);
279                         form.xhttp = null;
280                 }
281                 this.xhttp.onError = function(x) {
282                         if (url) fom.action = url;
283                         fom.submit();
284                 }
286                 this.xhttp.post(url ? url : fom.action, v.join('&'));
287         },
289         addId: function(fom) {
290                 var e;
292                 if (typeof(fom._http_id) == 'undefined') {
293                         e = document.createElement('INPUT');
294                         e.type = 'hidden';
295                         e.name = '_http_id';
296                         e.value = nvram.http_id;
297                         fom.appendChild(e);
298                 }
299                 else {
300                         fom._http_id.value = nvram.http_id;
301                 }
302         },
304         addIdAction: function(fom) {
305                 if (fom.action.indexOf('?') != -1) fom.action += '&_http_id=' + nvram.http_id;
306                         else fom.action += '?_http_id=' + nvram.http_id;
307         },
309         dump: function(fom, async, url) {
310         }
313 // -----------------------------------------------------------------------------
315 var ferror = {
316         set: function(e, message, quiet) {
317                 if ((e = E(e)) == null) return;
318                 e._error_msg = message;
319                 e._error_org = e.title;
320                 e.title = message;
321                 elem.addClass(e, 'error');
322                 if (!quiet) this.show(e);
323         },
325         clear: function(e) {
326                 if ((e = E(e)) == null) return;
327                 e.title = e._error_org || '';
328                 elem.removeClass(e, 'error');
329                 e._error_msg = null;
330                 e._error_org = null;
331         },
333         clearAll: function(e) {
334                 for (var i = 0; i < e.length; ++i)
335                         this.clear(e[i]);
336         },
338         show: function(e) {
339                 if ((e = E(e)) == null) return;
340                 if (!e._error_msg) return;
341                 elem.addClass(e, 'error-focused');
342                 e.focus();
343                 alert(e._error_msg);
344                 elem.removeClass(e, 'error-focused');
345         },
347         ok: function(e) {
348                 if ((e = E(e)) == null) return 0;
349         return !e._error_msg;
350         }
353 // -----------------------------------------------------------------------------
355 function _v_range(e, quiet, min, max, name)
357         if ((e = E(e)) == null) return 0;
358         var v = e.value;
359         if ((!v.match(/^ *[-\+]?\d+ *$/)) || (v < min) || (v > max)) {
360                 ferror.set(e, 'Invalid ' + name + '. Valid range: ' + min + '-' + max, quiet);
361                 return 0;
362         }
363         e.value = v * 1;
364         ferror.clear(e);
365         return 1;
368 function v_range(e, quiet, min, max)
370         return _v_range(e, quiet, min, max, 'number');
373 function v_port(e, quiet)
375         return _v_range(e, quiet, 1, 0xFFFF, 'port');
378 function v_octet(e, quiet)
380         return _v_range(e, quiet, 1, 254, 'address');
383 function v_mins(e, quiet, min, max)
385         var v, m;
387         if ((e = E(e)) == null) return 0;
388         if (e.value.match(/^\s*(.+?)([mhd])?\s*$/)) {
389                 m = 1;
390                 if (RegExp.$2 == 'h') m = 60;
391                         else if (RegExp.$2 == 'd') m = 60 * 24;
392                 v = Math.round(RegExp.$1 * m);
393                 if (!isNaN(v)) {
394                         e.value = v;
395                         return _v_range(e, quiet, min, max, 'minutes');
396                 }
397         }
398         ferror.set(e, 'Invalid number of minutes.', quiet);
399         return 0;
402 function v_macip(e, quiet, bok, ipp)
404         var s, a, b, c, d, i;
406         if ((e = E(e)) == null) return 0;
407         s = e.value.replace(/\s+/g, '');
409         if ((a = fixMAC(s)) != null) {
410                 if (isMAC0(a)) {
411                         if (bok) {
412                                 e.value = '';
413                         }
414                         else {
415                                 ferror.set(e, 'Invalid MAC or IP address');
416                                 return false;
417                         }
418                 }
419         else e.value = a;
420                 ferror.clear(e);
421                 return true;
422         }
424         a = s.split('-');
425         if (a.length > 2) {
426                 ferror.set(e, 'Invalid IP address range', quiet);
427                 return false;
428         }
429         c = 0;
430         for (i = 0; i < a.length; ++i) {
431                 b = a[i];
432                 if (b.match(/^\d+$/)) b = ipp + b;
434                 b = fixIP(b);
435                 if (!b) {
436                         ferror.set(e, 'Invalid IP address', quiet);
437                         return false;
438                 }
440                 if (b.indexOf(ipp) != 0) {
441                         ferror.set(e, 'IP address outside of LAN', quiet);
442                         return false;
443                 }
445                 d = (b.split('.'))[3];
446                 if (d <= c) {
447                         ferror.set(e, 'Invalid IP address range', quiet);
448                         return false;
449                 }
451                 a[i] = c = d;
452         }
453         e.value = ipp + a.join('-');
454         return true;
457 function fixIP(ip, x)
459         var a, n, i;
461         a = ip.split('.');
462         if (a.length != 4) return null;
463         for (i = 0; i < 4; ++i) {
464                 n = a[i] * 1;
465                 if ((isNaN(n)) || (n < 0) || (n > 255)) return null;
466                 a[i] = n;
467         }
468         if ((x) && ((a[3] == 0) || (a[3] == 255))) return null;
469         return a.join('.');
472 function v_ip(e, quiet, x)
474         var ip;
476         if ((e = E(e)) == null) return 0;
477         ip = fixIP(e.value, x);
478         if (!ip) {
479                 ferror.set(e, 'Invalid IP address', quiet);
480                 return false;
481         }
482         e.value = ip;
483         ferror.clear(e);
484         return true;
487 function v_ipz(e, quiet)
489         if ((e = E(e)) == null) return 0;
490         if (e.value == '') e.value = '0.0.0.0';
491         return v_ip(e, quiet);
494 function v_dns(e, quiet)
496         if ((e = E(e)) == null) return 0;       
497         if (e.value == '') {
498                 e.value = '0.0.0.0';
499         }
500         else {
501                 var s = e.value.split(':');
502                 if (s.length == 1) {
503                         s.push(53);
504                 }
505                 else if (s.length != 2) {
506                         ferror.set(e, 'Invalid IP address or port', quiet);
507                         return false;
508                 }
509                 
510                 if ((s[0] = fixIP(s[0])) == null) {
511                         ferror.set(e, 'Invalid IP address', quiet);
512                         return false;
513                 }
515                 if ((s[1] = fixPort(s[1], -1)) == -1) {
516                         ferror.set(e, 'Invalid port', quiet);
517                         return false;
518                 }
519         
520                 if (s[1] == 53) {
521                         e.value = s[0];
522                 }
523                 else {
524                         e.value = s.join(':');
525                 }
526         }
528         ferror.clear(e);
529         return true;
532 function aton(ip)
534         var o, x, i;
536         // ---- this is goofy because << mangles numbers as signed
537         o = ip.split('.');
538         x = '';
539         for (i = 0; i < 4; ++i) x += (o[i] * 1).hex(2);
540         return parseInt(x, 16);
543 function ntoa(ip)
545         return ((ip >> 24) & 255) + '.' + ((ip >> 16) & 255) + '.' + ((ip >> 8) & 255) + '.' + (ip & 255);
549 // ---- 1.2.3.4, 1.2.3.4/24, 1.2.3.4/255.255.255.0, 1.2.3.4-1.2.3.5
550 function _v_iptip(e, ip, quiet)
552         var ma, x, y, z, oip;
553         var a, b;
555         oip = ip;
557         // x.x.x.x - y.y.y.y
558         if (ip.match(/^(.*)-(.*)$/)) {
559                 a = fixIP(RegExp.$1);
560                 b = fixIP(RegExp.$2);
561                 if ((a == null) || (b == null)) {
562                         ferror.set(e, 'Invalid IP address range - ' + oip, quiet);
563                         return null;
564                 }
565                 ferror.clear(e);
567                 if (aton(a) > aton(b)) return b + '-' + a;
568                 return a + '-' + b;
569         }
571         ma = '';
573         // x.x.x.x/nn
574         // x.x.x.x/y.y.y.y
575         if (ip.match(/^(.*)\/(.*)$/)) {
576                 ip = RegExp.$1;
577                 b = RegExp.$2;
579                 ma = b * 1;
580                 if (isNaN(ma)) {
581                         ma = fixIP(b);
582                         if ((ma == null) || (!_v_netmask(ma))) {
583                                 ferror.set(e, 'Invalid netmask - ' + oip, quiet);
584                                 return null;
585                         }
586                 }
587                 else {
588                         if ((ma < 0) || (ma > 32)) {
589                                 ferror.set(e, 'Invalid netmask - ' + oip, quiet);
590                                 return null;
591                         }
592                 }
593         }
595         ip = fixIP(ip);
596         if (!ip) {
597                 ferror.set(e, 'Invalid IP address - ' + oip, quiet);
598                 return null;
599         }
601         ferror.clear(e);
602         return ip + ((ma != '') ? ('/' + ma) : '');
605 function v_iptip(e, quiet, multi)
607         var v, i;
609         if ((e = E(e)) == null) return 0;
610         v = e.value.split(',');
611         if (multi) {
612                 if (v.length > multi) {
613                         ferror.set(e, 'Too many IP addresses', quiet);
614                         return 0;
615                 }
616         }
617         else {
618                 if (v.length > 1) {
619                         ferror.set(e, 'Invalid IP address', quiet);
620                         return 0;
621                 }
622         }
623         for (i = 0; i < v.length; ++i) {
624                 if ((v[i] = _v_iptip(e, v[i], quiet)) == null) return 0;
625         }
626         e.value = v.join(', ');
627         return 1;
631 function fixPort(p, def)
633         if (def == null) def = -1;
634         if (p == null) return def;
635         p *= 1;
636         if ((isNaN(p) || (p < 1) || (p > 65535) || (('' + p).indexOf('.') != -1))) return def;
637         return p;
640 function _v_portrange(e, quiet, v)
642         if (v.match(/^(.*)[-:](.*)$/)) {
643                 var x = RegExp.$1;
644                 var y = RegExp.$2;
646                 x = fixPort(x, -1);
647                 y = fixPort(y, -1);
648                 if ((x == -1) || (y == -1)) {
649                         ferror.set(e, 'Invalid port range: ' + v, quiet);
650                         return null;
651                 }
652                 if (x > y) {
653                         v = x;
654                         x = y;
655                         y = v;
656                 }
657                 ferror.clear(e);
658                 if (x == y) return x;
659                 return x + '-' + y;
660         }
662         v = fixPort(v, -1);
663         if (v == -1) {
664                 ferror.set(e, 'Invalid port', quiet);
665                 return null;
666         }
668         ferror.clear(e);
669         return v;
672 function v_portrange(e, quiet)
674         var v;
676         if ((e = E(e)) == null) return 0;
677         v = _v_portrange(e, quiet, e.value);
678         if (v == null) return 0;
679         e.value = v;
680         return 1;
683 function v_iptport(e, quiet)
685         var a, i, v, q;
687         if ((e = E(e)) == null) return 0;
689         a = e.value.split(/[,\.]/);
691         if (a.length == 0) {
692                 ferror.set(e, 'Expecting a list of ports or port range.', quiet);
693                 return 0;
694         }
695         if (a.length > 10) {
696                 ferror.set(e, 'Only 10 ports/range sets are allowed.', quiet);
697                 return 0;
698         }
700         q = [];
701         for (i = 0; i < a.length; ++i) {
702                 v = _v_portrange(e, quiet, a[i]);
703                 if (v == null) return 0;
704                 q.push(v);
705         }
707         e.value = q.join(',');
708         ferror.clear(e);
709         return 1;
712 function _v_netmask(mask)
714         var v = aton(mask) ^ 0xFFFFFFFF;
715         return (((v + 1) & v) == 0);
718 function v_netmask(e, quiet)
720         var n, b;
722         if ((e = E(e)) == null) return 0;
723         n = fixIP(e.value);
724         if (n) {
725                 if (_v_netmask(n)) {
726                         e.value = n;
727                         ferror.clear(e);
728                         return 1;
729                 }
730         }
731         else if (e.value.match(/^\s*\/\s*(\d+)\s*$/)) {
732                 b = RegExp.$1 * 1;
733                 if ((b >= 1) && (b <= 32)) {
734                         if (b == 32) n = 0xFFFFFFFF;    // js quirk
735                                 else n = (0xFFFFFFFF >>> b) ^ 0xFFFFFFFF;
736                         e.value = (n >>> 24) + '.' + ((n >>> 16) & 0xFF) + '.' + ((n >>> 8) & 0xFF) + '.' + (n & 0xFF);
737                         ferror.clear(e);
738                         return 1;
739                 }
740         }
741         ferror.set(e, 'Invalid netmask', quiet);
742         return 0;
745 function fixMAC(mac)
747         var t, i;
749         mac = mac.replace(/\s+/g, '').toUpperCase();
750         if (mac.length == 0) {
751                 mac = [0,0,0,0,0,0];
752         }
753         else if (mac.length == 12) {
754                 mac = mac.match(/../g);
755         }
756         else {
757                 mac = mac.split(/[:\-]/);
758                 if (mac.length != 6) return null;
759         }
760         for (i = 0; i < 6; ++i) {
761                 t = '' + mac[i];
762                 if (t.search(/^[0-9A-F]+$/) == -1) return null;
763                 if ((t = parseInt(t, 16)) > 255) return null;
764                 mac[i] = t.hex(2);
765         }
766         return mac.join(':');
769 function v_mac(e, quiet)
771         var mac;
773         if ((e = E(e)) == null) return 0;
774         mac = fixMAC(e.value);
775         if ((!mac) || (isMAC0(mac))) {
776                 ferror.set(e, 'Invalid MAC address', quiet);
777                 return 0;
778         }
779         e.value = mac;
780         ferror.clear(e);
781         return 1;
784 function v_macz(e, quiet)
786         var mac;
788         if ((e = E(e)) == null) return 0;
789         mac = fixMAC(e.value);
790         if (!mac) {
791                 ferror.set(e, 'Invalid MAC address', quiet);
792                 return false;
793         }
794         e.value = mac;
795         ferror.clear(e);
796         return true;
799 function v_length(e, quiet, min, max)
801         var s, n;
803         if ((e = E(e)) == null) return 0;
804         s = e.value.trim();
805         n = s.length;
806         if (min == undefined) min = 1;
807         if (n < min) {
808                 ferror.set(e, 'Invalid length. Please enter at least ' + min + ' character' + (min == 1 ? '.' : 's.'), quiet);
809                 return 0;
810         }
811         max = max || e.maxlength;
812     if (n > max) {
813                 ferror.set(e, 'Invalid length. Please reduce the length to ' + max + ' characters or less.', quiet);
814                 return 0;
815         }
816         e.value = s;
817         ferror.clear(e);
818         return 1;
821 function v_domain(e, quiet)
823         var s;
825         if ((e = E(e)) == null) return 0;
826         s = e.value.trim().replace(/\s+/g, ' ');
827         if ((s.length > 0) && (s.search(/^[.a-zA-Z0-9_\- ]+$/) == -1)) {
828                 ferror.set(e, "Invalid name. Only characters \"A-Z 0-9 . - _\" are allowed.", quiet);
829                 return 0;
830         }
831         e.value = s;
832         ferror.clear(e);
833         return 1;
836 function v_iptaddr(e, quiet, multi)
838         if ((e = E(e)) == null) return 0;
840         if (!v_iptip(e, 1, multi)) {
841                 var s = e._error_msg;
842                 if (!v_domain(e, 1)) {
843                         ferror.set(e, (s) ? s + ', or invalid domain name' : e._error_msg, quiet);
844                         return 0;
845                 }
846         }
847         ferror.clear(e);
848         return 1;
851 function v_nodelim(e, quiet, name, checklist)
853         if ((e = E(e)) == null) return 0;
855         e.value = e.value.trim();
856         if (e.value.indexOf('<') != -1 ||
857            (checklist && e.value.indexOf('>') != -1)) {
858                 ferror.set(e, 'Invalid ' + name + ': \"<\" ' + (checklist ? 'or \">\" are' : 'is') + ' not allowed.', quiet);
859                 return 0;
860         }
861         ferror.clear(e);
862         return 1;
865 function v_path(e, quiet, required)
867         if ((e = E(e)) == null) return 0;
868         if (required && !v_length(e, quiet, 1)) return 0;
870         if (!required && e.value.trim().length == 0) {
871                 ferror.clear(e);
872                 return 1;
873         }
874         if (e.value.substr(0, 1) != '/') {
875                 ferror.set(e, 'Please start at the / root directory.', quiet);
876                 return 0;
877         }
878         ferror.clear(e);
879         return 1;
882 function isMAC0(mac)
884         return (mac == '00:00:00:00:00:00');
887 // -----------------------------------------------------------------------------
889 function cmpIP(a, b)
891         if ((a = fixIP(a)) == null) a = '255.255.255.255';
892         if ((b = fixIP(b)) == null) b = '255.255.255.255';
893         return aton(a) - aton(b);
896 function cmpText(a, b)
898         if (a == '') a = '\xff';
899         if (b == '') b = '\xff';
900         return (a < b) ? -1 : ((a > b) ? 1 : 0);
903 function cmpInt(a, b)
905         a = parseInt(a, 10);
906         b = parseInt(b, 10);
907         return ((isNaN(a)) ? -0x7FFFFFFF : a) - ((isNaN(b)) ? -0x7FFFFFFF : b);
910 function cmpDate(a, b)
912         return b.getTime() - a.getTime();
915 // -----------------------------------------------------------------------------
917 // ---- todo: cleanup this mess
919 function TGO(e)
921         return elem.parentElem(e, 'TABLE').gridObj;
924 function tgHideIcons()
926         var e;
927         while ((e = document.getElementById('tg-row-panel')) != null) e.parentNode.removeChild(e);
930 // ---- options = sort, move, delete
931 function TomatoGrid(tb, options, maxAdd, editorFields)
933         this.init(tb, options, maxAdd, editorFields);
934         return this;
937 TomatoGrid.prototype = {
938         init: function(tb, options, maxAdd, editorFields) {
939                 if (tb) {
940                         this.tb = E(tb);
941                         this.tb.gridObj = this;
942                 }
943                 else {
944                         this.tb = null;
945                 }
946                 if (!options) options = '';
947                 this.header = null;
948                 this.footer = null;
949                 this.editor = null;
950                 this.canSort = options.indexOf('sort') != -1;
951                 this.canMove = options.indexOf('move') != -1;
952                 this.maxAdd = maxAdd || 140;
953                 this.canEdit = (editorFields != null);
954                 this.canDelete = this.canEdit || (options.indexOf('delete') != -1);
955                 this.editorFields = editorFields;
956                 this.sortColumn = -1;
957                 this.sortAscending = true;
958         },
960         _insert: function(at, cells, escCells) {
961                 var tr, td, c;
962                 var i, t;
964                 tr = this.tb.insertRow(at);
965                 for (i = 0; i < cells.length; ++i) {
966                         c = cells[i];
967                         if (typeof(c) == 'string') {
968                                 td = tr.insertCell(i);
969                                 td.className = 'co' + (i + 1);
970                                 if (escCells) td.appendChild(document.createTextNode(c));
971                                         else td.innerHTML = c;
972                         }
973                         else {
974                                 tr.appendChild(c);
975                         }
976                 }
977                 return tr;
978         },
980         // ---- header
982         headerClick: function(cell) {
983                 if (this.canSort) {
984                         this.sort(cell.cellN);
985                 }
986         },
988         headerSet: function(cells, escCells) {
989                 var e, i;
991                 elem.remove(this.header);
992                 this.header = e = this._insert(0, cells, escCells);
993                 e.className = 'header';
995                 for (i = 0; i < e.cells.length; ++i) {
996                         e.cells[i].cellN = i;   // cellIndex broken in Safari
997                         e.cells[i].onclick = function() { return TGO(this).headerClick(this); };
998                 }
999                 return e;
1000         },
1002         // ---- footer
1004         footerClick: function(cell) {
1005         },
1007         footerSet: function(cells, escCells) {
1008                 var e, i;
1010                 elem.remove(this.footer);
1011                 this.footer = e = this._insert(-1, cells, escCells);
1012                 e.className = 'footer';
1013                 for (i = 0; i < e.cells.length; ++i) {
1014                         e.cells[i].cellN = i;
1015                         e.cells[i].onclick = function() { TGO(this).footerClick(this) };
1016                 }
1017                 return e;
1018         },
1020         // ----
1022         rpUp: function(e) {
1023                 var i;
1025                 e = PR(e);
1026                 TGO(e).moving = null;
1027                 i = e.previousSibling;
1028                 if (i == this.header) return;
1029                 e.parentNode.removeChild(e);
1030                 i.parentNode.insertBefore(e, i);
1032                 this.recolor();
1033                 this.rpHide();
1034         },
1036         rpDn: function(e) {
1037                 var i;
1039                 e = PR(e);
1040                 TGO(e).moving = null;
1041                 i = e.nextSibling;
1042                 if (i == this.footer) return;
1043                 e.parentNode.removeChild(e);
1044                 i.parentNode.insertBefore(e, i.nextSibling);
1046                 this.recolor();
1047                 this.rpHide();
1048         },
1050         rpMo: function(img, e) {
1051                 var me;
1053                 e = PR(e);
1054                 me = TGO(e);
1055                 if (me.moving == e) {
1056                         me.moving = null;
1057                         this.rpHide();
1058                         return;
1059                 }
1060                 me.moving = e;
1061                 img.style.border = "1px dotted red";
1062         },
1064         rpDel: function(e) {
1065                 e = PR(e);
1066                 TGO(e).moving = null;
1067                 e.parentNode.removeChild(e);
1068                 this.recolor();
1069                 this.rpHide();
1070         },
1072         rpMouIn: function(evt) {
1073                 var e, x, ofs, me, s, n;
1075                 if ((evt = checkEvent(evt)) == null) return;
1077                 me = TGO(evt.target);
1078                 if (me.isEditing()) return;
1079                 if (me.moving) return;
1081                 me.rpHide();
1082                 e = document.createElement('div');
1083                 e.tgo = me;
1084                 e.ref = evt.target;
1085                 e.setAttribute('id', 'tg-row-panel');
1087                 n = 0;
1088                 s = '';
1089                 if (me.canMove) {
1090                         s = '<img src="rpu.gif" onclick="this.parentNode.tgo.rpUp(this.parentNode.ref)" title="Move Up"><img src="rpd.gif" onclick="this.parentNode.tgo.rpDn(this.parentNode.ref)" title="Move Down"><img src="rpm.gif" onclick="this.parentNode.tgo.rpMo(this,this.parentNode.ref)" title="Move">';
1091                         n += 3;
1092                 }
1093                 if (me.canDelete) {
1094                         s += '<img src="rpx.gif" onclick="this.parentNode.tgo.rpDel(this.parentNode.ref)" title="Delete">';
1095                         ++n;
1096                 }
1097                 x = PR(evt.target);
1098                 x = x.cells[x.cells.length - 1];
1099                 ofs = elem.getOffset(x);
1100                 n *= 18;
1101                 e.style.left = (ofs.x + x.offsetWidth - n) + 'px';
1102                 e.style.top = ofs.y + 'px';
1103                 e.style.width = n + 'px';
1104                 e.innerHTML = s;
1106                 document.body.appendChild(e);
1107         },
1109         rpHide: tgHideIcons,
1111         // ----
1113         onClick: function(cell) {
1114                 if (this.canEdit) {
1115                         if (this.moving) {
1116                                 var p = this.moving.parentNode;
1117                                 var q = PR(cell);
1118                                 if (this.moving != q) {
1119                                         var v = this.moving.rowIndex > q.rowIndex;
1120                                         p.removeChild(this.moving);
1121                                         if (v) p.insertBefore(this.moving, q);
1122                                                 else p.insertBefore(this.moving, q.nextSibling);
1123                                         this.recolor();
1124                                 }
1125                                 this.moving = null;
1126                                 this.rpHide();
1127                                 return;
1128                         }
1129                         this.edit(cell);
1130                 }
1131         },
1133         insert: function(at, data, cells, escCells) {
1134                 var e, i;
1136                 if ((this.footer) && (at == -1)) at = this.footer.rowIndex;
1137                 e = this._insert(at, cells, escCells);
1138                 e.className = (e.rowIndex & 1) ? 'even' : 'odd';
1140                 for (i = 0; i < e.cells.length; ++i) {
1141                         e.cells[i].onclick = function() { return TGO(this).onClick(this); };
1142                 }
1144                 e._data = data;
1145                 e.getRowData = function() { return this._data; }
1146                 e.setRowData = function(data) { this._data = data; }
1148                 if ((this.canMove) || (this.canEdit) || (this.canDelete)) {
1149                         e.onmouseover = this.rpMouIn;
1150 // ----                 e.onmouseout = this.rpMouOut;
1151                         if (this.canEdit) e.title = 'Click to edit';
1152                 }
1154                 return e;
1155         },
1157         // ----
1159         insertData: function(at, data) {
1160                 return this.insert(at, data, this.dataToView(data), false);
1161         },
1163         dataToView: function(data) {
1164                 var v = [];
1165                 for (var i = 0; i < data.length; ++i) {
1166                         var s = escapeHTML('' + data[i]);
1167                         if (this.editorFields && this.editorFields.length > i) {
1168                                 var ef = this.editorFields[i].multi;
1169                                 if (!ef) ef = [this.editorFields[i]];
1170                                 var f = (ef && ef.length > 0 ? ef[0] : null);
1171                                 if (f && f.type == 'password') {
1172                                         if (!f.peekaboo || get_config('web_pb', '1') != '0')
1173                                                 s = s.replace(/./g, '&#x25CF;');
1174                                 }
1175                         }
1176                         v.push(s);
1177                 }
1178                 return v;
1179         },
1181         dataToFieldValues: function(data) {
1182                 return data;
1183         },
1185         fieldValuesToData: function(row) {
1186                 var e, i, data;
1188                 data = [];
1189                 e = fields.getAll(row);
1190                 for (i = 0; i < e.length; ++i) data.push(e[i].value);
1191                 return data;
1192         },
1194         // ----
1196         edit: function(cell) {
1197                 var sr, er, e, c;
1199                 if (this.isEditing()) return;
1201                 sr = PR(cell);
1202                 sr.style.display = 'none';
1203                 elem.removeClass(sr, 'hover');
1204                 this.source = sr;
1206                 er = this.createEditor('edit', sr.rowIndex, sr);
1207                 er.className = 'editor';
1208                 this.editor = er;
1210                 c = er.cells[cell.cellIndex || 0];
1211                 e = c.getElementsByTagName('input');
1212                 if ((e) && (e.length > 0)) {
1213                         try {   // IE quirk
1214                                 e[0].focus();
1215                         }
1216                         catch (ex) {
1217                         }
1218                 }
1220                 this.controls = this.createControls('edit', sr.rowIndex);
1222                 this.disableNewEditor(true);
1223                 this.rpHide();
1224                 this.verifyFields(this.editor, true);
1225         },
1227         createEditor: function(which, rowIndex, source) {
1228                 var values;
1230                 if (which == 'edit') values = this.dataToFieldValues(source.getRowData());
1232                 var row = this.tb.insertRow(rowIndex);
1233                 row.className = 'editor';
1235                 var common = ' onkeypress="return TGO(this).onKey(\'' + which + '\', event)" onchange="TGO(this).onChange(\'' + which + '\', this)"';
1237                 var vi = 0;
1238                 for (var i = 0; i < this.editorFields.length; ++i) {
1239                         var s = '';
1240                         var ef = this.editorFields[i].multi;
1241                         if (!ef) ef = [this.editorFields[i]];
1243                         for (var j = 0; j < ef.length; ++j) {
1244                                 var f = ef[j];
1246                                 if (f.prefix) s += f.prefix;
1247                                 var attrib = ' class="fi' + (vi + 1) + '" ' + (f.attrib || '');
1248                                 var id = (this.tb ? ('_' + this.tb + '_' + (vi + 1)) : null);
1249                                 if (id) attrib += ' id="' + id + '"';
1250                                 switch (f.type) {
1251                                 case 'password':
1252                                         if (f.peekaboo) {
1253                                                 switch (get_config('web_pb', '1')) {
1254                                                 case '0':
1255                                                         f.type = 'text';
1256                                                 case '2':
1257                                                         f.peekaboo = 0;
1258                                                         break;
1259                                                 }
1260                                         }
1261                                         attrib += ' autocomplete="off"';
1262                                         if (f.peekaboo && id) attrib += ' onfocus=\'peekaboo("' + id + '",1)\'';
1263                                         // drop
1264                                 case 'text':
1265                                         s += '<input type="' + f.type + '" maxlength=' + f.maxlen + common + attrib;
1266                                         if (which == 'edit') s += ' value="' + escapeHTML('' + values[vi]) + '">';
1267                                                 else s += '>';
1268                                         break;
1269                                 case 'select':
1270                                         s += '<select' + common + attrib + '>';
1271                                         for (var k = 0; k < f.options.length; ++k) {
1272                                                 a = f.options[k];
1273                                                 if (which == 'edit') {
1274                                                         s += '<option value="' + a[0] + '"' + ((a[0] == values[vi]) ? ' selected>' : '>') + a[1] + '</option>';
1275                                                 }
1276                                                 else {
1277                                                         s += '<option value="' + a[0] + '">' + a[1] + '</option>';
1278                                                 }
1279                                         }
1280                                         s += '</select>';
1281                                         break;
1282                                 case 'checkbox':
1283                                         s += '<input type="checkbox"' + common + attrib;
1284                                         if ((which == 'edit') && (values[vi])) s += ' checked';
1285                                         s += '>';
1286                                         break;
1287                                 default:
1288                                         s += f.custom.replace(/\$which\$/g, which);
1289                                 }
1290                                 if (f.suffix) s += f.suffix;
1292                                 ++vi;
1293                         }
1294                         var c = row.insertCell(i);
1295                         c.innerHTML = s;
1296                         if (this.editorFields[i].vtop) c.vAlign = 'top';
1297                 }
1299                 return row;
1300         },
1302         createControls: function(which, rowIndex) {
1303                 var r, c;
1305                 r = this.tb.insertRow(rowIndex);
1306                 r.className = 'controls';
1308                 c = r.insertCell(0);
1309                 c.colSpan = this.header.cells.length;
1310                 if (which == 'edit') {
1311                         c.innerHTML =
1312                                 '<input type=button value="Delete" onclick="TGO(this).onDelete()"> &nbsp; ' +
1313                                 '<input type=button value="OK" onclick="TGO(this).onOK()"> ' +
1314                                 '<input type=button value="Cancel" onclick="TGO(this).onCancel()">';
1315                 }
1316                 else {
1317                         c.innerHTML =
1318                                 '<input type=button value="Add" onclick="TGO(this).onAdd()">';
1319                 }
1320                 return r;
1321         },
1323         removeEditor: function() {
1324                 if (this.editor) {
1326                         elem.remove(this.editor);
1327                         this.editor = null;
1328                 }
1329                 if (this.controls) {
1330                         elem.remove(this.controls);
1331                         this.controls = null;
1332                 }
1333         },
1335         showSource: function() {
1336                 if (this.source) {
1337                         this.source.style.display = '';
1338                         this.source = null;
1339                 }
1340         },
1342         onChange: function(which, cell) {
1343                 return this.verifyFields((which == 'new') ? this.newEditor : this.editor, true);
1344         },
1346         onKey: function(which, ev) {
1347                 switch (ev.keyCode) {
1348                 case 27:
1349                         if (which == 'edit') this.onCancel();
1350                         return false;
1351                 case 13:
1352                         if (((ev.srcElement) && (ev.srcElement.tagName == 'SELECT')) ||
1353                                 ((ev.target) && (ev.target.tagName == 'SELECT'))) return true;
1354                         if (which == 'edit') this.onOK();
1355                                 else this.onAdd();
1356                         return false;
1357                 }
1358                 return true;
1359         },
1361         onDelete: function() {
1362                 this.removeEditor();
1363                 elem.remove(this.source);
1364                 this.source = null;
1365                 this.disableNewEditor(false);
1366         },
1368         onCancel: function() {
1369                 this.removeEditor();
1370                 this.showSource();
1371                 this.disableNewEditor(false);
1372         },
1374         onOK: function() {
1375                 var i, data, view;
1377                 if (!this.verifyFields(this.editor, false)) return;
1379                 data = this.fieldValuesToData(this.editor);
1380                 view = this.dataToView(data);
1382                 this.source.setRowData(data);
1383                 for (i = 0; i < this.source.cells.length; ++i) {
1384                         this.source.cells[i].innerHTML = view[i];
1385                 }
1387                 this.removeEditor();
1388                 this.showSource();
1389                 this.disableNewEditor(false);
1390         },
1392         onAdd: function() {
1393                 var data;
1395                 this.moving = null;
1396                 this.rpHide();
1398                 if (!this.verifyFields(this.newEditor, false)) return;
1400                 data = this.fieldValuesToData(this.newEditor);
1401                 this.insertData(-1, data);
1403                 this.disableNewEditor(false);
1404                 this.resetNewEditor();
1405         },
1407         verifyFields: function(row, quiet) {
1408                 return true;
1409         },
1411         showNewEditor: function() {
1412                 var r;
1414                 r = this.createEditor('new', -1, null);
1415                 this.footer = this.newEditor = r;
1417                 r = this.createControls('new', -1);
1418                 this.newControls = r;
1420                 this.disableNewEditor(false);
1421         },
1423         disableNewEditor: function(disable) {
1424                 if (this.getDataCount() >= this.maxAdd) disable = true;
1425                 if (this.newEditor) fields.disableAll(this.newEditor, disable);
1426                 if (this.newControls) fields.disableAll(this.newControls, disable);
1427         },
1429         resetNewEditor: function() {
1430                 var i, e;
1432                 e = fields.getAll(this.newEditor);
1433                 ferror.clearAll(e);
1434                 for (i = 0; i < e.length; ++i) {
1435                         var f = e[i];
1436                         if (f.selectedIndex) f.selectedIndex = 0;
1437                                 else f.value = '';
1438                 }
1439                 try { if (e.length) e[0].focus(); } catch (er) { }
1440         },
1442         getDataCount: function() {
1443                 var n;
1444                 n = this.tb.rows.length;
1445                 if (this.footer) n = this.footer.rowIndex;
1446                 if (this.header) n -= this.header.rowIndex + 1;
1447                 return n;
1448         },
1450         sortCompare: function(a, b) {
1451                 var obj = TGO(a);
1452                 var col = obj.sortColumn;
1453                 var r = cmpText(a.cells[col].innerHTML, b.cells[col].innerHTML);
1454                 return obj.sortAscending ? r : -r;
1455         },
1457         sort: function(column) {
1458                 if (this.editor) return;
1460                 if (this.sortColumn >= 0) {
1461                         elem.removeClass(this.header.cells[this.sortColumn], 'sortasc', 'sortdes');
1462                 }
1463                 if (column == this.sortColumn) {
1464                         this.sortAscending = !this.sortAscending;
1465                 }
1466                 else {
1467                         this.sortAscending = true;
1468                         this.sortColumn = column;
1469                 }
1470                 elem.addClass(this.header.cells[column], this.sortAscending ? 'sortasc' : 'sortdes');
1472                 this.resort();
1473         },
1475         resort: function() {
1476                 if ((this.sortColumn < 0) || (this.getDataCount() == 0) || (this.editor)) return;
1478                 var p = this.header.parentNode;
1479                 var a = [];
1480                 var i, j, max, e, p;
1481                 var top;
1483                 this.moving = null;
1485                 top = this.header ? this.header.rowIndex + 1 : 0;
1486                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1487                 for (i = top; i < max; ++i) a.push(p.rows[i]);
1488                 a.sort(THIS(this, this.sortCompare));
1489                 this.removeAllData();
1490                 j = top;
1491                 for (i = 0; i < a.length; ++i) {
1492                         e = p.insertBefore(a[i], this.footer);
1493                         e.className = (j & 1) ? 'even' : 'odd';
1494                         ++j;
1495                 }
1496         },
1498         recolor: function() {
1499                  var i, e, o;
1501                  i = this.header ? this.header.rowIndex + 1 : 0;
1502                  e = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1503                  for (; i < e; ++i) {
1504                          o = this.tb.rows[i];
1505                          o.className = (o.rowIndex & 1) ? 'even' : 'odd';
1506                  }
1507         },
1509         removeAllData: function() {
1510                 var i, count;
1512                 i = this.header ? this.header.rowIndex + 1 : 0;
1513                 count = (this.footer ? this.footer.rowIndex : this.tb.rows.length) - i;
1514                 while (count-- > 0) elem.remove(this.tb.rows[i]);
1515         },
1517         getAllData: function() {
1518                 var i, max, data, r;
1520                 data = [];
1521                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1522                 for (i = this.header ? this.header.rowIndex + 1 : 0; i < max; ++i) {
1523                         r = this.tb.rows[i];
1524                         if ((r.style.display != 'none') && (r._data)) data.push(r._data);
1525                 }
1526                 return data;
1527         },
1529         isEditing: function() {
1530                 return (this.editor != null);
1531         }
1535 // -----------------------------------------------------------------------------
1538 function xmlHttpObj()
1540         var ob;
1541         try {
1542                 ob = new XMLHttpRequest();
1543                 if (ob) return ob;
1544         }
1545         catch (ex) { }
1546         try {
1547                 ob = new ActiveXObject('Microsoft.XMLHTTP');
1548                 if (ob) return ob;
1549         }
1550         catch (ex) { }
1551         return null;
1554 var _useAjax = -1;
1555 var _holdAjax = null;
1557 function useAjax()
1559         if (_useAjax == -1) _useAjax = ((_holdAjax = xmlHttpObj()) != null);
1560         return _useAjax;
1563 function XmlHttp()
1565         if ((!useAjax()) || ((this.xob = xmlHttpObj()) == null)) return null;
1566         return this;
1569 XmlHttp.prototype = {
1570         addId: function(vars) {
1571                 if (vars) vars += '&';
1572                         else vars = '';
1573                 vars += '_http_id=' + escapeCGI(nvram.http_id);
1574                 return vars;
1575         },
1577     get: function(url, vars) {
1578                 try {
1579                         vars = this.addId(vars);
1580                         url += '?' + vars;
1582                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1583                         this.xob.open('GET', url, true);
1584                         this.xob.send(null);
1585                 }
1586                 catch (ex) {
1587                         this.onError(ex);
1588                 }
1589         },
1591         post: function(url, vars) {
1592                 try {
1593                         vars = this.addId(vars);
1595                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1596                         this.xob.open('POST', url, true);
1597                         this.xob.send(vars);
1598                 }
1599                 catch (ex) {
1600                         this.onError(ex);
1601                 }
1602         },
1604         abort: function() {
1605                 try {
1606                         this.xob.onreadystatechange = function () { }
1607                         this.xob.abort();
1608                 }
1609                 catch (ex) {
1610                 }
1611         },
1613         onReadyStateChange: function() {
1614                 try {
1615                         if (typeof(E) == 'undefined') return;   // oddly late? testing for bug...
1617                         if (this.xob.readyState == 4) {
1618                                 if (this.xob.status == 200) {
1619                                         this.onCompleted(this.xob.responseText, this.xob.responseXML);
1620                                 }
1621                                 else {
1622                                         this.onError('' + (this.xob.status || 'unknown'));
1623                                 }
1624                         }
1625                 }
1626                 catch (ex) {
1627                         this.onError(ex);
1628                 }
1629         },
1631         onCompleted: function(text, xml) { },
1632         onError: function(ex) { }
1636 // -----------------------------------------------------------------------------
1639 function TomatoTimer(func, ms)
1641         this.tid = null;
1642         this.onTimer = func;
1643         if (ms) this.start(ms);
1644         return this;
1647 TomatoTimer.prototype = {
1648         start: function(ms) {
1649                 this.stop();
1650                 this.tid = setTimeout(THIS(this, this._onTimer), ms);
1651         },
1652         stop: function() {
1653                 if (this.tid) {
1654                         clearTimeout(this.tid);
1655                         this.tid = null;
1656                 }
1657         },
1659         isRunning: function() {
1660                 return (this.tid != null);
1661         },
1663         _onTimer: function() {
1664                 this.tid = null;
1665                 this.onTimer();
1666         },
1668         onTimer: function() {
1669         }
1673 // -----------------------------------------------------------------------------
1676 function TomatoRefresh(actionURL, postData, refreshTime, cookieTag)
1678         this.setup(actionURL, postData, refreshTime, cookieTag);
1679         this.timer = new TomatoTimer(THIS(this, this.start));
1682 TomatoRefresh.prototype = {
1683         running: 0,
1685         setup: function(actionURL, postData, refreshTime, cookieTag) {
1686                 var e, v;
1688                 this.actionURL = actionURL;
1689                 this.postData = postData;
1690                 this.refreshTime = refreshTime * 1000;
1691                 this.cookieTag = cookieTag;
1692         },
1694         start: function() {
1695                 var e;
1697                 if ((e = E('refresh-time')) != null) {
1698                         if (this.cookieTag) cookie.set(this.cookieTag, e.value);
1699                         this.refreshTime = e.value * 1000;
1700                 }
1701                 e = undefined;
1703                 this.updateUI('start');
1705                 this.running = 1;
1706                 if ((this.http = new XmlHttp()) == null) {
1707                         reloadPage();
1708                         return;
1709                 }
1711                 this.http.parent = this;
1713                 this.http.onCompleted = function(text, xml) {
1714                         var p = this.parent;
1716                         if (p.cookieTag) cookie.unset(p.cookieTag + '-error');
1717                         if (!p.running) {
1718                                 p.stop();
1719                                 return;
1720                         }
1722                         p.refresh(text);
1724                         if ((p.refreshTime > 0) && (!p.once)) {
1725                                 p.updateUI('wait');
1726                                 p.timer.start(Math.round(p.refreshTime));
1727                         }
1728                         else {
1729                                 p.stop();
1730                         }
1732                         p.errors = 0;
1733                 }
1735                 this.http.onError = function(ex) {
1736                         var p = this.parent;
1737                         if ((!p) || (!p.running)) return;
1739                         p.timer.stop();
1741                         if (++p.errors <= 3) {
1742                                 p.updateUI('wait');
1743                                 p.timer.start(3000);
1744                                 return;
1745                         }
1747                         if (p.cookieTag) {
1748                                 var e = cookie.get(p.cookieTag + '-error') * 1;
1749                                 if (isNaN(e)) e = 0;
1750                                         else ++e;
1751                                 cookie.unset(p.cookieTag);
1752                                 cookie.set(p.cookieTag + '-error', e, 1);
1753                                 if (e >= 3) {
1754                                         alert('XMLHTTP: ' + ex);
1755                                         return;
1756                                 }
1757                         }
1759                         setTimeout(reloadPage, 2000);
1760                 }
1762                 this.errors = 0;
1763                 this.http.post(this.actionURL, this.postData);
1764         },
1766         stop: function() {
1767                 if (this.cookieTag) cookie.set(this.cookieTag, -(this.refreshTime / 1000));
1768                 this.running = 0;
1769                 this.updateUI('stop');
1770                 this.timer.stop();
1771                 this.http = null;
1772                 this.once = undefined;
1773         },
1775         toggle: function(delay) {
1776                 if (this.running) this.stop();
1777                         else this.start(delay);
1778         },
1780         updateUI: function(mode) {
1781                 var e, b;
1783                 if (typeof(E) == 'undefined') return;   // for a bizzare bug...
1785                 b = (mode != 'stop') && (this.refreshTime > 0);
1786                 if ((e = E('refresh-button')) != null) {
1787                         e.value = b ? 'Stop' : 'Refresh';
1788                         e.disabled = ((mode == 'start') && (!b));
1789                 }
1790                 if ((e = E('refresh-time')) != null) e.disabled = b;
1791                 if ((e = E('refresh-spinner')) != null) e.style.visibility = b ? 'visible' : 'hidden';
1792         },
1794         initPage: function(delay, def) {
1795                 var e, v;
1797                 e = E('refresh-time');
1798                 if (((this.cookieTag) && (e != null)) &&
1799                         ((v = cookie.get(this.cookieTag)) != null) && (!isNaN(v *= 1))) {
1800                         e.value = Math.abs(v);
1801                         if (v > 0) v = (v * 1000) + (delay || 0);
1802                 }
1803                 else if (def) {
1804                         v = def;
1805                         if (e) e.value = def;
1806                 }
1807                 else v = 0;
1809                 if (delay < 0) {
1810                         v = -delay;
1811                         this.once = 1;
1812                 }
1814                 if (v > 0) {
1815                         this.running = 1;
1816                         this.refreshTime = v;
1817                         this.timer.start(v);
1818                         this.updateUI('wait');
1819                 }
1820         }
1823 function genStdTimeList(id, zero, min)
1825         var b = [];
1826         var t = [3,4,5,10,15,30,60,120,180,240,300,10*60,15*60,20*60,30*60];
1827         var i, v;
1829         if (min >= 0) {
1830                 b.push('<select id="' + id + '"><option value=0>' + zero);
1831                 for (i = 0; i < t.length; ++i) {
1832                         v = t[i];
1833                         if (v < min) continue;
1834                         b.push('<option value=' + v + '>');
1835                         if (v == 60) b.push('1 minute');
1836                                 else if (v > 60) b.push((v / 60) + ' minutes');
1837                                 else b.push(v + ' seconds');
1838                 }
1839                 b.push('</select> ');
1840         }
1841         document.write(b.join(''));
1844 function genStdRefresh(spin, min, exec)
1846         W('<div style="text-align:right">');
1847         if (spin) W('<img src="spin.gif" id="refresh-spinner"> ');
1848         genStdTimeList('refresh-time', 'Auto Refresh', min);
1849         W('<input type="button" value="Refresh" onclick="' + (exec ? exec : 'refreshClick()') + '" id="refresh-button"></div>');
1853 // -----------------------------------------------------------------------------
1856 function _tabCreate(tabs)
1858         var buf = [];
1859         buf.push('<ul id="tabs">');
1860         for (var i = 0; i < arguments.length; ++i)
1861                 buf.push('<li><a href="javascript:tabSelect(\'' + arguments[i][0] + '\')" id="' + arguments[i][0] + '">' + arguments[i][1] + '</a>');
1862         buf.push('</ul><div id="tabs-bottom"></div>');
1863         return buf.join('');
1866 function tabCreate(tabs)
1868         document.write(_tabCreate.apply(this, arguments));
1871 function tabHigh(id)
1873         var a = E('tabs').getElementsByTagName('A');
1874         for (var i = 0; i < a.length; ++i) {
1875                 if (id != a[i].id) elem.removeClass(a[i], 'active');
1876         }
1877         elem.addClass(id, 'active');
1880 // -----------------------------------------------------------------------------
1882 var cookie = {
1883         set: function(key, value, days) {
1884                 document.cookie = 'tomato_' + key + '=' + value + '; expires=' +
1885                         (new Date(new Date().getTime() + ((days ? days : 14) * 86400000))).toUTCString() + '; path=/';
1886         },
1888         get: function(key) {
1889                 var r = ('; ' + document.cookie + ';').match('; tomato_' + key + '=(.*?);');
1890                 return r ? r[1] : null;
1891         },
1893         unset: function(key) {
1894                 document.cookie = 'tomato_' + key + '=; expires=' +
1895                         (new Date(1)).toUTCString() + '; path=/';
1896         }
1899 // -----------------------------------------------------------------------------
1901 function checkEvent(evt)
1903         if (typeof(evt) == 'undefined') {
1904                 // ---- IE
1905                 evt = event;
1906                 evt.target = evt.srcElement;
1907                 evt.relatedTarget = evt.toElement;
1908         }
1909         return evt;
1912 function W(s)
1914         document.write(s);
1917 function E(e)
1919         return (typeof(e) == 'string') ? document.getElementById(e) : e;
1922 function PR(e)
1924         return elem.parentElem(e, 'TR');
1927 function THIS(obj, func)
1929         return function() { return func.apply(obj, arguments); }
1932 function UT(v)
1934         return (typeof(v) == 'undefined') ? '' : '' + v;
1937 function escapeHTML(s)
1939         function esc(c) {
1940                 return '&#' + c.charCodeAt(0) + ';';
1941         }
1942         return s.replace(/[&"'<>\r\n]/g, esc);
1945 function escapeCGI(s)
1947         return escape(s).replace(/\+/g, '%2B'); // escape() doesn't handle +
1950 function escapeD(s)
1952         function esc(c) {
1953                 return '%' + c.charCodeAt(0).hex(2);
1954         }
1955         return s.replace(/[<>|%]/g, esc);
1958 function ellipsis(s, max) {
1959         return (s.length <= max) ? s : s.substr(0, max - 3) + '...';
1962 function MIN(a, b)
1964         return a < b ? a : b;
1967 function MAX(a, b)
1969         return a > b ? a : b;
1972 function fixInt(n, min, max, def)
1974         if (n === null) return def;
1975         n *= 1;
1976         if (isNaN(n)) return def;
1977         if (n < min) return min;
1978         if (n > max) return max;
1979         return n;
1982 function comma(n)
1984         n = '' + n;
1985         var p = n;
1986         while ((n = n.replace(/(\d+)(\d{3})/g, '$1,$2')) != p) p = n;
1987         return n;
1990 function doScaleSize(n, sm)
1992         if (isNaN(n *= 1)) return '-';
1993         if (n <= 9999) return '' + n;
1994         var s = -1;
1995         do {
1996                 n /= 1024;
1997                 ++s;
1998         } while ((n > 9999) && (s < 2));
1999         return comma(n.toFixed(2)) + (sm ? '<small> ' : ' ') + (['KB', 'MB', 'GB'])[s] + (sm ? '</small>' : '');
2002 function scaleSize(n)
2004         return doScaleSize(n, 1);
2007 function timeString(mins)
2009         var h = Math.floor(mins / 60);
2010         if ((new Date(2000, 0, 1, 23, 0, 0, 0)).toLocaleString().indexOf('23') != -1)
2011                 return h + ':' + (mins % 60).pad(2);
2012         return ((h == 0) ? 12 : ((h > 12) ? h - 12 : h)) + ':' + (mins % 60).pad(2) + ((h >= 12) ? ' PM' : ' AM');
2015 function features(s)
2017         var features = ['ses','brau','aoss','wham','hpamp','!nve','11n','1000et'];
2018         var i;
2020         for (i = features.length - 1; i >= 0; --i) {
2021                 if (features[i] == s) return (parseInt(nvram.t_features) & (1 << i)) != 0;
2022         }
2023         return 0;
2026 function get_config(name, def)
2028         return ((typeof(nvram) != 'undefined') && (typeof(nvram[name]) != 'undefined')) ? nvram[name] : def;
2031 function nothing()
2035 // -----------------------------------------------------------------------------
2037 function show_notice1(s)
2039 // ---- !!TB - USB Support: multi-line notices
2040         if (s.length) document.write('<div id="notice1">' + s.replace(/\n/g, '<br>') + '</div><br style="clear:both">');
2043 // -----------------------------------------------------------------------------
2045 function myName()
2047         var name, i;
2049         name = document.location.pathname;
2050         name = name.replace(/\\/g, '/');        // IE local testing
2051         if ((i = name.lastIndexOf('/')) != -1) name = name.substring(i + 1, name.length);
2052         if (name == '') name = 'status-overview.asp';
2053         return name;
2056 function navi()
2058         var menu = [
2059                 ['Status',                              'status', 0, [
2060                         ['Overview',            'overview.asp'],
2061                         ['Device List',         'devices.asp'],
2062                         ['Web Usage',           'webmon.asp'],
2063                         ['Logs',                        'log.asp'] ] ],
2064                 ['Bandwidth',                   'bwm', 0, [
2065                         ['Real-Time',           'realtime.asp'],
2066                         ['Last 24 Hours',       '24.asp'],
2067                         ['Daily',                       'daily.asp'],
2068                         ['Weekly',                      'weekly.asp'],
2069                         ['Monthly',                     'monthly.asp'] ] ],
2070                 ['Tools',                               'tools', 0, [
2071                         ['Ping',                        'ping.asp'],
2072                         ['Trace',                       'trace.asp'],
2073                         ['System',                      'shell.asp'],
2074                         ['Wireless Survey',     'survey.asp'],
2075                         ['WOL',                         'wol.asp'] ] ],
2076                 null,
2077                 ['Basic',                               'basic', 0, [
2078                         ['Network',                     'network.asp'],
2079                         ['Identification',      'ident.asp'],
2080                         ['Time',                        'time.asp'],
2081                         ['DDNS',                        'ddns.asp'],
2082                         ['Static DHCP',         'static.asp'],
2083                         ['Wireless Filter',     'wfilter.asp'] ] ],
2084                 ['Advanced',                    'advanced', 0, [
2085                         ['Conntrack / Netfilter',       'ctnf.asp'],
2086                         ['DHCP / DNS',          'dhcpdns.asp'],
2087                         ['Firewall',            'firewall.asp'],
2088                         ['MAC Address',         'mac.asp'],
2089                         ['Miscellaneous',       'misc.asp'],
2090                         ['Routing',                     'routing.asp'],
2091                         ['Wireless',            'wireless.asp'] ] ],
2092                 ['Port Forwarding',     'forward', 0, [
2093                         ['Basic',                       'basic.asp'],
2094                         ['DMZ',                         'dmz.asp'],
2095                         ['Triggered',           'triggered.asp'],
2096                         ['UPnP / NAT-PMP',      'upnp.asp'] ] ],
2097                 ['QoS',                                 'qos', 0, [
2098                         ['Basic Settings',      'settings.asp'],
2099                         ['Classification',      'classify.asp'],
2100                         ['View Graphs',         'graphs.asp'],
2101                         ['View Details',        'detailed.asp']
2102                         ] ],
2103                 ['Access Restriction',  'restrict.asp'],
2104 /* REMOVE-BEGIN
2105                 ['Scripts',                             'sc', 0, [
2106                         ['Startup',                     'startup.asp'],
2107                         ['Shutdown',            'shutdown.asp'],
2108                         ['Firewall',            'firewall.asp'],
2109                         ['WAN Up',                      'wanup.asp']
2110                         ] ],
2111 REMOVE-END */
2112 /* USB-BEGIN */
2113 // ---- !!TB - USB, FTP, Samba, Media Server
2114                 ['USB and NAS',                 'nas', 0, [
2115                         ['USB Support',         'usb.asp']
2116 /* FTP-BEGIN */
2117                         ,['FTP Server',         'ftp.asp']
2118 /* FTP-END */
2119 /* SAMBA-BEGIN */
2120                         ,['File Sharing',       'samba.asp']
2121 /* SAMBA-END */
2122 /* MEDIA-SRV-BEGIN */
2123                         ,['Media Server',       'media.asp']
2124 /* MEDIA-SRV-END */
2125                         ] ],
2126 /* USB-END */
2127 /* VPN-BEGIN */
2128                 ['VPN Tunneling',               'vpn', 0, [
2129                         ['Server',                      'server.asp'],
2130                         ['Client',                      'client.asp'] ] ],
2131 /* VPN-END */
2132                 null,
2133                 ['Administration',              'admin', 0, [
2134                         ['Admin Access',        'access.asp'],
2135                         ['Bandwidth Monitoring','bwm.asp'],
2136                         ['Buttons / LED',       'buttons.asp'],
2137 /* CIFS-BEGIN */
2138                         ['CIFS Client',         'cifs.asp'],
2139 /* CIFS-END */
2140                         ['Configuration',       'config.asp'],
2141                         ['Debugging',           'debug.asp'],
2142 /* JFFS2-BEGIN */
2143                         ['JFFS',                        'jffs2.asp'],
2144 /* JFFS2-END */
2145                         ['Logging',                     'log.asp'],
2146                         ['Scheduler',           'sched.asp'],
2147                         ['Scripts',                     'scripts.asp'],
2148                         ['Upgrade',                     'upgrade.asp'] ] ],
2149                 null,
2150                 ['About',                               'about.asp'],
2151                 ['Reboot...',                   'javascript:reboot()'],
2152                 ['Shutdown...',                 'javascript:shutdown()'],
2153                 ['Logout',                              'javascript:logout()']
2154         ];
2155         var name, base;
2156         var i, j;
2157         var buf = [];
2158         var sm;
2159         var a, b, c;
2160         var on1;
2161         var cexp = get_config('web_mx', '').toLowerCase();
2163         name = myName();
2164         if (name == 'restrict-edit.asp') name = 'restrict.asp';
2165         if ((i = name.indexOf('-')) != -1) {
2166                 base = name.substring(0, i);
2167                 name = name.substring(i + 1, name.length);
2168         }
2169         else base = '';
2171         for (i = 0; i < menu.length; ++i) {
2172                 var m = menu[i];
2173                 if (!m) {
2174                         buf.push("<br>");
2175                         continue;
2176                 }
2177                 if (m.length == 2) {
2178                         buf.push('<a href="' + m[1] + '" class="indent1' + (((base == '') && (name == m[1])) ? ' active' : '') + '">' + m[0] + '</a>');
2179                 }
2180                 else {
2181                         if (base == m[1]) {
2182                                 b = name;
2183                         }
2184                         else {
2185                                 a = cookie.get('menu_' + m[1]);
2186                                 b = m[3][0][1];
2187                                 for (j = 0; j < m[3].length; ++j) {
2188                                         if (m[3][j][1] == a) {
2189                                                 b = a;
2190                                                 break;
2191                                         }
2192                                 }
2193                         }
2194                         a = m[1] + '-' + b;
2195                         if (a == 'status-overview.asp') a = '/';
2196                         on1 = (base == m[1]);
2197                         buf.push('<a href="' + a + '" class="indent1' + (on1 ? ' active' : '') + '">' + m[0] + '</a>');
2198                         if ((!on1) && (m[2] == 0) && (cexp.indexOf(m[1]) == -1)) continue;
2200                         for (j = 0; j < m[3].length; ++j) {
2201                                 sm = m[3][j];
2202                                 a = m[1] + '-' + sm[1];
2203                                 if (a == 'status-overview.asp') a = '/';
2204                                 buf.push('<a href="' + a + '" class="indent2' + (((on1) && (name == sm[1])) ? ' active' : '') + '">' + sm[0] + '</a>');
2205                         }
2206                 }
2207         }
2208         document.write(buf.join(''));
2210         if (base.length) {
2211                 if ((base == 'qos') && (name == 'detailed.asp')) name = 'view.asp';
2212                 cookie.set('menu_' + base, name);
2213         }
2216 function createFieldTable(flags, desc)
2218         var common;
2219         var i, n;
2220         var name;
2221         var id;
2222         var fields;
2223         var f;
2224         var a;
2225         var buf = [];
2226         var buf2;
2227         var id1;
2228         var tr;
2230         if ((flags.indexOf('noopen') == -1)) buf.push('<table class="fields">');
2231         for (desci = 0; desci < desc.length; ++desci) {
2232                 var v = desc[desci];
2234                 if (!v) {
2235                         buf.push('<tr><td colspan=2 class="spacer">&nbsp;</td></tr>');
2236                         continue;
2237                 }
2239                 if (v.ignore) continue;
2241                 buf.push('<tr');
2242                 if (v.rid) buf.push(' id="' + v.rid + '"');
2243                 if (v.hidden) buf.push(' style="display:none"');
2244                 buf.push('>');
2246                 if (v.text) {
2247                         if (v.title) {
2248                                 buf.push('<td class="title indent' + (v.indent || 1) + '">' + v.title + '</td><td class="content">' + v.text + '</td></tr>');
2249                         }
2250                         else {
2251                                 buf.push('<td colspan=2>' + v.text + '</td></tr>');
2252                         }
2253                         continue;
2254                 }
2256                 id1 = '';
2257                 buf2 = [];
2258                 buf2.push('<td class="content">');
2260                 if (v.multi) fields = v.multi;
2261                         else fields = [v];
2263                 for (n = 0; n < fields.length; ++n) {
2264                         f = fields[n];
2265                         if (f.prefix) buf2.push(f.prefix);
2267                         if ((f.type == 'radio') && (!f.id)) id = '_' + f.name + '_' + i;
2268                                 else id = (f.id ? f.id : ('_' + f.name));
2270                         if (id1 == '') id1 = id;
2272                         common = ' onchange="verifyFields(this, 1)" id="' + id + '"';
2273                         if (f.attrib) common += ' ' + f.attrib;
2274                         name = f.name ? (' name="' + f.name + '"') : '';
2276                         switch (f.type) {
2277                         case 'checkbox':
2278                                 buf2.push('<input type="checkbox"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2279                                 break;
2280                         case 'radio':
2281                                 buf2.push('<input type="radio"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2282                                 break;
2283                         case 'password':
2284                                 if (f.peekaboo) {
2285                                         switch (get_config('web_pb', '1')) {
2286                                         case '0':
2287                                                 f.type = 'text';
2288                                         case '2':
2289                                                 f.peekaboo = 0;
2290                                                 break;
2291                                         }
2292                                 }
2293                                 if (f.type == 'password') {
2294                                         common += ' autocomplete="off"';
2295                                         if (f.peekaboo) common += ' onfocus=\'peekaboo("' + id + '",1)\'';
2296                                 }
2297                                 // drop
2298                         case 'text':
2299                                 buf2.push('<input type="' + f.type + '"' + name + ' value="' + escapeHTML(UT(f.value)) + '" maxlength=' + f.maxlen + (f.size ? (' size=' + f.size) : '') + common + '>');
2300                                 break;
2301                         case 'select':
2302                                 buf2.push('<select' + name + common + '>');
2303                                 for (i = 0; i < f.options.length; ++i) {
2304                                         a = f.options[i];
2305                                         if (a.length == 1) a.push(a[0]);
2306                                         buf2.push('<option value="' + a[0] + '"' + ((a[0] == f.value) ? ' selected' : '') + '>' + a[1] + '</option>');
2307                                 }
2308                                 buf2.push('</select>');
2309                                 break;
2310                         case 'textarea':
2311                                 buf2.push('<textarea' + name + common + (f.wrap ? (' wrap=' + f.wrap) : '') + '>' + escapeHTML(UT(f.value)) + '</textarea>');
2312                                 break;
2313                         default:
2314                                 if (f.custom) buf2.push(f.custom);
2315                                 break;
2316                         }
2317                         if (f.suffix) buf2.push(f.suffix);
2318                 }
2319                 buf2.push('</td>');
2321                 buf.push('<td class="title indent' + (v.indent ? v.indent : 1) + '">');
2322                 if (id1 != '') buf.push('<label for="' + id + '">' + v.title + '</label></td>');
2323                         else buf.push(+ v.title + '</td>');
2325                 buf.push(buf2.join(''));
2326                 buf.push('</tr>');
2327         }
2328         if ((!flags) || (flags.indexOf('noclose') == -1)) buf.push('</table>');
2329         document.write(buf.join(''));
2332 function peekaboo(id, show)
2334         try {
2335                 var o = document.createElement('INPUT');
2336                 var e = E(id);
2337                 var name = e.name;
2338                 o.type = show ? 'text' : 'password';
2339                 o.value = e.value;
2340                 o.size = e.size;
2341                 o.maxLength = e.maxLength;
2342                 o.autocomplete = e.autocomplete;
2343                 o.title = e.title;
2344                 o.disabled = e.disabled;
2345                 o.onchange = e.onchange;
2346                 e.parentNode.replaceChild(o, e);
2347                 e = null;
2348                 o.id = id;
2349                 o.name = name;
2351                 if (show) {
2352                         o.onblur = function(ev) { setTimeout('peekaboo("' + this.id + '", 0)', 0) };
2353                         setTimeout('try { E("' + id + '").focus() } catch (ex) { }', 0)
2354                 }
2355                 else {
2356                         o.onfocus = function(ev) { peekaboo(this.id, 1); };
2357                 }
2358         }
2359         catch (ex) {
2360 //              alert(ex);
2361         }
2363 /* REMOVE-BEGIN
2364 notes:
2365  - e.type= doesn't work in IE, ok in FF
2366  - may mess keyboard tabing (bad: IE; ok: FF, Opera)... setTimeout() delay seems to help a little.
2367 REMOVE-END */
2370 // -----------------------------------------------------------------------------
2372 function reloadPage()
2374         document.location.reload(1);
2377 function reboot()
2379         if (confirm("Reboot?")) form.submitHidden('tomato.cgi', { _reboot: 1, _commit: 0, _nvset: 0 });
2382 function shutdown()
2384         if (confirm("Shutdown?")) form.submitHidden('shutdown.cgi', { });
2387 function logout()
2389         form.submitHidden('logout.asp', { });
2392 // -----------------------------------------------------------------------------
2396 // ---- debug
2398 function isLocal()
2400         return location.href.search('file://') == 0;
2403 function console(s)