fix missing comma typo in advanced/firewall
[tomato/davidwu.git] / release / src / router / www / tomato.js
blob763d81007b5a0cf5f19418e6ab73f976204ca938
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 fixFile(name)
357         var i;
358         if (((i = name.lastIndexOf('/')) > 0) || ((i = name.lastIndexOf('\\')) > 0))
359                 name = name.substring(i + 1, name.length);
360         return name;
363 function _v_range(e, quiet, min, max, name)
365         if ((e = E(e)) == null) return 0;
366         var v = e.value;
367         if ((!v.match(/^ *[-\+]?\d+ *$/)) || (v < min) || (v > max)) {
368                 ferror.set(e, 'Invalid ' + name + '. Valid range: ' + min + '-' + max, quiet);
369                 return 0;
370         }
371         e.value = v * 1;
372         ferror.clear(e);
373         return 1;
376 function v_range(e, quiet, min, max)
378         return _v_range(e, quiet, min, max, 'number');
381 function v_port(e, quiet)
383         return _v_range(e, quiet, 1, 0xFFFF, 'port');
386 function v_octet(e, quiet)
388         return _v_range(e, quiet, 1, 254, 'address');
391 function v_mins(e, quiet, min, max)
393         var v, m;
395         if ((e = E(e)) == null) return 0;
396         if (e.value.match(/^\s*(.+?)([mhd])?\s*$/)) {
397                 m = 1;
398                 if (RegExp.$2 == 'h') m = 60;
399                         else if (RegExp.$2 == 'd') m = 60 * 24;
400                 v = Math.round(RegExp.$1 * m);
401                 if (!isNaN(v)) {
402                         e.value = v;
403                         return _v_range(e, quiet, min, max, 'minutes');
404                 }
405         }
406         ferror.set(e, 'Invalid number of minutes.', quiet);
407         return 0;
410 function v_macip(e, quiet, bok, lan_ipaddr, lan_netmask)
412         var s, a, b, c, d, i;
413         var ipp, temp;
415         temp = lan_ipaddr.split('.');
416         ipp = temp[0]+'.'+temp[1]+'.'+temp[2]+'.';
418         if ((e = E(e)) == null) return 0;
419         s = e.value.replace(/\s+/g, '');
421         if ((a = fixMAC(s)) != null) {
422                 if (isMAC0(a)) {
423                         if (bok) {
424                                 e.value = '';
425                         }
426                         else {
427                                 ferror.set(e, 'Invalid MAC or IP address');
428                                 return false;
429                         }
430                 }
431                 else e.value = a;
432                 ferror.clear(e);
433                 return true;
434         }
436         a = s.split('-');
437     
438         if (a.length > 2) {
439                 ferror.set(e, 'Invalid IP address range', quiet);
440                 return false;
441         }
442         
443         if (a[0].match(/^\d+$/)){
444                 a[0]=ipp+a[0];
445                 if ((a.length == 2) && (a[1].match(/^\d+$/)))
446                         a[1]=ipp+a[1];
447         }
448         else{
449                 if ((a.length == 2) && (a[1].match(/^\d+$/))){
450                         temp=a[0].split('.');
451                         a[1]=temp[0]+'.'+temp[1]+'.'+temp[2]+'.'+a[1];
452                 }
453         }
454         for (i = 0; i < a.length; ++i) {
455                 b = a[i];    
456                 b = fixIP(b);
457                 if (!b) {
458                         ferror.set(e, 'Invalid IP address', quiet);
459                         return false;
460                 }
462                 if ((aton(b) & aton(lan_netmask))!=(aton(lan_ipaddr) & aton(lan_netmask))) {
463                         ferror.set(e, 'IP address outside of LAN', quiet);
464                         return false;
465                 }
467                 d = (b.split('.'))[3];
468                 if (parseInt(d) <= parseInt(c)) {
469                         ferror.set(e, 'Invalid IP address range', quiet);
470                         return false;
471                 }
473                 a[i] = c = d;
474         }
475         e.value = b.split('.')[0] + '.' + b.split('.')[1] + '.' + b.split('.')[2] + '.' + a.join('-');
476         return true;
479 function fixIP(ip, x)
481         var a, n, i;
482         a = ip;
483         i = a.indexOf("<br>");
484         if (i > 0)
485                 a = a.slice(0,i);
487         a = a.split('.');
488         if (a.length != 4) return null;
489         for (i = 0; i < 4; ++i) {
490                 n = a[i] * 1;
491                 if ((isNaN(n)) || (n < 0) || (n > 255)) return null;
492                 a[i] = n;
493         }
494         if ((x) && ((a[3] == 0) || (a[3] == 255))) return null;
495         return a.join('.');
498 function v_ip(e, quiet, x)
500         var ip;
502         if ((e = E(e)) == null) return 0;
503         ip = fixIP(e.value, x);
504         if (!ip) {
505                 ferror.set(e, 'Invalid IP address', quiet);
506                 return false;
507         }
508         e.value = ip;
509         ferror.clear(e);
510         return true;
513 function v_ipz(e, quiet)
515         if ((e = E(e)) == null) return 0;
516         if (e.value == '') e.value = '0.0.0.0';
517         return v_ip(e, quiet);
520 function v_dns(e, quiet)
522         if ((e = E(e)) == null) return 0;       
523         if (e.value == '') {
524                 e.value = '0.0.0.0';
525         }
526         else {
527                 var s = e.value.split(':');
528                 if (s.length == 1) {
529                         s.push(53);
530                 }
531                 else if (s.length != 2) {
532                         ferror.set(e, 'Invalid IP address or port', quiet);
533                         return false;
534                 }
535                 
536                 if ((s[0] = fixIP(s[0])) == null) {
537                         ferror.set(e, 'Invalid IP address', quiet);
538                         return false;
539                 }
541                 if ((s[1] = fixPort(s[1], -1)) == -1) {
542                         ferror.set(e, 'Invalid port', quiet);
543                         return false;
544                 }
545         
546                 if (s[1] == 53) {
547                         e.value = s[0];
548                 }
549                 else {
550                         e.value = s.join(':');
551                 }
552         }
554         ferror.clear(e);
555         return true;
558 function aton(ip)
560         var o, x, i;
562         // ---- this is goofy because << mangles numbers as signed
563         o = ip.split('.');
564         x = '';
565         for (i = 0; i < 4; ++i) x += (o[i] * 1).hex(2);
566         return parseInt(x, 16);
569 function ntoa(ip)
571         return ((ip >> 24) & 255) + '.' + ((ip >> 16) & 255) + '.' + ((ip >> 8) & 255) + '.' + (ip & 255);
575 // ---- 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
576 function _v_iptip(e, ip, quiet)
578         var ma, x, y, z, oip;
579         var a, b;
581         oip = ip;
583         // x.x.x.x - y.y.y.y
584         if (ip.match(/^(.*)-(.*)$/)) {
585                 a = fixIP(RegExp.$1);
586                 b = fixIP(RegExp.$2);
587                 if ((a == null) || (b == null)) {
588                         ferror.set(e, oip + ' - invalid IP address range', quiet);
589                         return null;
590                 }
591                 ferror.clear(e);
593                 if (aton(a) > aton(b)) return b + '-' + a;
594                 return a + '-' + b;
595         }
597         ma = '';
599         // x.x.x.x/nn
600         // x.x.x.x/y.y.y.y
601         if (ip.match(/^(.*)\/(.*)$/)) {
602                 ip = RegExp.$1;
603                 b = RegExp.$2;
605                 ma = b * 1;
606                 if (isNaN(ma)) {
607                         ma = fixIP(b);
608                         if ((ma == null) || (!_v_netmask(ma))) {
609                                 ferror.set(e, oip + ' - invalid netmask', quiet);
610                                 return null;
611                         }
612                 }
613                 else {
614                         if ((ma < 0) || (ma > 32)) {
615                                 ferror.set(e, oip + ' - invalid netmask', quiet);
616                                 return null;
617                         }
618                 }
619         }
621         ip = fixIP(ip);
622         if (!ip) {
623                 ferror.set(e, oip + ' - invalid IP address', quiet);
624                 return null;
625         }
627         ferror.clear(e);
628         return ip + ((ma != '') ? ('/' + ma) : '');
631 function v_iptip(e, quiet, multi)
633         var v, i;
635         if ((e = E(e)) == null) return 0;
636         v = e.value.split(',');
637         if (multi) {
638                 if (v.length > multi) {
639                         ferror.set(e, 'Too many IP addresses', quiet);
640                         return 0;
641                 }
642         }
643         else {
644                 if (v.length > 1) {
645                         ferror.set(e, 'Invalid IP address', quiet);
646                         return 0;
647                 }
648         }
649         for (i = 0; i < v.length; ++i) {
650                 if ((v[i] = _v_iptip(e, v[i], quiet)) == null) return 0;
651         }
652         e.value = v.join(', ');
653         return 1;
656 function _v_domain(e, dom, quiet)
658         var s;
660         s = dom.replace(/\s+/g, ' ').trim();
661         if (s.length > 0) {
662                 s = _v_hostname(e, s, 1, 1, 7, '.', true);
663                 if (s == null) {
664                         ferror.set(e, "Invalid name. Only characters \"A-Z 0-9 . -\" are allowed.", quiet);
665                         return null;
666                 }
667         }
668         ferror.clear(e);
669         return s;
672 function v_domain(e, quiet)
674         var v;
676         if ((e = E(e)) == null) return 0;
677         if ((v = _v_domain(e, e.value, quiet)) == null) return 0;
679         e.value = v;
680         return 1;
683 /* IPV6-BEGIN */
684 function ExpandIPv6Address(ip)
686         var a, pre, n, i, fill, post;
688         ip = ip.toLowerCase();
689         if (!ip.match(/^(::)?([a-f0-9]{1,4}::?){0,7}([a-f0-9]{1,4})(::)?$/)) return null;
691         a = ip.split('::');
692         switch (a.length) {
693         case 1:
694                 if (a[0] == '') return null;
695                 pre = a[0].split(':');
696                 if (pre.length != 8) return null;
697                 ip = pre.join(':');
698                 break;
699         case 2:
700                 pre = a[0].split(':');
701                 post = a[1].split(':');
702                 n = 8 - pre.length - post.length;
703                 for (i=0; i<2; i++) {
704                         if (a[i]=='') n++;
705                 }
706                 if (n < 0) return null;
707                 fill = '';
708                 while (n-- > 0) fill += ':0';
709                 ip = pre.join(':') + fill + ':' + post.join(':');
710                 ip = ip.replace(/^:/, '').replace(/:$/, '');
711                 break;
712         default:
713                 return null;
714         }
715         
716         ip = ip.replace(/([a-f0-9]{1,4})/ig, '000$1');
717         ip = ip.replace(/0{0,3}([a-f0-9]{4})/ig, '$1');
718         return ip;
721 function CompressIPv6Address(ip)
723         var a, segments;
724         
725         ip = ExpandIPv6Address(ip);
726         if (!ip) return null;
727         
728         // if (ip.match(/(?:^00)|(?:^fe[8-9a-b])|(?:^ff)/)) return null; // not valid routable unicast address
730         ip = ip.replace(/(^|:)0{1,3}/g, '$1');
731         ip = ip.replace(/(:0)+$/, '::');
732         ip = ip.replace(/(?:(?:^|:)0){2,}(?!.*(?:::|(?::0){3,}))/, ':');
733         return ip;
736 function ZeroIPv6PrefixBits(ip, prefix_length)
738         var b, c, m, n;
739         ip = ExpandIPv6Address(ip);
740         ip = ip.replace(/:/g,'');
741         n = Math.floor(prefix_length/4);
742         m = 32 - Math.ceil(prefix_length/4);
743         b = prefix_length % 4;
744         if (b != 0) 
745                 c = (parseInt(ip.charAt(n), 16) & (0xf << 4-b)).toString(16);
746         else
747                 c = '';
748         
749         ip = ip.substring(0, n) + c + Array((m%4)+1).join('0') + (m>=4 ? '::' : '');
750         ip = ip.replace(/([a-f0-9]{4})(?=[a-f0-9])/g,'$1:');
751         ip = ip.replace(/(^|:)0{1,3}/g, '$1');
752         return ip;
755 function ipv6ton(ip)
757         var o, x, i;
759         ip = ExpandIPv6Address(ip);
760         if (!ip) return 0;
762         o = ip.split(':');
763         x = '';
764         for (i = 0; i < 8; ++i) x += (('0x' + o[i]) * 1).hex(4);
765         return parseInt(x, 16);
768 function _v_ipv6_addr(e, ip, ipt, quiet)
770         var oip;
771         var a, b;
773         oip = ip;
775         // ip range
776         if ((ipt) && ip.match(/^(.*)-(.*)$/)) {
777                 a = RegExp.$1;
778                 b = RegExp.$2;
779                 a = CompressIPv6Address(a);
780                 b = CompressIPv6Address(b);
781                 if ((a == null) || (b == null)) {
782                         ferror.set(e, oip + ' - invalid IPv6 address range', quiet);
783                         return null;
784                 }
785                 ferror.clear(e);
787                 if (ipv6ton(a) > ipv6ton(b)) return b + '-' + a;
788                 return a + '-' + b;
789         }
791         // mask matches
792         if ((ipt) && ip.match(/^([A-Fa-f0-9:]+)\/([A-Fa-f0-9:]+)$/)) {
793                 a = RegExp.$1;
794                 b = RegExp.$2;
795                 a = CompressIPv6Address(a);
796                 b = CompressIPv6Address(b);
797                 if ((a == null) || (b == null)) {
798                         ferror.set(e, oip + ' - invalid IPv6 address with mask', quiet);
799                         return null;
800                 }
801                 ferror.clear(e);
803                 return ip;
804         }
806         
807         if ((ipt) && ip.match(/^([A-Fa-f0-9:]+)\/(\d+)$/)) {
808                 a = RegExp.$1;
809                 b = parseInt(RegExp.$2, 10);
810                 a = ExpandIPv6Address(a);
811                 if ((a == null) || (b == null)) {
812                         ferror.set(e, oip + ' - invalid IPv6 address', quiet);
813                         return null;
814                 }
815                 if (b < 0 || b > 128) {
816                         ferror.set(e, oip + ' - invalid CIDR notation on IPv6 address', quiet);
817                         return null;
818                 }
819                 ferror.clear(e);
821                 ip = ZeroIPv6PrefixBits(a, b);
822                 return ip + '/' + b.toString(10);
823         }
825         ip = CompressIPv6Address(oip);
826         if (!ip) {
827                 ferror.set(e, oip + ' - invalid IPv6 address', quiet);
828                 return null;
829         }
831         ferror.clear(e);
832         return ip;
835 function v_ipv6_addr(e, quiet)
837         if ((e = E(e)) == null) return 0;
839         ip = _v_ipv6_addr(e, e.value, false, quiet);
840         if (ip) e.value = ip;
841         return (ip != null);
843 /* IPV6-END */
845 function fixPort(p, def)
847         if (def == null) def = -1;
848         if (p == null) return def;
849         p *= 1;
850         if ((isNaN(p) || (p < 1) || (p > 65535) || (('' + p).indexOf('.') != -1))) return def;
851         return p;
854 function _v_portrange(e, quiet, v)
856         if (v.match(/^(.*)[-:](.*)$/)) {
857                 var x = RegExp.$1;
858                 var y = RegExp.$2;
860                 x = fixPort(x, -1);
861                 y = fixPort(y, -1);
862                 if ((x == -1) || (y == -1)) {
863                         ferror.set(e, 'Invalid port range: ' + v, quiet);
864                         return null;
865                 }
866                 if (x > y) {
867                         v = x;
868                         x = y;
869                         y = v;
870                 }
871                 ferror.clear(e);
872                 if (x == y) return x;
873                 return x + '-' + y;
874         }
876         v = fixPort(v, -1);
877         if (v == -1) {
878                 ferror.set(e, 'Invalid port', quiet);
879                 return null;
880         }
882         ferror.clear(e);
883         return v;
886 function v_portrange(e, quiet)
888         var v;
890         if ((e = E(e)) == null) return 0;
891         v = _v_portrange(e, quiet, e.value);
892         if (v == null) return 0;
893         e.value = v;
894         return 1;
897 function v_iptport(e, quiet)
899         var a, i, v, q;
901         if ((e = E(e)) == null) return 0;
903         a = e.value.split(/[,\.]/);
905         if (a.length == 0) {
906                 ferror.set(e, 'Expecting a list of ports or port range.', quiet);
907                 return 0;
908         }
909         if (a.length > 10) {
910                 ferror.set(e, 'Only 10 ports/range sets are allowed.', quiet);
911                 return 0;
912         }
914         q = [];
915         for (i = 0; i < a.length; ++i) {
916                 v = _v_portrange(e, quiet, a[i]);
917                 if (v == null) return 0;
918                 q.push(v);
919         }
921         e.value = q.join(',');
922         ferror.clear(e);
923         return 1;
926 function _v_netmask(mask)
928         var v = aton(mask) ^ 0xFFFFFFFF;
929         return (((v + 1) & v) == 0);
932 function v_netmask(e, quiet)
934         var n, b;
936         if ((e = E(e)) == null) return 0;
937         n = fixIP(e.value);
938         if (n) {
939                 if (_v_netmask(n)) {
940                         e.value = n;
941                         ferror.clear(e);
942                         return 1;
943                 }
944         }
945         else if (e.value.match(/^\s*\/\s*(\d+)\s*$/)) {
946                 b = RegExp.$1 * 1;
947                 if ((b >= 1) && (b <= 32)) {
948                         if (b == 32) n = 0xFFFFFFFF;    // js quirk
949                                 else n = (0xFFFFFFFF >>> b) ^ 0xFFFFFFFF;
950                         e.value = (n >>> 24) + '.' + ((n >>> 16) & 0xFF) + '.' + ((n >>> 8) & 0xFF) + '.' + (n & 0xFF);
951                         ferror.clear(e);
952                         return 1;
953                 }
954         }
955         ferror.set(e, 'Invalid netmask', quiet);
956         return 0;
959 function fixMAC(mac)
961         var t, i;
963         mac = mac.replace(/\s+/g, '').toUpperCase();
964         if (mac.length == 0) {
965                 mac = [0,0,0,0,0,0];
966         }
967         else if (mac.length == 12) {
968                 mac = mac.match(/../g);
969         }
970         else {
971                 mac = mac.split(/[:\-]/);
972                 if (mac.length != 6) return null;
973         }
974         for (i = 0; i < 6; ++i) {
975                 t = '' + mac[i];
976                 if (t.search(/^[0-9A-F]+$/) == -1) return null;
977                 if ((t = parseInt(t, 16)) > 255) return null;
978                 mac[i] = t.hex(2);
979         }
980         return mac.join(':');
983 function v_mac(e, quiet)
985         var mac;
987         if ((e = E(e)) == null) return 0;
988         mac = fixMAC(e.value);
989         if ((!mac) || (isMAC0(mac))) {
990                 ferror.set(e, 'Invalid MAC address', quiet);
991                 return 0;
992         }
993         e.value = mac;
994         ferror.clear(e);
995         return 1;
998 function v_macz(e, quiet)
1000         var mac;
1002         if ((e = E(e)) == null) return 0;
1003         mac = fixMAC(e.value);
1004         if (!mac) {
1005                 ferror.set(e, 'Invalid MAC address', quiet);
1006                 return false;
1007         }
1008         e.value = mac;
1009         ferror.clear(e);
1010         return true;
1013 function v_length(e, quiet, min, max)
1015         var s, n;
1017         if ((e = E(e)) == null) return 0;
1018         s = e.value.trim();
1019         n = s.length;
1020         if (min == undefined) min = 1;
1021         if (n < min) {
1022                 ferror.set(e, 'Invalid length. Please enter at least ' + min + ' character' + (min == 1 ? '.' : 's.'), quiet);
1023                 return 0;
1024         }
1025         max = max || e.maxlength;
1026         if (n > max) {
1027                 ferror.set(e, 'Invalid length. Please reduce the length to ' + max + ' characters or less.', quiet);
1028                 return 0;
1029         }
1030         e.value = s;
1031         ferror.clear(e);
1032         return 1;
1035 function _v_iptaddr(e, quiet, multi, ipv4, ipv6)
1037         var v, t, i;
1039         if ((e = E(e)) == null) return 0;
1040         v = e.value.split(',');
1041         if (multi) {
1042                 if (v.length > multi) {
1043                         ferror.set(e, 'Too many addresses', quiet);
1044                         return 0;
1045                 }
1046         }
1047         else {
1048                 if (v.length > 1) {
1049                         ferror.set(e, 'Invalid domain name or IP address', quiet);
1050                         return 0;
1051                 }
1052         }
1054         for (i = 0; i < v.length; ++i) {
1055                 if ((t = _v_domain(e, v[i], 1)) == null) {
1056 /* IPV6-BEGIN */
1057                         if ((!ipv6) && (!ipv4)) {
1058                                 if (!quiet) ferror.show(e);
1059                                 return 0;
1060                         }
1061                         if ((!ipv6) || ((t = _v_ipv6_addr(e, v[i], 1, 1)) == null)) {
1062 /* IPV6-END */
1063                                 if (!ipv4) {
1064                                         if (!quiet) ferror.show(e);
1065                                         return 0;
1066                                 }
1067                                 if ((t = _v_iptip(e, v[i], 1)) == null) {
1068                                         ferror.set(e, e._error_msg + ', or invalid domain name', quiet);
1069                                         return 0;
1070                                 }
1071 /* IPV6-BEGIN */
1072                         }
1073 /* IPV6-END */
1074                 }
1075                 v[i] = t;
1076         }
1078         e.value = v.join(', ');
1079         ferror.clear(e);
1080         return 1;
1083 function v_iptaddr(e, quiet, multi)
1085         return _v_iptaddr(e, quiet, multi, 1, 0);
1088 function _v_hostname(e, h, quiet, required, multi, delim, cidr)
1090         var s;
1091         var v, i;
1092         var re;
1094         v = (typeof(delim) == 'undefined') ? h.split(/\s+/) : h.split(delim);
1096         if (multi) {
1097                 if (v.length > multi) {
1098                         ferror.set(e, 'Too many hostnames.', quiet);
1099                         return null;
1100                 }
1101         }
1102         else {
1103                 if (v.length > 1) {
1104                         ferror.set(e, 'Invalid hostname.', quiet);
1105                         return null;
1106                 }
1107         }
1109         re = /^[a-zA-Z0-9](([a-zA-Z0-9\-]{0,61})[a-zA-Z0-9]){0,1}$/;
1111         for (i = 0; i < v.length; ++i) {
1112                 s = v[i].replace(/_+/g, '-').replace(/\s+/g, '-');
1113                 if (s.length > 0) {
1114                         if (cidr && i == v.length-1)
1115                                 re = /^[a-zA-Z0-9](([a-zA-Z0-9\-]{0,61})[a-zA-Z0-9]){0,1}(\/\d{1,3})?$/;
1116                         if (s.search(re) == -1 || s.search(/^\d+$/) != -1) {
1117                                 ferror.set(e, 'Invalid hostname. Only "A-Z 0-9" and "-" in the middle are allowed (up to 63 characters).', quiet);
1118                                 return null;
1119                         }
1120                 } else if (required) {
1121                         ferror.set(e, 'Invalid hostname.', quiet);
1122                         return null;
1123                 }
1124                 v[i] = s;
1125         }
1127         ferror.clear(e);
1128         return v.join((typeof(delim) == 'undefined') ? ' ' : delim);
1131 function v_hostname(e, quiet, multi, delim)
1133         var v;
1135         if ((e = E(e)) == null) return 0;
1137         v = _v_hostname(e, e.value, quiet, 0, multi, delim, false);
1139         if (v == null) return 0;
1141         e.value = v;
1142         return 1;
1145 function v_nodelim(e, quiet, name, checklist)
1147         if ((e = E(e)) == null) return 0;
1149         e.value = e.value.trim();
1150         if (e.value.indexOf('<') != -1 ||
1151            (checklist && e.value.indexOf('>') != -1)) {
1152                 ferror.set(e, 'Invalid ' + name + ': \"<\" ' + (checklist ? 'or \">\" are' : 'is') + ' not allowed.', quiet);
1153                 return 0;
1154         }
1155         ferror.clear(e);
1156         return 1;
1159 function v_path(e, quiet, required)
1161         if ((e = E(e)) == null) return 0;
1162         if (required && !v_length(e, quiet, 1)) return 0;
1164         if (!required && e.value.trim().length == 0) {
1165                 ferror.clear(e);
1166                 return 1;
1167         }
1168         if (e.value.substr(0, 1) != '/') {
1169                 ferror.set(e, 'Please start at the / root directory.', quiet);
1170                 return 0;
1171         }
1172         ferror.clear(e);
1173         return 1;
1176 function isMAC0(mac)
1178         return (mac == '00:00:00:00:00:00');
1181 // -----------------------------------------------------------------------------
1183 function cmpIP(a, b)
1185         if ((a = fixIP(a)) == null) a = '255.255.255.255';
1186         if ((b = fixIP(b)) == null) b = '255.255.255.255';
1187         return aton(a) - aton(b);
1190 function cmpText(a, b)
1192         if (a == '') a = '\xff';
1193         if (b == '') b = '\xff';
1194         return (a < b) ? -1 : ((a > b) ? 1 : 0);
1197 function cmpInt(a, b)
1199         a = parseInt(a, 10);
1200         b = parseInt(b, 10);
1201         return ((isNaN(a)) ? -0x7FFFFFFF : a) - ((isNaN(b)) ? -0x7FFFFFFF : b);
1204 function cmpFloat(a, b)
1206         a = parseFloat(a);
1207         b = parseFloat(b);
1208         return ((isNaN(a)) ? -Number.MAX_VALUE : a) - ((isNaN(b)) ? -Number.MAX_VALUE : b);
1211 function cmpDate(a, b)
1213         return b.getTime() - a.getTime();
1216 // -----------------------------------------------------------------------------
1218 // ---- todo: cleanup this mess
1220 function TGO(e)
1222         return elem.parentElem(e, 'TABLE').gridObj;
1225 function tgHideIcons()
1227         var e;
1228         while ((e = document.getElementById('tg-row-panel')) != null) e.parentNode.removeChild(e);
1231 // ---- options = sort, move, delete
1232 function TomatoGrid(tb, options, maxAdd, editorFields)
1234         this.init(tb, options, maxAdd, editorFields);
1235         return this;
1238 TomatoGrid.prototype = {
1239         init: function(tb, options, maxAdd, editorFields) {
1240                 if (tb) {
1241                         this.tb = E(tb);
1242                         this.tb.gridObj = this;
1243                 }
1244                 else {
1245                         this.tb = null;
1246                 }
1247                 if (!options) options = '';
1248                 this.header = null;
1249                 this.footer = null;
1250                 this.editor = null;
1251                 this.canSort = options.indexOf('sort') != -1;
1252                 this.canMove = options.indexOf('move') != -1;
1253                 this.maxAdd = maxAdd || 500;
1254                 this.canEdit = (editorFields != null);
1255                 this.canDelete = this.canEdit || (options.indexOf('delete') != -1);
1256                 this.editorFields = editorFields;
1257                 this.sortColumn = -1;
1258                 this.sortAscending = true;
1259         },
1261         _insert: function(at, cells, escCells) {
1262                 var tr, td, c;
1263                 var i, t;
1265                 tr = this.tb.insertRow(at);
1266                 for (i = 0; i < cells.length; ++i) {
1267                         c = cells[i];
1268                         if (typeof(c) == 'string') {
1269                                 td = tr.insertCell(i);
1270                                 td.className = 'co' + (i + 1);
1271                                 if (escCells) td.appendChild(document.createTextNode(c));
1272                                         else td.innerHTML = c;
1273                         }
1274                         else {
1275                                 tr.appendChild(c);
1276                         }
1277                 }
1278                 return tr;
1279         },
1281         // ---- header
1283         headerClick: function(cell) {
1284                 if (this.canSort) {
1285                         this.sort(cell.cellN);
1286                 }
1287         },
1289         headerSet: function(cells, escCells) {
1290                 var e, i;
1292                 elem.remove(this.header);
1293                 this.header = e = this._insert(0, cells, escCells);
1294                 e.className = 'header';
1296                 for (i = 0; i < e.cells.length; ++i) {
1297                         e.cells[i].cellN = i;   // cellIndex broken in Safari
1298                         e.cells[i].onclick = function() { return TGO(this).headerClick(this); };
1299                 }
1300                 return e;
1301         },
1303         // ---- footer
1305         footerClick: function(cell) {
1306         },
1308         footerSet: function(cells, escCells) {
1309                 var e, i;
1311                 elem.remove(this.footer);
1312                 this.footer = e = this._insert(-1, cells, escCells);
1313                 e.className = 'footer';
1314                 for (i = 0; i < e.cells.length; ++i) {
1315                         e.cells[i].cellN = i;
1316                         e.cells[i].onclick = function() { TGO(this).footerClick(this) };
1317                 }
1318                 return e;
1319         },
1321         // ----
1323         rpUp: function(e) {
1324                 var i;
1326                 e = PR(e);
1327                 TGO(e).moving = null;
1328                 i = e.previousSibling;
1329                 if (i == this.header) return;
1330                 e.parentNode.removeChild(e);
1331                 i.parentNode.insertBefore(e, i);
1333                 this.recolor();
1334                 this.rpHide();
1335         },
1337         rpDn: function(e) {
1338                 var i;
1340                 e = PR(e);
1341                 TGO(e).moving = null;
1342                 i = e.nextSibling;
1343                 if (i == this.footer) return;
1344                 e.parentNode.removeChild(e);
1345                 i.parentNode.insertBefore(e, i.nextSibling);
1347                 this.recolor();
1348                 this.rpHide();
1349         },
1351         rpMo: function(img, e) {
1352                 var me;
1354                 e = PR(e);
1355                 me = TGO(e);
1356                 if (me.moving == e) {
1357                         me.moving = null;
1358                         this.rpHide();
1359                         return;
1360                 }
1361                 me.moving = e;
1362                 img.style.border = "1px dotted red";
1363         },
1365         rpDel: function(e) {
1366                 e = PR(e);
1367                 TGO(e).moving = null;
1368                 e.parentNode.removeChild(e);
1369                 this.recolor();
1370                 this.rpHide();
1371         },
1373         rpMouIn: function(evt) {
1374                 var e, x, ofs, me, s, n;
1376                 if ((evt = checkEvent(evt)) == null) return;
1378                 me = TGO(evt.target);
1379                 if (me.isEditing()) return;
1380                 if (me.moving) return;
1382                 me.rpHide();
1383                 e = document.createElement('div');
1384                 e.tgo = me;
1385                 e.ref = evt.target;
1386                 e.setAttribute('id', 'tg-row-panel');
1388                 n = 0;
1389                 s = '';
1390                 if (me.canMove) {
1391                         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">';
1392                         n += 3;
1393                 }
1394                 if (me.canDelete) {
1395                         s += '<img src="rpx.gif" onclick="this.parentNode.tgo.rpDel(this.parentNode.ref)" title="Delete">';
1396                         ++n;
1397                 }
1398                 x = PR(evt.target);
1399                 x = x.cells[x.cells.length - 1];
1400                 ofs = elem.getOffset(x);
1401                 n *= 18;
1402                 e.style.left = (ofs.x + x.offsetWidth - n) + 'px';
1403                 e.style.top = ofs.y + 'px';
1404                 e.style.width = n + 'px';
1405                 e.innerHTML = s;
1407                 document.body.appendChild(e);
1408         },
1410         rpHide: tgHideIcons,
1412         // ----
1414         onClick: function(cell) {
1415                 if (this.canEdit) {
1416                         if (this.moving) {
1417                                 var p = this.moving.parentNode;
1418                                 var q = PR(cell);
1419                                 if (this.moving != q) {
1420                                         var v = this.moving.rowIndex > q.rowIndex;
1421                                         p.removeChild(this.moving);
1422                                         if (v) p.insertBefore(this.moving, q);
1423                                                 else p.insertBefore(this.moving, q.nextSibling);
1424                                         this.recolor();
1425                                 }
1426                                 this.moving = null;
1427                                 this.rpHide();
1428                                 return;
1429                         }
1430                         this.edit(cell);
1431                 }
1432         },
1434         insert: function(at, data, cells, escCells) {
1435                 var e, i;
1437                 if ((this.footer) && (at == -1)) at = this.footer.rowIndex;
1438                 e = this._insert(at, cells, escCells);
1439                 e.className = (e.rowIndex & 1) ? 'even' : 'odd';
1441                 for (i = 0; i < e.cells.length; ++i) {
1442                         e.cells[i].onclick = function() { return TGO(this).onClick(this); };
1443                 }
1445                 e._data = data;
1446                 e.getRowData = function() { return this._data; }
1447                 e.setRowData = function(data) { this._data = data; }
1449                 if ((this.canMove) || (this.canEdit) || (this.canDelete)) {
1450                         e.onmouseover = this.rpMouIn;
1451 // ----                 e.onmouseout = this.rpMouOut;
1452                         if (this.canEdit) e.title = 'Click to edit';
1453                 }
1455                 return e;
1456         },
1458         // ----
1460         insertData: function(at, data) {
1461                 return this.insert(at, data, this.dataToView(data), false);
1462         },
1464         dataToView: function(data) {
1465                 var v = [];
1466                 for (var i = 0; i < data.length; ++i) {
1467                         var s = escapeHTML('' + data[i]);
1468                         if (this.editorFields && this.editorFields.length > i) {
1469                                 var ef = this.editorFields[i].multi;
1470                                 if (!ef) ef = [this.editorFields[i]];
1471                                 var f = (ef && ef.length > 0 ? ef[0] : null);
1472                                 if (f && f.type == 'password') {
1473                                         if (!f.peekaboo || get_config('web_pb', '1') != '0')
1474                                                 s = s.replace(/./g, '&#x25CF;');
1475                                 }
1476                         }
1477                         v.push(s);
1478                 }
1479                 return v;
1480         },
1482         dataToFieldValues: function(data) {
1483                 return data;
1484         },
1486         fieldValuesToData: function(row) {
1487                 var e, i, data;
1489                 data = [];
1490                 e = fields.getAll(row);
1491                 for (i = 0; i < e.length; ++i) data.push(e[i].value);
1492                 return data;
1493         },
1495         // ----
1497         edit: function(cell) {
1498                 var sr, er, e, c;
1500                 if (this.isEditing()) return;
1502                 sr = PR(cell);
1503                 sr.style.display = 'none';
1504                 elem.removeClass(sr, 'hover');
1505                 this.source = sr;
1507                 er = this.createEditor('edit', sr.rowIndex, sr);
1508                 er.className = 'editor';
1509                 this.editor = er;
1511                 c = er.cells[cell.cellIndex || 0];
1512                 e = c.getElementsByTagName('input');
1513                 if ((e) && (e.length > 0)) {
1514                         try {   // IE quirk
1515                                 e[0].focus();
1516                         }
1517                         catch (ex) {
1518                         }
1519                 }
1521                 this.controls = this.createControls('edit', sr.rowIndex);
1523                 this.disableNewEditor(true);
1524                 this.rpHide();
1525                 this.verifyFields(this.editor, true);
1526         },
1528         createEditor: function(which, rowIndex, source) {
1529                 var values;
1531                 if (which == 'edit') values = this.dataToFieldValues(source.getRowData());
1533                 var row = this.tb.insertRow(rowIndex);
1534                 row.className = 'editor';
1536                 var common = ' onkeypress="return TGO(this).onKey(\'' + which + '\', event)" onchange="TGO(this).onChange(\'' + which + '\', this)"';
1538                 var vi = 0;
1539                 for (var i = 0; i < this.editorFields.length; ++i) {
1540                         var s = '';
1541                         var ef = this.editorFields[i].multi;
1542                         if (!ef) ef = [this.editorFields[i]];
1544                         for (var j = 0; j < ef.length; ++j) {
1545                                 var f = ef[j];
1547                                 if (f.prefix) s += f.prefix;
1548                                 var attrib = ' class="fi' + (vi + 1) + '" ' + (f.attrib || '');
1549                                 var id = (this.tb ? ('_' + this.tb + '_' + (vi + 1)) : null);
1550                                 if (id) attrib += ' id="' + id + '"';
1551                                 switch (f.type) {
1552                                 case 'password':
1553                                         if (f.peekaboo) {
1554                                                 switch (get_config('web_pb', '1')) {
1555                                                 case '0':
1556                                                         f.type = 'text';
1557                                                 case '2':
1558                                                         f.peekaboo = 0;
1559                                                         break;
1560                                                 }
1561                                         }
1562                                         attrib += ' autocomplete="off"';
1563                                         if (f.peekaboo && id) attrib += ' onfocus=\'peekaboo("' + id + '",1)\'';
1564                                         // drop
1565                                 case 'text':
1566                                         s += '<input type="' + f.type + '" maxlength=' + f.maxlen + common + attrib;
1567                                         if (which == 'edit') s += ' value="' + escapeHTML('' + values[vi]) + '">';
1568                                                 else s += '>';
1569                                         break;
1570                                 case 'select':
1571                                         s += '<select' + common + attrib + '>';
1572                                         for (var k = 0; k < f.options.length; ++k) {
1573                                                 a = f.options[k];
1574                                                 if (which == 'edit') {
1575                                                         s += '<option value="' + a[0] + '"' + ((a[0] == values[vi]) ? ' selected>' : '>') + a[1] + '</option>';
1576                                                 }
1577                                                 else {
1578                                                         s += '<option value="' + a[0] + '">' + a[1] + '</option>';
1579                                                 }
1580                                         }
1581                                         s += '</select>';
1582                                         break;
1583                                 case 'checkbox':
1584                                         s += '<input type="checkbox"' + common + attrib;
1585                                         if ((which == 'edit') && (values[vi])) s += ' checked';
1586                                         s += '>';
1587                                         break;
1588                                 default:
1589                                         s += f.custom.replace(/\$which\$/g, which);
1590                                 }
1591                                 if (f.suffix) s += f.suffix;
1593                                 ++vi;
1594                         }
1595                         var c = row.insertCell(i);
1596                         c.innerHTML = s;
1597                         if (this.editorFields[i].vtop) c.vAlign = 'top';
1598                 }
1600                 return row;
1601         },
1603         createControls: function(which, rowIndex) {
1604                 var r, c;
1606                 r = this.tb.insertRow(rowIndex);
1607                 r.className = 'controls';
1609                 c = r.insertCell(0);
1610                 c.colSpan = this.header.cells.length;
1611                 if (which == 'edit') {
1612                         c.innerHTML =
1613                                 '<input type=button value="Delete" onclick="TGO(this).onDelete()"> &nbsp; ' +
1614                                 '<input type=button value="OK" onclick="TGO(this).onOK()"> ' +
1615                                 '<input type=button value="Cancel" onclick="TGO(this).onCancel()">';
1616                 }
1617                 else {
1618                         c.innerHTML =
1619                                 '<input type=button value="Add" onclick="TGO(this).onAdd()">';
1620                 }
1621                 return r;
1622         },
1624         removeEditor: function() {
1625                 if (this.editor) {
1627                         elem.remove(this.editor);
1628                         this.editor = null;
1629                 }
1630                 if (this.controls) {
1631                         elem.remove(this.controls);
1632                         this.controls = null;
1633                 }
1634         },
1636         showSource: function() {
1637                 if (this.source) {
1638                         this.source.style.display = '';
1639                         this.source = null;
1640                 }
1641         },
1643         onChange: function(which, cell) {
1644                 return this.verifyFields((which == 'new') ? this.newEditor : this.editor, true);
1645         },
1647         onKey: function(which, ev) {
1648                 switch (ev.keyCode) {
1649                 case 27:
1650                         if (which == 'edit') this.onCancel();
1651                         return false;
1652                 case 13:
1653                         if (((ev.srcElement) && (ev.srcElement.tagName == 'SELECT')) ||
1654                                 ((ev.target) && (ev.target.tagName == 'SELECT'))) return true;
1655                         if (which == 'edit') this.onOK();
1656                                 else this.onAdd();
1657                         return false;
1658                 }
1659                 return true;
1660         },
1662         onDelete: function() {
1663                 this.removeEditor();
1664                 elem.remove(this.source);
1665                 this.source = null;
1666                 this.disableNewEditor(false);
1667         },
1669         onCancel: function() {
1670                 this.removeEditor();
1671                 this.showSource();
1672                 this.disableNewEditor(false);
1673         },
1675         onOK: function() {
1676                 var i, data, view;
1678                 if (!this.verifyFields(this.editor, false)) return;
1680                 data = this.fieldValuesToData(this.editor);
1681                 view = this.dataToView(data);
1683                 this.source.setRowData(data);
1684                 for (i = 0; i < this.source.cells.length; ++i) {
1685                         this.source.cells[i].innerHTML = view[i];
1686                 }
1688                 this.removeEditor();
1689                 this.showSource();
1690                 this.disableNewEditor(false);
1691         },
1693         onAdd: function() {
1694                 var data;
1696                 this.moving = null;
1697                 this.rpHide();
1699                 if (!this.verifyFields(this.newEditor, false)) return;
1701                 data = this.fieldValuesToData(this.newEditor);
1702                 this.insertData(-1, data);
1704                 this.disableNewEditor(false);
1705                 this.resetNewEditor();
1706         },
1708         verifyFields: function(row, quiet) {
1709                 return true;
1710         },
1712         showNewEditor: function() {
1713                 var r;
1715                 r = this.createEditor('new', -1, null);
1716                 this.footer = this.newEditor = r;
1718                 r = this.createControls('new', -1);
1719                 this.newControls = r;
1721                 this.disableNewEditor(false);
1722         },
1724         disableNewEditor: function(disable) {
1725                 if (this.getDataCount() >= this.maxAdd) disable = true;
1726                 if (this.newEditor) fields.disableAll(this.newEditor, disable);
1727                 if (this.newControls) fields.disableAll(this.newControls, disable);
1728         },
1730         resetNewEditor: function() {
1731                 var i, e;
1733                 e = fields.getAll(this.newEditor);
1734                 ferror.clearAll(e);
1735                 for (i = 0; i < e.length; ++i) {
1736                         var f = e[i];
1737                         if (f.selectedIndex) f.selectedIndex = 0;
1738                                 else f.value = '';
1739                 }
1740                 try { if (e.length) e[0].focus(); } catch (er) { }
1741         },
1743         getDataCount: function() {
1744                 var n;
1745                 n = this.tb.rows.length;
1746                 if (this.footer) n = this.footer.rowIndex;
1747                 if (this.header) n -= this.header.rowIndex + 1;
1748                 return n;
1749         },
1751         sortCompare: function(a, b) {
1752                 var obj = TGO(a);
1753                 var col = obj.sortColumn;
1754                 var r = cmpText(a.cells[col].innerHTML, b.cells[col].innerHTML);
1755                 return obj.sortAscending ? r : -r;
1756         },
1758         sort: function(column) {
1759                 if (this.editor) return;
1761                 if (this.sortColumn >= 0) {
1762                         elem.removeClass(this.header.cells[this.sortColumn], 'sortasc', 'sortdes');
1763                 }
1764                 if (column == this.sortColumn) {
1765                         this.sortAscending = !this.sortAscending;
1766                 }
1767                 else {
1768                         this.sortAscending = true;
1769                         this.sortColumn = column;
1770                 }
1771                 elem.addClass(this.header.cells[column], this.sortAscending ? 'sortasc' : 'sortdes');
1773                 this.resort();
1774         },
1776         resort: function() {
1777                 if ((this.sortColumn < 0) || (this.getDataCount() == 0) || (this.editor)) return;
1779                 var p = this.header.parentNode;
1780                 var a = [];
1781                 var i, j, max, e, p;
1782                 var top;
1784                 this.moving = null;
1786                 top = this.header ? this.header.rowIndex + 1 : 0;
1787                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1788                 for (i = top; i < max; ++i) a.push(p.rows[i]);
1789                 a.sort(THIS(this, this.sortCompare));
1790                 this.removeAllData();
1791                 j = top;
1792                 for (i = 0; i < a.length; ++i) {
1793                         e = p.insertBefore(a[i], this.footer);
1794                         e.className = (j & 1) ? 'even' : 'odd';
1795                         ++j;
1796                 }
1797         },
1799         recolor: function() {
1800                  var i, e, o;
1802                  i = this.header ? this.header.rowIndex + 1 : 0;
1803                  e = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1804                  for (; i < e; ++i) {
1805                          o = this.tb.rows[i];
1806                          o.className = (o.rowIndex & 1) ? 'even' : 'odd';
1807                  }
1808         },
1810         removeAllData: function() {
1811                 var i, count;
1813                 i = this.header ? this.header.rowIndex + 1 : 0;
1814                 count = (this.footer ? this.footer.rowIndex : this.tb.rows.length) - i;
1815                 while (count-- > 0) elem.remove(this.tb.rows[i]);
1816         },
1818         getAllData: function() {
1819                 var i, max, data, r;
1821                 data = [];
1822                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1823                 for (i = this.header ? this.header.rowIndex + 1 : 0; i < max; ++i) {
1824                         r = this.tb.rows[i];
1825                         if ((r.style.display != 'none') && (r._data)) data.push(r._data);
1826                 }
1827                 return data;
1828         },
1830         isEditing: function() {
1831                 return (this.editor != null);
1832         }
1836 // -----------------------------------------------------------------------------
1839 function xmlHttpObj()
1841         var ob;
1842         try {
1843                 ob = new XMLHttpRequest();
1844                 if (ob) return ob;
1845         }
1846         catch (ex) { }
1847         try {
1848                 ob = new ActiveXObject('Microsoft.XMLHTTP');
1849                 if (ob) return ob;
1850         }
1851         catch (ex) { }
1852         return null;
1855 var _useAjax = -1;
1856 var _holdAjax = null;
1858 function useAjax()
1860         if (_useAjax == -1) _useAjax = ((_holdAjax = xmlHttpObj()) != null);
1861         return _useAjax;
1864 function XmlHttp()
1866         if ((!useAjax()) || ((this.xob = xmlHttpObj()) == null)) return null;
1867         return this;
1870 XmlHttp.prototype = {
1871         addId: function(vars) {
1872                 if (vars) vars += '&';
1873                         else vars = '';
1874                 vars += '_http_id=' + escapeCGI(nvram.http_id);
1875                 return vars;
1876         },
1878         get: function(url, vars) {
1879                 try {
1880                         vars = this.addId(vars);
1881                         url += '?' + vars;
1883                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1884                         this.xob.open('GET', url, true);
1885                         this.xob.send(null);
1886                 }
1887                 catch (ex) {
1888                         this.onError(ex);
1889                 }
1890         },
1892         post: function(url, vars) {
1893                 try {
1894                         vars = this.addId(vars);
1896                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1897                         this.xob.open('POST', url, true);
1898                         this.xob.send(vars);
1899                 }
1900                 catch (ex) {
1901                         this.onError(ex);
1902                 }
1903         },
1905         abort: function() {
1906                 try {
1907                         this.xob.onreadystatechange = function () { }
1908                         this.xob.abort();
1909                 }
1910                 catch (ex) {
1911                 }
1912         },
1914         onReadyStateChange: function() {
1915                 try {
1916                         if (typeof(E) == 'undefined') return;   // oddly late? testing for bug...
1918                         if (this.xob.readyState == 4) {
1919                                 if (this.xob.status == 200) {
1920                                         this.onCompleted(this.xob.responseText, this.xob.responseXML);
1921                                 }
1922                                 else {
1923                                         this.onError('' + (this.xob.status || 'unknown'));
1924                                 }
1925                         }
1926                 }
1927                 catch (ex) {
1928                         this.onError(ex);
1929                 }
1930         },
1932         onCompleted: function(text, xml) { },
1933         onError: function(ex) { }
1937 // -----------------------------------------------------------------------------
1940 function TomatoTimer(func, ms)
1942         this.tid = null;
1943         this.onTimer = func;
1944         if (ms) this.start(ms);
1945         return this;
1948 TomatoTimer.prototype = {
1949         start: function(ms) {
1950                 this.stop();
1951                 this.tid = setTimeout(THIS(this, this._onTimer), ms);
1952         },
1953         stop: function() {
1954                 if (this.tid) {
1955                         clearTimeout(this.tid);
1956                         this.tid = null;
1957                 }
1958         },
1960         isRunning: function() {
1961                 return (this.tid != null);
1962         },
1964         _onTimer: function() {
1965                 this.tid = null;
1966                 this.onTimer();
1967         },
1969         onTimer: function() {
1970         }
1974 // -----------------------------------------------------------------------------
1977 function TomatoRefresh(actionURL, postData, refreshTime, cookieTag)
1979         this.setup(actionURL, postData, refreshTime, cookieTag);
1980         this.timer = new TomatoTimer(THIS(this, this.start));
1983 TomatoRefresh.prototype = {
1984         running: 0,
1986         setup: function(actionURL, postData, refreshTime, cookieTag) {
1987                 var e, v;
1989                 this.actionURL = actionURL;
1990                 this.postData = postData;
1991                 this.refreshTime = refreshTime * 1000;
1992                 this.cookieTag = cookieTag;
1993         },
1995         start: function() {
1996                 var e;
1998                 if ((e = E('refresh-time')) != null) {
1999                         if (this.cookieTag) cookie.set(this.cookieTag, e.value);
2000                         this.refreshTime = e.value * 1000;
2001                 }
2002                 e = undefined;
2004                 this.updateUI('start');
2006                 this.running = 1;
2007                 if ((this.http = new XmlHttp()) == null) {
2008                         reloadPage();
2009                         return;
2010                 }
2012                 this.http.parent = this;
2014                 this.http.onCompleted = function(text, xml) {
2015                         var p = this.parent;
2017                         if (p.cookieTag) cookie.unset(p.cookieTag + '-error');
2018                         if (!p.running) {
2019                                 p.stop();
2020                                 return;
2021                         }
2023                         p.refresh(text);
2025                         if ((p.refreshTime > 0) && (!p.once)) {
2026                                 p.updateUI('wait');
2027                                 p.timer.start(Math.round(p.refreshTime));
2028                         }
2029                         else {
2030                                 p.stop();
2031                         }
2033                         p.errors = 0;
2034                 }
2036                 this.http.onError = function(ex) {
2037                         var p = this.parent;
2038                         if ((!p) || (!p.running)) return;
2040                         p.timer.stop();
2042                         if (++p.errors <= 3) {
2043                                 p.updateUI('wait');
2044                                 p.timer.start(3000);
2045                                 return;
2046                         }
2048                         if (p.cookieTag) {
2049                                 var e = cookie.get(p.cookieTag + '-error') * 1;
2050                                 if (isNaN(e)) e = 0;
2051                                         else ++e;
2052                                 cookie.unset(p.cookieTag);
2053                                 cookie.set(p.cookieTag + '-error', e, 1);
2054                                 if (e >= 3) {
2055                                         alert('XMLHTTP: ' + ex);
2056                                         return;
2057                                 }
2058                         }
2060                         setTimeout(reloadPage, 2000);
2061                 }
2063                 this.errors = 0;
2064                 this.http.post(this.actionURL, this.postData);
2065         },
2067         stop: function() {
2068                 if (this.cookieTag) cookie.set(this.cookieTag, -(this.refreshTime / 1000));
2069                 this.running = 0;
2070                 this.updateUI('stop');
2071                 this.timer.stop();
2072                 this.http = null;
2073                 this.once = undefined;
2074         },
2076         toggle: function(delay) {
2077                 if (this.running) this.stop();
2078                         else this.start(delay);
2079         },
2081         updateUI: function(mode) {
2082                 var e, b;
2084                 if (typeof(E) == 'undefined') return;   // for a bizzare bug...
2086                 b = (mode != 'stop') && (this.refreshTime > 0);
2087                 if ((e = E('refresh-button')) != null) {
2088                         e.value = b ? 'Stop' : 'Refresh';
2089                         e.disabled = ((mode == 'start') && (!b));
2090                 }
2091                 if ((e = E('refresh-time')) != null) e.disabled = b;
2092                 if ((e = E('refresh-spinner')) != null) e.style.visibility = b ? 'visible' : 'hidden';
2093         },
2095         initPage: function(delay, def) {
2096                 var e, v;
2098                 e = E('refresh-time');
2099                 if (((this.cookieTag) && (e != null)) &&
2100                         ((v = cookie.get(this.cookieTag)) != null) && (!isNaN(v *= 1))) {
2101                         e.value = Math.abs(v);
2102                         if (v > 0) v = (v * 1000) + (delay || 0);
2103                 }
2104                 else if (def) {
2105                         v = def;
2106                         if (e) e.value = def;
2107                 }
2108                 else v = 0;
2110                 if (delay < 0) {
2111                         v = -delay;
2112                         this.once = 1;
2113                 }
2115                 if (v > 0) {
2116                         this.running = 1;
2117                         this.refreshTime = v;
2118                         this.timer.start(v);
2119                         this.updateUI('wait');
2120                 }
2121         }
2124 function genStdTimeList(id, zero, min)
2126         var b = [];
2127         var t = [0.5,1,2,3,4,5,10,15,30,60,120,180,240,300,10*60,15*60,20*60,30*60];
2128         var i, v;
2130         if (min >= 0) {
2131                 b.push('<select id="' + id + '"><option value=0>' + zero);
2132                 for (i = 0; i < t.length; ++i) {
2133                         v = t[i];
2134                         if (v < min) continue;
2135                         b.push('<option value=' + v + '>');
2136                         if (v == 60) b.push('1 minute');
2137                                 else if (v > 60) b.push((v / 60) + ' minutes');
2138                                 else if (v == 1) b.push('1 second');
2139                                 else b.push(v + ' seconds');
2140                 }
2141                 b.push('</select> ');
2142         }
2143         document.write(b.join(''));
2146 function genStdRefresh(spin, min, exec)
2148         W('<div style="text-align:right">');
2149         if (spin) W('<img src="spin.gif" id="refresh-spinner"> ');
2150         genStdTimeList('refresh-time', 'Auto Refresh', min);
2151         W('<input type="button" value="Refresh" onclick="' + (exec ? exec : 'refreshClick()') + '" id="refresh-button"></div>');
2155 // -----------------------------------------------------------------------------
2158 function _tabCreate(tabs)
2160         var buf = [];
2161         buf.push('<ul id="tabs">');
2162         for (var i = 0; i < arguments.length; ++i)
2163                 buf.push('<li><a href="javascript:tabSelect(\'' + arguments[i][0] + '\')" id="' + arguments[i][0] + '">' + arguments[i][1] + '</a>');
2164         buf.push('</ul><div id="tabs-bottom"></div>');
2165         return buf.join('');
2168 function tabCreate(tabs)
2170         document.write(_tabCreate.apply(this, arguments));
2173 function tabHigh(id)
2175         var a = E('tabs').getElementsByTagName('A');
2176         for (var i = 0; i < a.length; ++i) {
2177                 if (id != a[i].id) elem.removeClass(a[i], 'active');
2178         }
2179         elem.addClass(id, 'active');
2182 // -----------------------------------------------------------------------------
2184 var cookie = {
2185 // The value 2147483647000 is ((2^31)-1)*1000, which is the number of
2186 // milliseconds (minus 1 second) which correlates with the year 2038 counter
2187 // rollover. This effectively makes the cookie never expire.
2188 set: function(key, value, days) {
2189 document.cookie = 'tomato_' + encodeURIComponent(key) + '=' + encodeURIComponent(value) + '; expires=' +
2190 new Date(2147483647000).toUTCString() + '; path=/';
2192 get: function(key) {
2193 var r = ('; ' + document.cookie + ';').match('; tomato_' + encodeURIComponent(key) + '=(.*?);');
2194 return r ? decodeURIComponent(r[1]) : null;
2196 unset: function(key) {
2197 document.cookie = 'tomato_' + encodeURIComponent(key) + '=; expires=' +
2198 (new Date(1)).toUTCString() + '; path=/';
2202 // -----------------------------------------------------------------------------
2204 function checkEvent(evt)
2206         if (typeof(evt) == 'undefined') {
2207                 // ---- IE
2208                 evt = event;
2209                 evt.target = evt.srcElement;
2210                 evt.relatedTarget = evt.toElement;
2211         }
2212         return evt;
2215 function W(s)
2217         document.write(s);
2220 function E(e)
2222         return (typeof(e) == 'string') ? document.getElementById(e) : e;
2225 function PR(e)
2227         return elem.parentElem(e, 'TR');
2230 function THIS(obj, func)
2232         return function() { return func.apply(obj, arguments); }
2235 function UT(v)
2237         return (typeof(v) == 'undefined') ? '' : '' + v;
2240 function escapeHTML(s)
2242         function esc(c) {
2243                 return '&#' + c.charCodeAt(0) + ';';
2244         }
2245         return s.replace(/[&"'<>\r\n]/g, esc);
2248 function escapeCGI(s)
2250         return escape(s).replace(/\+/g, '%2B'); // escape() doesn't handle +
2253 function escapeD(s)
2255         function esc(c) {
2256                 return '%' + c.charCodeAt(0).hex(2);
2257         }
2258         return s.replace(/[<>|%]/g, esc);
2261 function ellipsis(s, max) {
2262         return (s.length <= max) ? s : s.substr(0, max - 3) + '...';
2265 function MIN(a, b)
2267         return (a < b) ? a : b;
2270 function MAX(a, b)
2272         return (a > b) ? a : b;
2275 function fixInt(n, min, max, def)
2277         if (n === null) return def;
2278         n *= 1;
2279         if (isNaN(n)) return def;
2280         if (n < min) return min;
2281         if (n > max) return max;
2282         return n;
2285 function comma(n)
2287         n = '' + n;
2288         var p = n;
2289         while ((n = n.replace(/(\d+)(\d{3})/g, '$1,$2')) != p) p = n;
2290         return n;
2293 function doScaleSize(n, sm)
2295         if (isNaN(n *= 1)) return '-';
2296         if (n <= 9999) return '' + n;
2297         var s = -1;
2298         do {
2299                 n /= 1024;
2300                 ++s;
2301         } while ((n > 9999) && (s < 2));
2302         return comma(n.toFixed(2)) + (sm ? '<small> ' : ' ') + (['KB', 'MB', 'GB'])[s] + (sm ? '</small>' : '');
2305 function scaleSize(n)
2307         return doScaleSize(n, 1);
2310 function timeString(mins)
2312         var h = Math.floor(mins / 60);
2313         if ((new Date(2000, 0, 1, 23, 0, 0, 0)).toLocaleString().indexOf('23') != -1)
2314                 return h + ':' + (mins % 60).pad(2);
2315         return ((h == 0) ? 12 : ((h > 12) ? h - 12 : h)) + ':' + (mins % 60).pad(2) + ((h >= 12) ? ' PM' : ' AM');
2318 function features(s)
2320         var features = ['ses','brau','aoss','wham','hpamp','!nve','11n','1000et'];
2321         var i;
2323         for (i = features.length - 1; i >= 0; --i) {
2324                 if (features[i] == s) return (parseInt(nvram.t_features) & (1 << i)) != 0;
2325         }
2326         return 0;
2329 function get_config(name, def)
2331         return ((typeof(nvram) != 'undefined') && (typeof(nvram[name]) != 'undefined')) ? nvram[name] : def;
2334 function nothing()
2338 // -----------------------------------------------------------------------------
2340 function show_notice1(s)
2342 // ---- !!TB - USB Support: multi-line notices
2343         if (s.length) document.write('<div id="notice1">' + s.replace(/\n/g, '<br>') + '</div><br style="clear:both">');
2346 // -----------------------------------------------------------------------------
2348 function myName()
2350         var name, i;
2352         name = document.location.pathname;
2353         name = name.replace(/\\/g, '/');        // IE local testing
2354         if ((i = name.lastIndexOf('/')) != -1) name = name.substring(i + 1, name.length);
2355         if (name == '') name = 'status-overview.asp';
2356         return name;
2359 function navi()
2361         var menu = [
2362                 ['Status',                              'status', 0, [
2363                         ['Overview',            'overview.asp'],
2364                         ['Device List',         'devices.asp'],
2365                         ['Web Usage',           'webmon.asp'],
2366                         ['Logs',                        'log.asp'] ] ],
2367                 ['Bandwidth',                   'bwm', 0, [
2368                         ['Real-Time',           'realtime.asp'],
2369                         ['Last 24 Hours',       '24.asp'],
2370 /* REMOVE-BEGIN
2371                         ['Client Monitor',      'client.asp'],
2372 REMOVE-END */
2373                         ['Daily',                       'daily.asp'],
2374                         ['Weekly',                      'weekly.asp'],
2375                         ['Monthly',                     'monthly.asp'] ] ],
2376                 ['IP Traffic',                  'ipt', 0, [
2377                         ['Real-Time',           'realtime.asp'],
2378                         ['Last 24 Hours',       '24.asp'],
2379                         ['Transfer Rates',      'details.asp'],
2380                         ['Daily',                       'daily.asp'],
2381                         ['Monthly',                     'monthly.asp'] ] ],
2382                 ['Tools',                               'tools', 0, [
2383                         ['Ping',                        'ping.asp'],
2384                         ['Trace',                       'trace.asp'],
2385                         ['System',                      'shell.asp'],
2386                         ['Wireless Survey',     'survey.asp'],
2387                         ['WOL',                         'wol.asp'] ] ],
2388                 null,
2389                 ['Basic',                               'basic', 0, [
2390                         ['Network',                     'network.asp'],
2391 /* IPV6-BEGIN */
2392                         ['IPv6',                        'ipv6.asp'],
2393 /* IPV6-END */
2394                         ['Identification',      'ident.asp'],
2395                         ['Time',                        'time.asp'],
2396                         ['DDNS',                        'ddns.asp'],
2397                         ['DHCP/ARP/BW',         'static.asp'],
2398                         ['Wireless Filter',     'wfilter.asp'] ] ],
2399                 ['Advanced',                    'advanced', 0, [
2400                         ['Conntrack/Netfilter', 'ctnf.asp'],
2401                         ['DHCP/DNS',            'dhcpdns.asp'],
2402                         ['Firewall',            'firewall.asp'],
2403                         ['MAC Address',         'mac.asp'],
2404                         ['Miscellaneous',       'misc.asp'],
2405                         ['Routing',                     'routing.asp'],
2406                         ['Wireless',            'wireless.asp']
2407 /* VLAN-BEGIN */
2408                         ,['VLAN',                       'vlan.asp'],
2409                         ['LAN Access',                  'access.asp'],
2410                         ['Virtual Wireless',            'wlanvifs.asp']
2411 /* VLAN-END */
2412                          ] ],
2413                 ['Port Forwarding',     'forward', 0, [
2414                         ['Basic',                       'basic.asp'],
2415 /* IPV6-BEGIN */
2416                         ['Basic IPv6',          'basic-ipv6.asp'],
2417 /* IPV6-END */
2418                         ['DMZ',                 'dmz.asp'],
2419                         ['Triggered',           'triggered.asp'],
2420                         ['UPnP/NAT-PMP',        'upnp.asp'] ] ],
2421                 ['QoS',                                 'qos', 0, [
2422                         ['Basic Settings',      'settings.asp'],
2423                         ['Classification',      'classify.asp'],
2424                         ['View Graphs',         'graphs.asp'],
2425                         ['View Details',        'detailed.asp'],
2426                         ['Transfer Rates',      'ctrate.asp'],
2427                         ['B/W Limiter',         'qoslimit.asp'] ] ],
2428                 ['Access Restriction',          'restrict.asp'],
2430 /* NOCAT-BEGIN */
2431                 ['Captive Portal',              'splashd.asp'],
2432 /* NOCAT-END */
2434 /* REMOVE-BEGIN
2435                 ['Scripts',                             'sc', 0, [
2436                         ['Startup',                     'startup.asp'],
2437                         ['Shutdown',            'shutdown.asp'],
2438                         ['Firewall',            'firewall.asp'],
2439                         ['WAN Up',                      'wanup.asp']
2440                         ] ],
2441 REMOVE-END */
2442 /* USB-BEGIN */
2443 // ---- !!TB - USB, FTP, Samba, Media Server
2444                 ['USB and NAS',                 'nas', 0, [
2445                         ['USB Support',         'usb.asp']
2446 /* FTP-BEGIN */
2447                         ,['FTP Server',         'ftp.asp']
2448 /* FTP-END */
2449 /* SAMBA-BEGIN */
2450                         ,['File Sharing',       'samba.asp']
2451 /* SAMBA-END */
2452 /* MEDIA-SRV-BEGIN */
2453                         ,['Media Server',       'media.asp']
2454 /* MEDIA-SRV-END */
2455                         ] ],
2456 /* USB-END */
2457 /* VPN-BEGIN */
2458                 ['VPN Tunneling',               'vpn', 0, [
2459 /* OPENVPN-BEGIN */
2460                         ['OpenVPN Server',      'server.asp'],
2461                         ['OpenVPN Client',      'client.asp'],
2462 /* OPENVPN-END */
2463 /* PPTPD-BEGIN */
2464                         ['PPTP Server',         'pptp-server.asp'],
2465                         ['PPTP Online',         'pptp-online.asp'],
2466 /* PPTPD-END */
2467 /* USERPPTP-BEGIN */
2468                         ['PPTP Client',         'pptp.asp']
2469 /* USERPPTP-END */
2470                 ] ],
2471 /* VPN-END */
2472                 null,
2473                 ['Administration',              'admin', 0, [
2474                         ['Admin Access',        'access.asp'],
2475                         ['Bandwidth Monitoring','bwm.asp'],
2476                         ['IP Traffic Monitoring','iptraffic.asp'],
2477                         ['Buttons/LED', 'buttons.asp'],
2478 /* CIFS-BEGIN */
2479                         ['CIFS Client',         'cifs.asp'],
2480 /* CIFS-END */
2481                         ['Configuration',       'config.asp'],
2482                         ['Debugging',           'debug.asp'],
2483 /* JFFS2-BEGIN */
2484                         ['JFFS',                        'jffs2.asp'],
2485 /* JFFS2-END */
2486                         ['Logging',                     'log.asp'],
2487                         ['Scheduler',           'sched.asp'],
2488                         ['Scripts',                     'scripts.asp'],
2489 /* SNMP-BEGIN */
2490                         ['SNMP',                'snmp.asp'],
2491 /* SNMP-END */
2492                         ['Upgrade',                     'upgrade.asp'] ] ],
2493                 null,
2494                 ['About',                               'about.asp'],
2495                 ['Reboot...',                   'javascript:reboot()'],
2496                 ['Shutdown...',                 'javascript:shutdown()'],
2497                 ['Logout',                              'javascript:logout()']
2498         ];
2499         var name, base;
2500         var i, j;
2501         var buf = [];
2502         var sm;
2503         var a, b, c;
2504         var on1;
2505         var cexp = get_config('web_mx', '').toLowerCase();
2507         name = myName();
2508         if (name == 'restrict-edit.asp') name = 'restrict.asp';
2509         if ((i = name.indexOf('-')) != -1) {
2510                 base = name.substring(0, i);
2511                 name = name.substring(i + 1, name.length);
2512         }
2513         else base = '';
2515         for (i = 0; i < menu.length; ++i) {
2516                 var m = menu[i];
2517                 if (!m) {
2518                         buf.push("<br>");
2519                         continue;
2520                 }
2521                 if (m.length == 2) {
2522                         buf.push('<a href="' + m[1] + '" class="indent1' + (((base == '') && (name == m[1])) ? ' active' : '') + '">' + m[0] + '</a>');
2523                 }
2524                 else {
2525                         if (base == m[1]) {
2526                                 b = name;
2527                         }
2528                         else {
2529                                 a = cookie.get('menu_' + m[1]);
2530                                 b = m[3][0][1];
2531                                 for (j = 0; j < m[3].length; ++j) {
2532                                         if (m[3][j][1] == a) {
2533                                                 b = a;
2534                                                 break;
2535                                         }
2536                                 }
2537                         }
2538                         a = m[1] + '-' + b;
2539                         if (a == 'status-overview.asp') a = '/';
2540                         on1 = (base == m[1]);
2541                         buf.push('<a href="' + a + '" class="indent1' + (on1 ? ' active' : '') + '">' + m[0] + '</a>');
2542                         if ((!on1) && (m[2] == 0) && (cexp.indexOf(m[1]) == -1)) continue;
2544                         for (j = 0; j < m[3].length; ++j) {
2545                                 sm = m[3][j];
2546                                 a = m[1] + '-' + sm[1];
2547                                 if (a == 'status-overview.asp') a = '/';
2548                                 buf.push('<a href="' + a + '" class="indent2' + (((on1) && (name == sm[1])) ? ' active' : '') + '">' + sm[0] + '</a>');
2549                         }
2550                 }
2551         }
2552         document.write(buf.join(''));
2554         if (base.length) {
2555                 if ((base == 'qos') && (name == 'detailed.asp')) name = 'view.asp';
2556                 cookie.set('menu_' + base, name);
2557         }
2560 function createFieldTable(flags, desc)
2562         var common;
2563         var i, n;
2564         var name;
2565         var id;
2566         var fields;
2567         var f;
2568         var a;
2569         var buf = [];
2570         var buf2;
2571         var id1;
2572         var tr;
2574         if ((flags.indexOf('noopen') == -1)) buf.push('<table class="fields">');
2575         for (desci = 0; desci < desc.length; ++desci) {
2576                 var v = desc[desci];
2578                 if (!v) {
2579                         buf.push('<tr><td colspan=2 class="spacer">&nbsp;</td></tr>');
2580                         continue;
2581                 }
2583                 if (v.ignore) continue;
2585                 buf.push('<tr');
2586                 if (v.rid) buf.push(' id="' + v.rid + '"');
2587                 if (v.hidden) buf.push(' style="display:none"');
2588                 buf.push('>');
2590                 if (v.text) {
2591                         if (v.title) {
2592                                 buf.push('<td class="title indent' + (v.indent || 1) + '">' + v.title + '</td><td class="content">' + v.text + '</td></tr>');
2593                         }
2594                         else {
2595                                 buf.push('<td colspan=2>' + v.text + '</td></tr>');
2596                         }
2597                         continue;
2598                 }
2600                 id1 = '';
2601                 buf2 = [];
2602                 buf2.push('<td class="content">');
2604                 if (v.multi) fields = v.multi;
2605                         else fields = [v];
2607                 for (n = 0; n < fields.length; ++n) {
2608                         f = fields[n];
2609                         if (f.prefix) buf2.push(f.prefix);
2611                         if ((f.type == 'radio') && (!f.id)) id = '_' + f.name + '_' + i;
2612                                 else id = (f.id ? f.id : ('_' + f.name));
2614                         if (id1 == '') id1 = id;
2616                         common = ' onchange="verifyFields(this, 1)" id="' + id + '"';
2617                         if (f.attrib) common += ' ' + f.attrib;
2618                         name = f.name ? (' name="' + f.name + '"') : '';
2620                         switch (f.type) {
2621                         case 'checkbox':
2622                                 buf2.push('<input type="checkbox"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2623                                 break;
2624                         case 'radio':
2625                                 buf2.push('<input type="radio"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2626                                 break;
2627                         case 'password':
2628                                 if (f.peekaboo) {
2629                                         switch (get_config('web_pb', '1')) {
2630                                         case '0':
2631                                                 f.type = 'text';
2632                                         case '2':
2633                                                 f.peekaboo = 0;
2634                                                 break;
2635                                         }
2636                                 }
2637                                 if (f.type == 'password') {
2638                                         common += ' autocomplete="off"';
2639                                         if (f.peekaboo) common += ' onfocus=\'peekaboo("' + id + '",1)\'';
2640                                 }
2641                                 // drop
2642                         case 'text':
2643                                 buf2.push('<input type="' + f.type + '"' + name + ' value="' + escapeHTML(UT(f.value)) + '" maxlength=' + f.maxlen + (f.size ? (' size=' + f.size) : '') + common + '>');
2644                                 break;
2645                         case 'select':
2646                                 buf2.push('<select' + name + common + '>');
2647                                 for (i = 0; i < f.options.length; ++i) {
2648                                         a = f.options[i];
2649                                         if (a.length == 1) a.push(a[0]);
2650                                         buf2.push('<option value="' + a[0] + '"' + ((a[0] == f.value) ? ' selected' : '') + '>' + a[1] + '</option>');
2651                                 }
2652                                 buf2.push('</select>');
2653                                 break;
2654                         case 'textarea':
2655                                 buf2.push('<textarea' + name + common + (f.wrap ? (' wrap=' + f.wrap) : '') + '>' + escapeHTML(UT(f.value)) + '</textarea>');
2656                                 break;
2657                         default:
2658                                 if (f.custom) buf2.push(f.custom);
2659                                 break;
2660                         }
2661                         if (f.suffix) buf2.push(f.suffix);
2662                 }
2663                 buf2.push('</td>');
2665                 buf.push('<td class="title indent' + (v.indent ? v.indent : 1) + '">');
2666                 if (id1 != '') buf.push('<label for="' + id + '">' + v.title + '</label></td>');
2667                         else buf.push(+ v.title + '</td>');
2669                 buf.push(buf2.join(''));
2670                 buf.push('</tr>');
2671         }
2672         if ((!flags) || (flags.indexOf('noclose') == -1)) buf.push('</table>');
2673         document.write(buf.join(''));
2676 function peekaboo(id, show)
2678         try {
2679                 var o = document.createElement('INPUT');
2680                 var e = E(id);
2681                 var name = e.name;
2682                 o.type = show ? 'text' : 'password';
2683                 o.value = e.value;
2684                 o.size = e.size;
2685                 o.maxLength = e.maxLength;
2686                 o.autocomplete = e.autocomplete;
2687                 o.title = e.title;
2688                 o.disabled = e.disabled;
2689                 o.onchange = e.onchange;
2690                 e.parentNode.replaceChild(o, e);
2691                 e = null;
2692                 o.id = id;
2693                 o.name = name;
2695                 if (show) {
2696                         o.onblur = function(ev) { setTimeout('peekaboo("' + this.id + '", 0)', 0) };
2697                         setTimeout('try { E("' + id + '").focus() } catch (ex) { }', 0)
2698                 }
2699                 else {
2700                         o.onfocus = function(ev) { peekaboo(this.id, 1); };
2701                 }
2702         }
2703         catch (ex) {
2704 //              alert(ex);
2705         }
2707 /* REMOVE-BEGIN
2708 notes:
2709  - e.type= doesn't work in IE, ok in FF
2710  - may mess keyboard tabing (bad: IE; ok: FF, Opera)... setTimeout() delay seems to help a little.
2711 REMOVE-END */
2714 // -----------------------------------------------------------------------------
2716 function reloadPage()
2718         document.location.reload(1);
2721 function reboot()
2723         if (confirm("Reboot?")) form.submitHidden('tomato.cgi', { _reboot: 1, _commit: 0, _nvset: 0 });
2726 function shutdown()
2728         if (confirm("Shutdown?")) form.submitHidden('shutdown.cgi', { });
2731 function logout()
2733         form.submitHidden('logout.asp', { });
2736 // -----------------------------------------------------------------------------
2740 // ---- debug
2742 function isLocal()
2744         return location.href.search('file://') == 0;
2747 function console(s)