Merge branch 'tomato-ND-usbmod-vpn' into tomato-ND-USBmod
[tomato.git] / release / src / router / www / tomato.js
blob13afa36f13ac2698253e7e398aa97f23b681bbe1
1 /*
2         Tomato GUI
3         Copyright (C) 2006-2008 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         },
288         
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         },
337         
338         show: function(e) {
339                 if ((e = E(e)) == null) return;
340                 if (!e._error_msg) return;
341                 elem.addClass(e, 'error-focused');
342                 e.focus();
343                 alert(e._error_msg);
344                 elem.removeClass(e, 'error-focused');
345         },
347         ok: function(e) {
348                 if ((e = E(e)) == null) return 0;
349         return !e._error_msg;
350         }
353 // -----------------------------------------------------------------------------
355 function _v_range(e, quiet, min, max, name)
357         var v;
359         if ((e = E(e)) == null) return 0;
360         v = e.value * 1;
361         if ((isNaN(v)) || (v < min) || (v > max)) {
362                 ferror.set(e, 'Invalid ' + name + '. Valid range: ' + min + '-' + max, quiet);
363                 return 0;
364         }
365         e.value = v;
366         ferror.clear(e);
367         return 1;
370 function v_range(e, quiet, min, max)
372         return _v_range(e, quiet, min, max, 'number');
375 function v_port(e, quiet)
377         return _v_range(e, quiet, 1, 0xFFFF, 'port');
380 function v_octet(e, quiet)
382         return _v_range(e, quiet, 1, 254, 'address');
385 function v_mins(e, quiet, min, max)
387         var v, m;
389         if ((e = E(e)) == null) return 0;
390         if (e.value.match(/^\s*(.+?)([mhd])?\s*$/)) {
391                 m = 1;
392                 if (RegExp.$2 == 'h') m = 60;
393                         else if (RegExp.$2 == 'd') m = 60 * 24;
394                 v = Math.round(RegExp.$1 * m);
395                 if (!isNaN(v)) {
396                         e.value = v;
397                         return _v_range(e, quiet, min, max, 'minutes');
398                 }
399         }
400         ferror.set(e, 'Invalid number of minutes.', quiet);
401         return 0;
404 function v_macip(e, quiet, bok, ipp)
406         var s, a, b, c, d, i;
408         if ((e = E(e)) == null) return 0;
409         s = e.value.replace(/\s+/g, '');
411         if ((a = fixMAC(s)) != null) {
412                 if (isMAC0(a)) {
413                         if (bok) {
414                                 e.value = '';
415                         }
416                         else {
417                                 ferror.set(e, 'Invalid MAC or IP address');
418                                 return false;
419                         }
420                 }
421         else e.value = a;
422                 ferror.clear(e);
423                 return true;
424         }
426         a = s.split('-');
427         if (a.length > 2) {
428                 ferror.set(e, 'Invalid IP address range', quiet);
429                 return false;
430         }
431         c = 0;
432         for (i = 0; i < a.length; ++i) {
433                 b = a[i];
434                 if (b.match(/^\d+$/)) b = ipp + b;
436                 b = fixIP(b);
437                 if (!b) {
438                         ferror.set(e, 'Invalid IP address', quiet);
439                         return false;
440                 }
442                 if (b.indexOf(ipp) != 0) {
443                         ferror.set(e, 'IP address outside of LAN', quiet);
444                         return false;
445                 }
447                 d = (b.split('.'))[3];
448                 if (d <= c) {
449                         ferror.set(e, 'Invalid IP address range', quiet);
450                         return false;
451                 }
453                 a[i] = c = d;
454         }
455         e.value = ipp + a.join('-');
456         return true;
459 function fixIP(ip, x)
461         var a, n, i;
463         a = ip.split('.');
464         if (a.length != 4) return null;
465         for (i = 0; i < 4; ++i) {
466                 n = a[i] * 1;
467                 if ((isNaN(n)) || (n < 0) || (n > 255)) return null;
468                 a[i] = n;
469         }
470         if ((x) && ((a[3] == 0) || (a[3] == 255))) return null;
471         return a.join('.');
474 function v_ip(e, quiet, x)
476         var ip;
478         if ((e = E(e)) == null) return 0;
479         ip = fixIP(e.value, x);
480         if (!ip) {
481                 ferror.set(e, 'Invalid IP address', quiet);
482                 return false;
483         }
484         e.value = ip;
485         ferror.clear(e);
486         return true;
489 function v_ipz(e, quiet)
491         if ((e = E(e)) == null) return 0;
492         e = E(e);
493         if (e.value == '') e.value = '0.0.0.0';
494         return v_ip(e, quiet);
497 function aton(ip)
499         var o, x, i;
501         // ---- this is goofy because << mangles numbers as signed
502         o = ip.split('.');
503         x = '';
504         for (i = 0; i < 4; ++i) x += (o[i] * 1).hex(2);
505         return parseInt(x, 16);
508 function ntoa(ip)
510         return ((ip >> 24) & 255) + '.' + ((ip >> 16) & 255) + '.' + ((ip >> 8) & 255) + '.' + (ip & 255);
513 // ---- 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
514 function v_iptip(e, quiet)
516         var ip, ma, x, y, z;
518         if ((e = E(e)) == null) return 0;
520         ip = e.value;
521         ma = '';
522         if (ip.match(/^(.*)-(.*)$/)) {
523                 ip = fixIP(RegExp.$1);
524                 x = fixIP(RegExp.$2);
525                 if ((ip == null) || (x == null)) {
526                         ferror.set(e, 'Invalid IP address range', quiet);
527                         return 0;
528                 }
529                 ferror.clear(e);
530                 y = aton(ip);
531                 z = aton(x);
532                 if (y == z) {
533                         e.value = ip;
534                 }
535                 else if (z < y) {
536                         e.value = x + '-' + ip;
537                 }
538                 else {
539                         e.value = ip + '-' + x;
540                 }
541                 return 1;
542         }
543         if (ip.match(/^(.*)\/(.*)$/)) {
544                 ip = RegExp.$1;
545                 ma = RegExp.$2;
546                 x = ma * 1;
547                 if (!isNaN(x)) {
548                         if ((x < 0) || (x > 32)) {
549                                 ferror.set(e, 'Invalid netmask', quiet);
550                                 return 0;
551                         }
552                         ma = x;
553                 }
554                 else {
555                         ma = fixIP(ma);
556                         if ((ma == null) || (!_v_netmask(ma))) {
557                                 ferror.set(e, 'Invalid netmask', quiet);
558                                 return 0;
559                         }
560                 }
561         }
562         ip = fixIP(ip);
563         if (!ip) {
564                 ferror.set(e, 'Invalid IP address', quiet);
565                 return 0;
566         }
567         e.value = ip + ((ma != '') ? ('/' + ma) : '');
568         ferror.clear(e);
569         return 1;
572 function fixPort(p, def)
574         if (def == null) def = -1;
575         if (p == null) return def;
576         p *= 1;
577         if ((isNaN(p)) || (p < 1) || (p > 65535)) return def;
578         return p;
581 function _v_portrange(e, quiet, v)
583         var x, y;
585         if (v.match(/^(.*)[-:](.*)$/)) {
586                 x = fixPort(RegExp.$1, -1);
587                 y = fixPort(RegExp.$2, -1);
588                 if ((x == -1) || (y == -1)) {
589                         ferror.set(e, 'Invalid port range: ' + v, quiet);
590                         return null;
591                 }
592                 if (x > y) {
593                         v = x;
594                         x = y;
595                         y = v;
596                 }
597                 ferror.clear(e);
598                 if (x == y) return x;
599                 return x + '-' + y;
600         }
602         v = fixPort(v, -1);
603         if (v == -1) {
604                 ferror.set(e, 'Invalid port', quiet);
605                 return null;
606         }
608         ferror.clear(e);
609         return v;
612 function v_portrange(e, quiet)
614         var v;
616         if ((e = E(e)) == null) return 0;
617         v = _v_portrange(e, quiet, e.value);
618         if (v == null) return 0;
619         e.value = v;
620         return 1;
623 function v_iptport(e, quiet)
625         var a, i, v;
627         if ((e = E(e)) == null) return 0;
629         a = e.value.split(/,/);
630         for (i = 0; i < MIN(a.length, 10); ++i) {
631                 v = _v_portrange(e, quiet, a[i]);
632                 if (v == null) return 0;
633                 a[i] = v;
634         }
635         if (a.length == 0) {
636                 ferror.set(e, 'Expecting a list of ports or port range.', quiet);
637                 return 0;
638         }
639         e.value = a.join(',');
640         ferror.clear(e);
641         return 1;
644 function _v_netmask(mask)
646         var v = aton(mask) ^ 0xFFFFFFFF;
647         return (((v + 1) & v) == 0);
650 function v_netmask(e, quiet)
652         var n, b;
654         if ((e = E(e)) == null) return 0;
655         n = fixIP(e.value);
656         if (n) {
657                 if (_v_netmask(n)) {
658                         e.value = n;
659                         ferror.clear(e);
660                         return 1;
661                 }
662         }
663         else if (e.value.match(/^\s*\/\s*(\d+)\s*$/)) {
664                 b = RegExp.$1 * 1;
665                 if ((b >= 1) && (b <= 32)) {
666                         if (b == 32) n = 0xFFFFFFFF;    // js quirk
667                                 else n = (0xFFFFFFFF >>> b) ^ 0xFFFFFFFF;
668                         e.value = (n >>> 24) + '.' + ((n >>> 16) & 0xFF) + '.' + ((n >>> 8) & 0xFF) + '.' + (n & 0xFF);
669                         ferror.clear(e);
670                         return 1;
671                 }
672         }
673         ferror.set(e, 'Invalid netmask', quiet);
674         return 0;
677 function fixMAC(mac)
679         var t, i;
681         mac = mac.replace(/\s+/g, '').toUpperCase();
682         if (mac.length == 0) {
683                 mac = [0,0,0,0,0,0];
684         }
685         else if (mac.length == 12) {
686                 mac = mac.match(/../g);
687         }
688         else {
689                 mac = mac.split(/[:\-]/);
690                 if (mac.length != 6) return null;
691         }
692         for (i = 0; i < 6; ++i) {
693                 t = '' + mac[i];
694                 if (t.search(/^[0-9A-F]+$/) == -1) return null;
695                 if ((t = parseInt(t, 16)) > 255) return null;
696                 mac[i] = t.hex(2);
697         }
698         return mac.join(':');
701 function v_mac(e, quiet)
703         var mac;
705         if ((e = E(e)) == null) return 0;
706         mac = fixMAC(e.value);
707         if ((!mac) || (isMAC0(mac))) {
708                 ferror.set(e, 'Invalid MAC address', quiet);
709                 return 0;
710         }
711         e.value = mac;
712         ferror.clear(e);
713         return 1;
716 function v_macz(e, quiet)
718         var mac;
720         if ((e = E(e)) == null) return 0;
721         mac = fixMAC(e.value);
722         if (!mac) {
723                 ferror.set(e, 'Invalid MAC address', quiet);
724                 return false;
725         }
726         e.value = mac;
727         ferror.clear(e);
728         return true;
731 function v_length(e, quiet, min, max)
733         var s, n;
735         if ((e = E(e)) == null) return 0;
736         s = e.value.trim();
737         n = s.length;
738         if (min == undefined) min = 1;
739         if (n < min) {
740                 ferror.set(e, 'Invalid length. Please enter at least ' + min + ' character' + (min == 1 ? '.' : 's.'), quiet);
741                 return 0;
742         }
743         max = max || e.maxlength;
744     if (n > max) {
745                 ferror.set(e, 'Invalid length. Please reduce the length to ' + max + ' characters or less.', quiet);
746                 return 0;
747         }
748         e.value = s;
749         ferror.clear(e);
750         return 1;
753 function v_domain(e, quiet)
755         var s;
757         if ((e = E(e)) == null) return 0;
758         s = e.value.trim().replace(/\s+/g, ' ');
759         if ((s.length > 0) && (s.search(/^[.a-zA-Z0-9_\- ]+$/) == -1)) {
760                 ferror.set(e, "Invalid name. Only characters \"A-Z 0-9 . - _\" are allowed.", quiet);
761                 return 0;
762         }
763         e.value = s;
764         ferror.clear(e);
765         return 1;
768 function isMAC0(mac)
770         return (mac == '00:00:00:00:00:00');
773 // -----------------------------------------------------------------------------
775 function cmpIP(a, b)
777         if ((a = fixIP(a)) == null) a = '255.255.255.255';
778         if ((b = fixIP(b)) == null) b = '255.255.255.255';
779         return aton(a) - aton(b);
782 function cmpText(a, b)
784         if (a == '') a = '\xff';
785         if (b == '') b = '\xff';
786         return (a < b) ? -1 : ((a > b) ? 1 : 0);
789 function cmpInt(a, b)
791         a = parseInt(a, 10);
792         b = parseInt(b, 10);
793         return ((isNaN(a)) ? -0x7FFFFFFF : a) - ((isNaN(b)) ? -0x7FFFFFFF : b);
796 function cmpDate(a, b)
798         return b.getTime() - a.getTime();
801 // -----------------------------------------------------------------------------
803 // ---- todo: cleanup this mess
805 function TGO(e)
807         return elem.parentElem(e, 'TABLE').gridObj;
810 function tgHideIcons()
812         var e;
813         while ((e = document.getElementById('tg-row-panel')) != null) e.parentNode.removeChild(e);
816 // ---- options = sort, move, delete
817 function TomatoGrid(tb, options, maxAdd, editorFields)
819         this.init(tb, options, maxAdd, editorFields);
820         return this;
823 TomatoGrid.prototype = {
824         init: function(tb, options, maxAdd, editorFields) {
825                 if (tb) {
826                         this.tb = E(tb);
827                         this.tb.gridObj = this;
828                 }
829                 else {
830                         this.tb = null;
831                 }
832                 if (!options) options = '';
833                 this.header = null;
834                 this.footer = null;
835                 this.editor = null;
836                 this.canSort = options.indexOf('sort') != -1;
837                 this.canMove = options.indexOf('move') != -1;
838                 this.maxAdd = maxAdd || 100;
839                 this.canEdit = (editorFields != null);
840                 this.canDelete = this.canEdit || (options.indexOf('delete') != -1);
841                 this.editorFields = editorFields;
842                 this.sortColumn = -1;
843                 this.sortAscending = true;
844         },
846         _insert: function(at, cells, escCells) {
847                 var tr, td, c;
848                 var i, t;
850                 tr = this.tb.insertRow(at);
851                 for (i = 0; i < cells.length; ++i) {
852                         c = cells[i];
853                         if (typeof(c) == 'string') {
854                                 td = tr.insertCell(i);
855                                 td.className = 'co' + (i + 1);
856                                 if (escCells) td.appendChild(document.createTextNode(c));
857                                         else td.innerHTML = c;
858                         }
859                         else {
860                                 tr.appendChild(c);
861                         }
862                 }
863                 return tr;
864         },
866         // ---- header
868         headerClick: function(cell) {
869                 if (this.canSort) {
870                         this.sort(cell.cellN);
871                 }
872         },
874         headerSet: function(cells, escCells) {
875                 var e, i;
877                 elem.remove(this.header);
878                 this.header = e = this._insert(0, cells, escCells);
879                 e.className = 'header';
881                 for (i = 0; i < e.cells.length; ++i) {          
882                         e.cells[i].cellN = i;   // cellIndex broken in Safari
883                         e.cells[i].onclick = function() { return TGO(this).headerClick(this); };
884                 }
885                 return e;
886         },
888         // ---- footer
890         footerClick: function(cell) {
891         },
893         footerSet: function(cells, escCells) {
894                 var e, i;
896                 elem.remove(this.footer);
897                 this.footer = e = this._insert(-1, cells, escCells);
898                 e.className = 'footer';
899                 for (i = 0; i < e.cells.length; ++i) {
900                         e.cells[i].cellN = i;
901                         e.cells[i].onclick = function() { TGO(this).footerClick(this) };
902                 }
903                 return e;
904         },
906         // ----
908         rpUp: function(e) {
909                 var i;
911                 e = PR(e);
912                 TGO(e).moving = null;
913                 i = e.previousSibling;
914                 if (i == this.header) return;
915                 e.parentNode.removeChild(e);
916                 i.parentNode.insertBefore(e, i);
918                 this.recolor();
919                 this.rpHide();
920         },
922         rpDn: function(e) {
923                 var i;
925                 e = PR(e);
926                 TGO(e).moving = null;
927                 i = e.nextSibling;
928                 if (i == this.footer) return;
929                 e.parentNode.removeChild(e);
930                 i.parentNode.insertBefore(e, i.nextSibling);
932                 this.recolor();
933                 this.rpHide();
934         },
936         rpMo: function(img, e) {
937                 var me;
939                 e = PR(e);
940                 me = TGO(e);
941                 if (me.moving == e) {
942                         me.moving = null;
943                         this.rpHide();
944                         return;
945                 }
946                 me.moving = e;
947                 img.style.border = "1px dotted red";
948         },
949         
950         rpDel: function(e) {
951                 e = PR(e);
952                 TGO(e).moving = null;
953                 e.parentNode.removeChild(e);
954                 this.recolor();
955                 this.rpHide();
956         },
958         rpMouIn: function(evt) {
959                 var e, x, ofs, me, s, n;
961                 if ((evt = checkEvent(evt)) == null) return;
963                 me = TGO(evt.target);
964                 if (me.isEditing()) return;
965                 if (me.moving) return;
967                 me.rpHide();
968                 e = document.createElement('div');
969                 e.tgo = me;
970                 e.ref = evt.target;
971                 e.setAttribute('id', 'tg-row-panel');
973                 n = 0;
974                 s = '';
975                 if (me.canMove) {
976                         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">';
977                         n += 3;
978                 }
979                 if (me.canDelete) {
980                         s += '<img src="rpx.gif" onclick="this.parentNode.tgo.rpDel(this.parentNode.ref)" title="Delete">';
981                         ++n;
982                 }
983                 x = PR(evt.target);
984                 x = x.cells[x.cells.length - 1];
985                 ofs = elem.getOffset(x);
986                 n *= 18;
987                 e.style.left = (ofs.x + x.offsetWidth - n) + 'px';
988                 e.style.top = ofs.y + 'px';
989                 e.style.width = n + 'px';
990                 e.innerHTML = s;
992                 document.body.appendChild(e);
993         },
994         
995         rpHide: tgHideIcons,
997         // ----
999         onClick: function(cell) {
1000                 if (this.canEdit) {
1001                         if (this.moving) {
1002                                 var p = this.moving.parentNode;
1003                                 var q = PR(cell);
1004                                 if (this.moving != q) {
1005                                         var v = this.moving.rowIndex > q.rowIndex;
1006                                         p.removeChild(this.moving);
1007                                         if (v) p.insertBefore(this.moving, q);
1008                                                 else p.insertBefore(this.moving, q.nextSibling);
1009                                         this.recolor();
1010                                 }
1011                                 this.moving = null;
1012                                 this.rpHide();
1013                                 return;
1014                         }
1015                         this.edit(cell);
1016                 }
1017         },
1019         insert: function(at, data, cells, escCells) {
1020                 var e, i;
1022                 if ((this.footer) && (at == -1)) at = this.footer.rowIndex;
1023                 e = this._insert(at, cells, escCells);
1024                 e.className = (e.rowIndex & 1) ? 'even' : 'odd';
1026                 for (i = 0; i < e.cells.length; ++i) {
1027                         e.cells[i].onclick = function() { return TGO(this).onClick(this); };
1028                 }
1030                 e._data = data;
1031                 e.getRowData = function() { return this._data; }
1032                 e.setRowData = function(data) { this._data = data; }
1034                 if ((this.canMove) || (this.canEdit) || (this.canDelete)) {
1035                         e.onmouseover = this.rpMouIn;
1036 // ----                 e.onmouseout = this.rpMouOut;
1037                         if (this.canEdit) e.title = 'Click to edit';
1038                 }
1040                 return e;
1041         },
1043         // ----
1045         insertData: function(at, data) {
1046                 return this.insert(at, data, this.dataToView(data), false);
1047         },
1049         dataToView: function(data) {
1050                 var v = [];
1051                 for (var i = 0; i < data.length; ++i)
1052                         v.push(escapeHTML('' + data[i]));
1053                 return v;
1054         },
1056         dataToFieldValues: function(data) {
1057                 return data;
1058         },
1060         fieldValuesToData: function(row) {
1061                 var e, i, data;
1063                 data = [];
1064                 e = fields.getAll(row);
1065                 for (i = 0; i < e.length; ++i) data.push(e[i].value);
1066                 return data;
1067         },
1069         // ----
1071         edit: function(cell) {
1072                 var sr, er, e, c;
1074                 if (this.isEditing()) return;
1076                 sr = PR(cell);
1077                 sr.style.display = 'none';
1078                 elem.removeClass(sr, 'hover');
1079                 this.source = sr;
1081                 er = this.createEditor('edit', sr.rowIndex, sr);
1082         er.className = 'editor';
1083                 this.editor = er;
1085                 c = er.cells[cell.cellIndex || 0];
1086                 e = c.getElementsByTagName('input');
1087                 if ((e) && (e.length > 0)) {
1088                         try {   // IE quirk
1089                                 e[0].focus();
1090                         }
1091                         catch (ex) {
1092                         }
1093                 }
1095                 this.controls = this.createControls('edit', sr.rowIndex);
1097                 this.disableNewEditor(true);
1098                 this.rpHide();
1099                 this.verifyFields(this.editor, true);
1100         },
1102         createEditor: function(which, rowIndex, source) {
1103                 var values;
1105                 if (which == 'edit') values = this.dataToFieldValues(source.getRowData());
1107                 var row = this.tb.insertRow(rowIndex);
1108                 row.className = 'editor';
1110                 var common = ' onkeypress="return TGO(this).onKey(\'' + which + '\', event)" onchange="TGO(this).onChange(\'' + which + '\', this)"';
1112                 var vi = 0;
1113                 for (var i = 0; i < this.editorFields.length; ++i) {
1114                         var s = '';
1115                 var ef = this.editorFields[i].multi;
1116                         if (!ef) ef = [this.editorFields[i]];
1118                         for (var j = 0; j < ef.length; ++j) {
1119                                 var f = ef[j];
1121                                 if (f.prefix) s += f.prefix;
1122                                 var attrib = ' class="fi' + (vi + 1) + '" ' + (f.attrib || '');
1123                                 switch (f.type) {
1124                                 case 'text':
1125                                         s += '<input type="text" maxlength=' + f.maxlen + common + attrib;
1126                                         if (which == 'edit') s += ' value="' + escapeHTML('' + values[vi]) + '">';
1127                                                 else s += '>';
1128                                         break;
1129                                 case 'select':
1130                                         s += '<select' + common + attrib + '>';
1131                                         for (var k = 0; k < f.options.length; ++k) {
1132                                                 a = f.options[k];
1133                                                 if (which == 'edit') {
1134                                                         s += '<option value="' + a[0] + '"' + ((a[0] == values[vi]) ? ' selected>' : '>') + a[1] + '</option>';
1135                                                 }
1136                                                 else {
1137                                                         s += '<option value="' + a[0] + '">' + a[1] + '</option>';
1138                                                 }
1139                                         }
1140                                         s += '</select>';
1141                                         break;
1142                                 case 'checkbox':
1143                                         s += '<input type="checkbox"' + common + attrib;
1144                                         if ((which == 'edit') && (values[vi])) s += ' checked';
1145                                         s += '>';
1146                                         break;
1147                                 default:
1148                                         s += f.custom.replace(/\$which\$/g, which);
1149                                 }
1150                                 if (f.suffix) s += f.suffix;
1152                                 ++vi;
1153                         }
1154                         var c = row.insertCell(i);
1155                         c.innerHTML = s;
1156                         if (this.editorFields[i].vtop) c.vAlign = 'top';
1157                 }
1159                 return row;
1160         },
1162         createControls: function(which, rowIndex) {
1163                 var r, c;
1165                 r = this.tb.insertRow(rowIndex);
1166                 r.className = 'controls';
1168                 c = r.insertCell(0);
1169                 c.colSpan = this.header.cells.length;
1170                 if (which == 'edit') {
1171                         c.innerHTML =
1172                                 '<input type=button value="Delete" onclick="TGO(this).onDelete()"> &nbsp; ' +
1173                                 '<input type=button value="OK" onclick="TGO(this).onOK()"> ' +
1174                                 '<input type=button value="Cancel" onclick="TGO(this).onCancel()">';
1175                 }
1176                 else {
1177                         c.innerHTML =
1178                                 '<input type=button value="Add" onclick="TGO(this).onAdd()">';
1179                 }
1180                 return r;
1181         },
1183         removeEditor: function() {
1184                 if (this.editor) {
1186                         elem.remove(this.editor);
1187                         this.editor = null;
1188                 }
1189                 if (this.controls) {
1190                         elem.remove(this.controls);
1191                         this.controls = null;
1192                 }
1193         },
1195         showSource: function() {
1196                 if (this.source) {
1197                         this.source.style.display = '';
1198                         this.source = null;
1199                 }
1200         },
1202         onChange: function(which, cell) {
1203                 return this.verifyFields((which == 'new') ? this.newEditor : this.editor, true);
1204         },
1206         onKey: function(which, ev) {
1207                 switch (ev.keyCode) {
1208                 case 27:
1209                         if (which == 'edit') this.onCancel();
1210                         return false;
1211                 case 13:
1212                         if (((ev.srcElement) && (ev.srcElement.tagName == 'SELECT')) ||
1213                                 ((ev.target) && (ev.target.tagName == 'SELECT'))) return true;
1214                         if (which == 'edit') this.onOK();
1215                                 else this.onAdd();
1216                         return false;
1217                 }
1218                 return true;
1219         },
1221         onDelete: function() {
1222                 this.removeEditor();
1223                 elem.remove(this.source);
1224                 this.source = null;
1225                 this.disableNewEditor(false);
1226         },
1228         onCancel: function() {
1229                 this.removeEditor();
1230                 this.showSource();
1231                 this.disableNewEditor(false);
1232         },
1234         onOK: function() {
1235                 var i, data, view;
1237                 if (!this.verifyFields(this.editor, false)) return;
1239                 data = this.fieldValuesToData(this.editor);
1240                 view = this.dataToView(data);
1242                 this.source.setRowData(data);
1243                 for (i = 0; i < this.source.cells.length; ++i) {
1244                         this.source.cells[i].innerHTML = view[i];
1245                 }
1247                 this.removeEditor();
1248                 this.showSource();
1249                 this.disableNewEditor(false);
1250         },
1252         onAdd: function() {
1253                 var data;
1255                 this.moving = null;
1256                 this.rpHide();
1258                 if (!this.verifyFields(this.newEditor, false)) return;
1260                 data = this.fieldValuesToData(this.newEditor);
1261                 this.insertData(-1, data);
1263                 this.disableNewEditor(false);
1264                 this.resetNewEditor();
1265         },
1267         verifyFields: function(row, quiet) {
1268                 return true;
1269         },
1271         showNewEditor: function() {
1272                 var r;
1274                 r = this.createEditor('new', -1, null);
1275                 this.footer = this.newEditor = r;
1277                 r = this.createControls('new', -1);
1278                 this.newControls = r;
1280                 this.disableNewEditor(false);
1281         },
1283         disableNewEditor: function(disable) {
1284                 if (this.getDataCount() >= this.maxAdd) disable = true;
1285                 if (this.newEditor) fields.disableAll(this.newEditor, disable);
1286                 if (this.newControls) fields.disableAll(this.newControls, disable);
1287         },
1289         resetNewEditor: function() {
1290                 var i, e;
1292                 e = fields.getAll(this.newEditor);
1293                 ferror.clearAll(e);
1294                 for (i = 0; i < e.length; ++i) {
1295                         var f = e[i];
1296                         if (f.selectedIndex) f.selectedIndex = 0;
1297                                 else f.value = '';
1298                 }
1299                 try { if (e.length) e[0].focus(); } catch (er) { }
1300         },
1302         getDataCount: function() {
1303                 var n;
1304                 n = this.tb.rows.length;
1305                 if (this.footer) n = this.footer.rowIndex;
1306                 if (this.header) n -= this.header.rowIndex + 1;
1307                 return n;
1308         },
1310         sortCompare: function(a, b) {
1311                 var obj = TGO(a);
1312                 var col = obj.sortColumn;
1313                 var r = cmpText(a.cells[col].innerHTML, b.cells[col].innerHTML);
1314                 return obj.sortAscending ? r : -r;
1315         },
1317         sort: function(column) {
1318                 if (this.editor) return;
1320                 if (this.sortColumn >= 0) {
1321                         elem.removeClass(this.header.cells[this.sortColumn], 'sortasc', 'sortdes');
1322                 }
1323                 if (column == this.sortColumn) {
1324                         this.sortAscending = !this.sortAscending;
1325                 }
1326                 else {
1327                         this.sortAscending = true;
1328                         this.sortColumn = column;
1329                 }
1330                 elem.addClass(this.header.cells[column], this.sortAscending ? 'sortasc' : 'sortdes');
1332                 this.resort();
1333         },
1335         resort: function() {
1336                 if ((this.sortColumn < 0) || (this.getDataCount() == 0) || (this.editor)) return;
1338                 var p = this.header.parentNode;
1339                 var a = [];
1340                 var i, j, max, e, p;
1341                 var top;
1343                 this.moving = null;
1345                 top = this.header ? this.header.rowIndex + 1 : 0;
1346                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1347                 for (i = top; i < max; ++i) a.push(p.rows[i]);
1348                 a.sort(THIS(this, this.sortCompare));
1349                 this.removeAllData();
1350                 j = top;
1351                 for (i = 0; i < a.length; ++i) {
1352                         e = p.insertBefore(a[i], this.footer);
1353                         e.className = (j & 1) ? 'even' : 'odd';
1354                         ++j;
1355                 }
1356         },
1358         recolor: function() {
1359                  var i, e, o;
1361                  i = this.header ? this.header.rowIndex + 1 : 0;
1362                  e = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1363                  for (; i < e; ++i) {
1364                          o = this.tb.rows[i];
1365                          o.className = (o.rowIndex & 1) ? 'even' : 'odd';
1366                  }
1367         },
1369         removeAllData: function() {
1370                 var i, count;
1372                 i = this.header ? this.header.rowIndex + 1 : 0;
1373                 count = (this.footer ? this.footer.rowIndex : this.tb.rows.length) - i;
1374                 while (count-- > 0) elem.remove(this.tb.rows[i]);
1375         },
1377         getAllData: function() {
1378                 var i, max, data, r;
1380                 data = [];
1381                 max = this.footer ? this.footer.rowIndex : this.tb.rows.length;
1382                 for (i = this.header ? this.header.rowIndex + 1 : 0; i < max; ++i) {
1383                         r = this.tb.rows[i];
1384                         if ((r.style.display != 'none') && (r._data)) data.push(r._data);
1385                 }
1386                 return data;
1387         },
1389         isEditing: function() {
1390                 return (this.editor != null);
1391         }
1395 // -----------------------------------------------------------------------------
1398 function xmlHttpObj()
1400         var ob;
1401         try {
1402                 ob = new XMLHttpRequest();
1403                 if (ob) return ob;
1404         }
1405         catch (ex) { }
1406         try {
1407                 ob = new ActiveXObject('Microsoft.XMLHTTP');
1408                 if (ob) return ob;
1409         }
1410         catch (ex) { }
1411         return null;
1414 var _useAjax = -1;
1415 var _holdAjax = null;
1417 function useAjax()
1419         if (_useAjax == -1) _useAjax = ((_holdAjax = xmlHttpObj()) != null);
1420         return _useAjax;
1423 function XmlHttp()
1425         if ((!useAjax()) || ((this.xob = xmlHttpObj()) == null)) return null;
1426         return this;
1429 XmlHttp.prototype = {
1430         addId: function(vars) {
1431                 if (vars) vars += '&';
1432                         else vars = '';
1433                 vars += '_http_id=' + escapeCGI(nvram.http_id);
1434                 return vars;
1435         },
1437     get: function(url, vars) {
1438                 try {
1439                         vars = this.addId(vars);
1440                         url += '?' + vars;
1442                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1443                         this.xob.open('GET', url, true);
1444                         this.xob.send(null);
1445                 }
1446                 catch (ex) {
1447                         this.onError(ex);
1448                 }
1449         },
1451         post: function(url, vars) {
1452                 try {
1453                         vars = this.addId(vars);
1455                         this.xob.onreadystatechange = THIS(this, this.onReadyStateChange);
1456                         this.xob.open('POST', url, true);
1457                         this.xob.send(vars);
1458                 }
1459                 catch (ex) {
1460                         this.onError(ex);
1461                 }
1462         },
1464         abort: function() {
1465                 try {
1466                         this.xob.onreadystatechange = function () { }
1467                         this.xob.abort();
1468                 }
1469                 catch (ex) {
1470                 }
1471         },
1473         onReadyStateChange: function() {
1474                 try {
1475                         if (typeof(E) == 'undefined') return;   // oddly late? testing for bug...
1477                         if (this.xob.readyState == 4) {
1478                                 if (this.xob.status == 200) {
1479                                         this.onCompleted(this.xob.responseText, this.xob.responseXML);
1480                                 }
1481                                 else {
1482                                         this.onError('' + (this.xob.status || 'unknown'));
1483                                 }
1484                         }
1485                 }
1486                 catch (ex) {
1487                         this.onError(ex);
1488                 }
1489         },
1491         onCompleted: function(text, xml) { },
1492         onError: function(ex) { }
1496 // -----------------------------------------------------------------------------
1499 function TomatoTimer(func, ms)
1501         this.tid = null;
1502         this.onTimer = func;
1503         if (ms) this.start(ms);
1504         return this;
1507 TomatoTimer.prototype = {
1508         start: function(ms) {
1509                 this.stop();
1510                 this.tid = setTimeout(THIS(this, this._onTimer), ms);
1511         },
1512         stop: function() {
1513                 if (this.tid) {
1514                         clearTimeout(this.tid);
1515                         this.tid = null;
1516                 }
1517         },
1519         isRunning: function() {
1520                 return (this.tid != null);
1521         },
1523         _onTimer: function() {
1524                 this.tid = null;
1525                 this.onTimer();
1526         },
1528         onTimer: function() {
1529         }
1533 // -----------------------------------------------------------------------------
1536 function TomatoRefresh(actionURL, postData, refreshTime, cookieTag)
1538         this.setup(actionURL, postData, refreshTime, cookieTag);
1539         this.timer = new TomatoTimer(THIS(this, this.start));
1542 TomatoRefresh.prototype = {
1543         running: 0,
1545         setup: function(actionURL, postData, refreshTime, cookieTag) {
1546                 var e, v;
1548                 this.actionURL = actionURL;
1549                 this.postData = postData;
1550                 this.refreshTime = refreshTime * 1000;
1551                 this.cookieTag = cookieTag;
1552         },
1554         start: function() {
1555                 var e;
1557                 if ((e = E('refresh-time')) != null) {
1558                         if (this.cookieTag) cookie.set(this.cookieTag, e.value);
1559                         this.refreshTime = e.value * 1000;
1560                 }
1561                 e = undefined;
1563                 this.updateUI('start');
1565                 this.running = 1;
1566                 if ((this.http = new XmlHttp()) == null) {
1567                         reloadPage();
1568                         return;
1569                 }
1571                 this.http.parent = this;
1573                 this.http.onCompleted = function(text, xml) {
1574                         var p = this.parent;
1576                         if (p.cookieTag) cookie.unset(p.cookieTag + '-error');
1577                         if (!p.running) {
1578                                 p.stop();
1579                                 return;
1580                         }
1582                         p.refresh(text);
1584                         if ((p.refreshTime > 0) && (!p.once)) {
1585                                 p.updateUI('wait');
1586                                 p.timer.start(Math.round(p.refreshTime));
1587                         }
1588                         else {
1589                                 p.stop();
1590                         }
1591                         
1592                         p.errors = 0;
1593                 }
1595                 this.http.onError = function(ex) {
1596                         var p = this.parent;
1597                         if ((!p) || (!p.running)) return;
1598                         
1599                         p.timer.stop();
1601                         if (++p.errors <= 3) {
1602                                 p.updateUI('wait');
1603                                 p.timer.start(3000);
1604                                 return;
1605                         }
1606                         
1607                         if (p.cookieTag) {
1608                                 var e = cookie.get(p.cookieTag + '-error') * 1;
1609                                 if (isNaN(e)) e = 0;
1610                                         else ++e;
1611                                 cookie.unset(p.cookieTag);
1612                                 cookie.set(p.cookieTag + '-error', e, 1);
1613                                 if (e >= 3) {
1614                                         alert('XMLHTTP: ' + ex);
1615                                         return;
1616                                 }
1617                         }
1619                         setTimeout(reloadPage, 2000);
1620                 }
1622                 this.errors = 0;
1623                 this.http.post(this.actionURL, this.postData);
1624         },
1626         stop: function() {
1627                 if (this.cookieTag) cookie.set(this.cookieTag, -(this.refreshTime / 1000));
1628                 this.running = 0;
1629                 this.updateUI('stop');
1630                 this.timer.stop();
1631                 this.http = null;
1632                 this.once = undefined;
1633         },
1635         toggle: function(delay) {
1636                 if (this.running) this.stop();
1637                         else this.start(delay);
1638         },
1640         updateUI: function(mode) {
1641                 var e, b;
1643                 if (typeof(E) == 'undefined') return;   // for a bizzare bug...
1645                 b = (mode != 'stop') && (this.refreshTime > 0);
1646                 if ((e = E('refresh-button')) != null) {
1647                         e.value = b ? 'Stop' : 'Refresh';
1648                         e.disabled = ((mode == 'start') && (!b));
1649                 }
1650                 if ((e = E('refresh-time')) != null) e.disabled = b;
1651                 if ((e = E('refresh-spinner')) != null) e.style.visibility = b ? 'visible' : 'hidden';
1652         },
1654         initPage: function(delay, def) {
1655                 var e, v;
1657                 e = E('refresh-time');
1658                 if (((this.cookieTag) && (e != null)) &&
1659                         ((v = cookie.get(this.cookieTag)) != null) && (!isNaN(v *= 1))) {
1660                         e.value = Math.abs(v);
1661                         if (v > 0) v = (v * 1000) + (delay || 0);
1662                 }
1663                 else if (def) {
1664                         v = def;
1665                         if (e) e.value = def;
1666                 }
1667                 else v = 0;
1669                 if (delay < 0) {
1670                         v = -delay;
1671                         this.once = 1;
1672                 }
1674                 if (v > 0) {
1675                         this.running = 1;
1676                         this.refreshTime = v;
1677                         this.timer.start(v);
1678                         this.updateUI('wait');
1679                 }
1680         }
1683 function genStdTimeList(id, zero, min)
1685         var b = [];
1686         var t = [3,4,5,10,15,30,60,120,180,240,300,10*60,15*60,20*60,30*60];
1687         var i, v;
1689         if (min >= 0) {
1690                 b.push('<select id="' + id + '"><option value=0>' + zero);
1691                 for (i = 0; i < t.length; ++i) {
1692                         v = t[i];
1693                         if (v < min) continue;
1694                         b.push('<option value=' + v + '>');
1695                         if (v == 60) b.push('1 minute');
1696                                 else if (v > 60) b.push((v / 60) + ' minutes');
1697                                 else b.push(v + ' seconds');
1698                 }
1699                 b.push('</select> ');
1700         }
1701         document.write(b.join(''));
1704 function genStdRefresh(spin, min, exec)
1706         W('<div style="text-align:right">');
1707         if (spin) W('<img src="spin.gif" id="refresh-spinner"> ');
1708         genStdTimeList('refresh-time', 'Auto Refresh', min);
1709         W('<input type="button" value="Refresh" onclick="' + (exec ? exec : 'refreshClick()') + '" id="refresh-button"></div>');
1713 // -----------------------------------------------------------------------------
1716 function _tabCreate(tabs)
1718         var buf = [];
1719         buf.push('<ul id="tabs">');
1720         for (var i = 0; i < arguments.length; ++i)
1721                 buf.push('<li><a href="javascript:tabSelect(\'' + arguments[i][0] + '\')" id="' + arguments[i][0] + '">' + arguments[i][1] + '</a>');
1722         buf.push('</ul><div id="tabs-bottom"></div>');
1723         return buf.join('');
1726 function tabCreate(tabs)
1728         document.write(_tabCreate.apply(this, arguments));
1731 function tabHigh(id)
1733         var a = E('tabs').getElementsByTagName('A');
1734         for (var i = 0; i < a.length; ++i) {
1735                 if (id != a[i].id) elem.removeClass(a[i], 'active');
1736         }
1737         elem.addClass(id, 'active');
1740 // -----------------------------------------------------------------------------
1742 var cookie = {
1743         set: function(key, value, days) {
1744                 document.cookie = 'tomato_' + key + '=' + value + '; expires=' +
1745                         (new Date(new Date().getTime() + ((days ? days : 14) * 86400000))).toUTCString() + '; path=/';
1746         },
1748         get: function(key) {
1749                 var r = ('; ' + document.cookie + ';').match('; tomato_' + key + '=(.*?);');
1750                 return r ? r[1] : null;
1751         },
1753         unset: function(key) {
1754                 document.cookie = 'tomato_' + key + '=; expires=' +
1755                         (new Date(1)).toUTCString() + '; path=/';
1756         }
1759 // -----------------------------------------------------------------------------
1761 function checkEvent(evt)
1763         if (typeof(evt) == 'undefined') {
1764                 // ---- IE
1765                 evt = event;
1766                 evt.target = evt.srcElement;
1767                 evt.relatedTarget = evt.toElement;
1768         }
1769         return evt;
1772 function W(s)
1774         document.write(s);
1777 function E(e)
1779         return (typeof(e) == 'string') ? document.getElementById(e) : e;
1782 function PR(e)
1784         return elem.parentElem(e, 'TR');
1787 function THIS(obj, func)
1789         return function() { return func.apply(obj, arguments); }
1792 function UT(v)
1794         return (typeof(v) == 'undefined') ? '' : '' + v;
1797 function escapeHTML(s)
1799         function esc(c) {
1800                 return '&#' + c.charCodeAt(0) + ';';
1801         }
1802         return s.replace(/[&"'<>\r\n]/g, esc);
1805 function escapeCGI(s)
1807         return escape(s).replace(/\+/g, '%2B'); // escape() doesn't handle +
1810 function escapeD(s)
1812         function esc(c) {
1813                 return '%' + c.charCodeAt(0).hex(2);
1814         }
1815         return s.replace(/[<>|%]/g, esc);
1818 function ellipsis(s, max) {
1819         return (s.length <= max) ? s : s.substr(0, max - 3) + '...';
1822 function MIN(a, b)
1824         return a < b ? a : b;
1827 function MAX(a, b)
1829         return a > b ? a : b;
1832 function fixInt(n, min, max, def)
1834         if (n === null) return def;
1835         n *= 1;
1836         if (isNaN(n)) return def;
1837         if (n < min) return min;
1838         if (n > max) return max;
1839         return n;
1842 function comma(n)
1844         n = '' + n;
1845         var p = n;
1846         while ((n = n.replace(/(\d+)(\d{3})/g, '$1,$2')) != p) p = n;
1847         return n;
1850 function scaleSize(n)
1852         if (isNaN(n *= 1)) return '-';
1853         if (n <= 9999) return '' + n;
1854         var s = -1;
1855         do {
1856                 n /= 1024;
1857                 ++s;
1858         } while ((n > 9999) && (s < 2));
1859         return comma(n.toFixed(2)) + '<small> ' + (['KB', 'MB', 'GB'])[s] + '</small>';
1862 function timeString(mins)
1864         var h = Math.floor(mins / 60);
1865         if ((new Date(2000, 0, 1, 23, 0, 0, 0)).toLocaleString().indexOf('23') != -1)
1866                 return h + ':' + (mins % 60).pad(2);
1867         return ((h == 0) ? 12 : ((h > 12) ? h - 12 : h)) + ':' + (mins % 60).pad(2) + ((h >= 12) ? ' PM' : ' AM');
1870 function features(s)
1872         var features = ['ses','brau','aoss','wham','hpamp','!nve','11n'];
1873         var i;
1875         for (i = features.length - 1; i >= 0; --i) {
1876                 if (features[i] == s) return (parseInt(nvram.t_features) & (1 << i)) != 0;
1877         }
1878         return 0;
1881 function nothing()
1885 // -----------------------------------------------------------------------------
1887 function show_notice1(s)
1889 // ---- !!TB - USB Support: multi-line notices
1890         if (s.length) document.write('<div id="notice1">' + s.replace(/\n/g, '<br>') + '</div><br style="clear:both">');
1893 // -----------------------------------------------------------------------------
1895 function myName()
1897         var name, i;
1899         name = document.location.pathname;
1900         name = name.replace(/\\/g, '/');        // IE local testing
1901         if ((i = name.lastIndexOf('/')) != -1) name = name.substring(i + 1, name.length);
1902         if (name == '') name = 'status-overview.asp';
1903         return name;
1906 function navi()
1908         var menu = [
1909                 ['Status',                              'status', 1, [
1910                         ['Overview',            'overview.asp'],
1911                         ['Device List',         'devices.asp'],
1912                         ['Logs',                        'log.asp'] ] ],
1913                 ['Bandwidth',                   'bwm', 1, [
1914                         ['Real-Time',           'realtime.asp'],
1915                         ['Last 24 Hours',       '24.asp'],
1916                         ['Daily',                       'daily.asp'],
1917                         ['Weekly',                      'weekly.asp'],
1918                         ['Monthly',                     'monthly.asp'] ] ],
1919                 ['Tools',                               'tools', 1, [
1920                         ['Ping',                        'ping.asp'],
1921                         ['Trace',                       'trace.asp'],
1922                         ['Wireless Survey',     'survey.asp'],
1923                         ['WOL',                         'wol.asp'] ] ],
1924                 null,
1925                 ['Basic',                               'basic', 0, [
1926                         ['Network',                     'network.asp'],
1927                         ['Identification',      'ident.asp'],
1928                         ['Time',                        'time.asp'],
1929                         ['DDNS',                        'ddns.asp'],
1930                         ['Static DHCP',         'static.asp'],
1931                         ['Wireless Filter',     'wfilter.asp'] ] ],
1932                 ['Advanced',                    'advanced', 0, [
1933                         ['Conntrack / Netfilter',       'ctnf.asp'],
1934                         ['DHCP / DNS',          'dhcpdns.asp'],
1935                         ['Firewall',            'firewall.asp'],
1936                         ['MAC Address',         'mac.asp'],
1937                         ['Miscellaneous',       'misc.asp'],
1938                         ['Routing',                     'routing.asp'],
1939                         ['Wireless',            'wireless.asp'] ] ],
1940                 ['Port Forwarding',     'forward', 0, [
1941                         ['Basic',                       'basic.asp'],
1942                         ['DMZ',                         'dmz.asp'],
1943                         ['Triggered',           'triggered.asp'],
1944                         ['UPnP',                        'upnp.asp'] ] ],
1945                 ['QoS',                                 'qos', 0, [
1946                         ['Basic Settings',      'settings.asp'],
1947                         ['Classification',      'classify.asp'],
1948                         ['View Graphs',         'graphs.asp'],
1949                         ['View Details',        'detailed.asp']
1950                         ] ],
1951                 ['Access Restriction',  'restrict.asp'],
1952 // ---- !!TB - USB, FTP, Samba
1953                 ['USB and NAS',                 'nas', 0, [
1954                         ['USB Support',         'usb.asp']
1955 /* FTP-BEGIN */                 
1956                         ,['FTP Server',         'ftp.asp']
1957 /* FTP-END */
1958 /* SAMBA-BEGIN */
1959                         ,['File Sharing',       'samba.asp']
1960 /* SAMBA-END */
1961                         ] ],
1962 /* VPN-BEGIN */
1963                 ['VPN Tunneling',               'vpn', 0, [
1964                         ['Server',                      'server.asp'],
1965                         ['Client',                      'client.asp'] ] ],
1966 /* VPN-END */
1967                 null,
1968                 ['Administration',              'admin', 0, [
1969                         ['Admin Access',        'access.asp'],
1970                         ['Bandwidth Monitoring','bwm.asp'],
1971                         ['Buttons / LED',       'buttons.asp'],
1972 /* CIFS-BEGIN */
1973                         ['CIFS Client',         'cifs.asp'],
1974 /* CIFS-END */
1975                         ['Configuration',       'config.asp'],
1976                         ['Debugging',           'debug.asp'],
1977                         ['JFFS',                        'jffs2.asp'],
1978                         ['Logging',                     'log.asp'],
1979                         ['Scheduler',           'sched.asp'],
1980                         ['Scripts',                     'scripts.asp'],
1981                         ['Upgrade',                     'upgrade.asp'] ] ],
1982                 null,
1983                 ['About',                               'about.asp'],
1984                 ['Reboot...',                   'javascript:reboot()'],
1985                 ['Shutdown...',                 'javascript:shutdown()'],
1986                 ['Logout',                              'javascript:logout()']
1987         ];
1988         var name, base;
1989         var i, j;
1990         var buf = [];
1991         var sm;
1992         var a, b, c;
1993         var on1;
1995         name = myName();
1996         if (name == 'restrict-edit.asp') name = 'restrict.asp';
1997         if ((i = name.indexOf('-')) != -1) {
1998                 base = name.substring(0, i);
1999                 name = name.substring(i + 1, name.length);
2000         }
2001         else base = '';
2003         for (i = 0; i < menu.length; ++i) {
2004                 var m = menu[i];
2005                 if (!m) {
2006                         buf.push("<br>");
2007                         continue;
2008                 }
2009                 
2010                 if (m[1] == 'javascript:logout()') {
2011                         // ---- can't logout in IE...
2012                         try {
2013                                 if (navigator.userAgent.match(/MSIE\s+(\d+)/)) {
2014                                         continue;
2015                                 }
2016                         }
2017                         catch (ex) {
2018                         }
2019                 }
2020                 
2021                 if (m.length == 2) {
2022                         buf.push('<a href="' + m[1] + '" class="indent1' + (((base == '') && (name == m[1])) ? ' active' : '') + '">' + m[0] + '</a>');
2023                 }
2024                 else {
2025                         if (base == m[1]) {
2026                                 b = name;
2027                         }
2028                         else {
2029                                 a = cookie.get('menu_' + m[1]);
2030                                 b = m[3][0][1];
2031                                 for (j = 0; j < m[3].length; ++j) {
2032                                         if (m[3][j][1] == a) {
2033                                                 b = a;
2034                                                 break;
2035                                         }
2036                                 }
2037                         }
2038                         a = m[1] + '-' + b;
2039                         if (a == 'status-overview.asp') a = '/';
2040                         on1 = (base == m[1]);
2041                         buf.push('<a href="' + a + '" class="indent1' + (on1 ? ' active' : '') + '">' + m[0] + '</a>');
2042                         if ((!on1) && (m[2] == 0)) continue;
2044                         for (j = 0; j < m[3].length; ++j) {
2045                                 sm = m[3][j];
2046                                 a = m[1] + '-' + sm[1];
2047                                 if (a == 'status-overview.asp') a = '/';
2048                                 buf.push('<a href="' + a + '" class="indent2' + (((on1) && (name == sm[1])) ? ' active' : '') + '">' + sm[0] + '</a>');
2049                         }
2050                 }
2051         }
2052         document.write(buf.join(''));
2054         if (base.length) {
2055                 if ((base == 'qos') && (name == 'detailed.asp')) name = 'view.asp';
2056                 cookie.set('menu_' + base, name);
2057         }
2060 function createFieldTable(flags, desc)
2062         var common;
2063         var i, n;
2064         var name;
2065         var id;
2066         var fields;
2067         var f;
2068         var a;
2069         var buf = [];
2070         var tr;
2072         if ((flags.indexOf('noopen') == -1)) buf.push('<table class="fields">');
2073         for (desci = 0; desci < desc.length; ++desci) {
2074                 var v = desc[desci];
2076                 if (!v) {
2077                         buf.push('<tr><td colspan=2 class="spacer">&nbsp;</td></tr>');
2078                         continue;
2079                 }
2081                 if (v.ignore) continue;
2083                 buf.push('<tr');
2084                 if (v.rid) buf.push(' id="' + v.rid + '"');
2085                 if (v.hidden) buf.push(' style="display:none"');
2086                 buf.push('>');
2088                 if (v.text) {
2089                         if (v.title) {
2090                                 buf.push('<td class="title indent' + (v.indent || 1) + '">' + v.title + '</td><td class="content">' + v.text + '</td></tr>');
2091                         }
2092                         else {
2093                                 buf.push('<td colspan=2>' + v.text + '</td></tr>');
2094                         }
2095                         continue;
2096                 }
2098                 buf.push('<td class="title indent' + (v.indent ? v.indent : 1) + '">' + v.title + '</td>');
2099                 buf.push('<td class="content">');
2101                 if (v.multi) fields = v.multi;
2102                         else fields = [v];
2104                 for (n = 0; n < fields.length; ++n) {
2105                         f = fields[n];
2106                         if (f.prefix) buf.push(f.prefix);
2108                         if ((f.type == 'radio') && (!f.id)) id = '_' + f.name + '_' + i;
2109                                 else id = (f.id ? f.id : ('_' + f.name));
2110                         common = ' onchange="verifyFields(this, 1)" id="' + id + '"';
2111                         if (f.attrib) common += ' ' + f.attrib;
2112                         name = f.name ? (' name="' + f.name + '"') : '';
2114                         switch (f.type) {
2115                         case 'checkbox':
2116                                 buf.push('<input type="checkbox"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2117                                 break;
2118                         case 'radio':
2119                                 buf.push('<input type="radio"' + name + (f.value ? ' checked' : '') + ' onclick="verifyFields(this, 1)"' + common + '>');
2120                                 break;
2121                         case 'password':
2122                         case 'text':
2123                                 buf.push('<input type="' + f.type + '"' + name + ' value="' + escapeHTML(UT(f.value)) + '" maxlength=' + f.maxlen + (f.size ? (' size=' + f.size) : '') + common + '>');
2124                                 break;
2125                         case 'select':
2126                                 buf.push('<select' + name + common + '>');
2127                                 for (i = 0; i < f.options.length; ++i) {
2128                                         a = f.options[i];
2129                                         if (a.length == 1) a.push(a[0]);
2130                                         buf.push('<option value="' + a[0] + '"' + ((a[0] == f.value) ? ' selected' : '') + '>' + a[1] + '</option>');
2131                                 }
2132                                 buf.push('</select>');
2133                                 break;
2134                         case 'textarea':
2135                                 buf.push('<textarea' + name + common + '>' + escapeHTML(UT(f.value)) + '</textarea>');
2136                                 break;
2137                         default:
2138                                 if (f.custom) buf.push(f.custom);
2139                                 break;
2140                         }
2141                         if (f.suffix) buf.push(f.suffix);
2142                 }
2143                 buf.push('</td>');
2144                 buf.push('</tr>');
2145         }
2146         if ((!flags) || (flags.indexOf('noclose') == -1)) buf.push('</table>');
2147         document.write(buf.join(''));
2151 // -----------------------------------------------------------------------------
2153 function reloadPage()
2155         document.location.reload(1);
2158 function reboot()
2160         if (confirm("Reboot?")) form.submitHidden('tomato.cgi', { _reboot: 1, _commit: 0, _nvset: 0 });
2163 function shutdown()
2165         if (confirm("Shutdown?")) form.submitHidden('shutdown.cgi', { });
2168 function logout()
2170         form.submitHidden('logout.asp', { });
2173 // -----------------------------------------------------------------------------
2177 // ---- debug
2179 function isLocal()
2181         return location.href.search('file://') == 0;
2184 function console(s)