luci-base: add hostport and ipaddrport validation types
[project/luci.git] / modules / luci-base / htdocs / luci-static / resources / cbi.js
1 /*
2         LuCI - Lua Configuration Interface
3
4         Copyright 2008 Steven Barth <steven@midlink.org>
5         Copyright 2008-2012 Jo-Philipp Wich <jow@openwrt.org>
6
7         Licensed under the Apache License, Version 2.0 (the "License");
8         you may not use this file except in compliance with the License.
9         You may obtain a copy of the License at
10
11         http://www.apache.org/licenses/LICENSE-2.0
12 */
13
14 var cbi_d = [];
15 var cbi_t = [];
16 var cbi_c = [];
17
18 var cbi_validators = {
19
20         'integer': function()
21         {
22                 return (this.match(/^-?[0-9]+$/) != null);
23         },
24
25         'uinteger': function()
26         {
27                 return (cbi_validators.integer.apply(this) && (this >= 0));
28         },
29
30         'float': function()
31         {
32                 return !isNaN(parseFloat(this));
33         },
34
35         'ufloat': function()
36         {
37                 return (cbi_validators['float'].apply(this) && (this >= 0));
38         },
39
40         'ipaddr': function()
41         {
42                 return cbi_validators.ip4addr.apply(this) ||
43                         cbi_validators.ip6addr.apply(this);
44         },
45
46         'ip4addr': function()
47         {
48                 if (this.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(\/(\S+))?$/))
49                 {
50                         return (RegExp.$1 >= 0) && (RegExp.$1 <= 255) &&
51                                (RegExp.$2 >= 0) && (RegExp.$2 <= 255) &&
52                                (RegExp.$3 >= 0) && (RegExp.$3 <= 255) &&
53                                (RegExp.$4 >= 0) && (RegExp.$4 <= 255) &&
54                                ((RegExp.$6.indexOf('.') < 0)
55                                   ? ((RegExp.$6 >= 0) && (RegExp.$6 <= 32))
56                                   : (cbi_validators.ip4addr.apply(RegExp.$6)))
57                         ;
58                 }
59
60                 return false;
61         },
62
63         'ip6addr': function()
64         {
65                 if( this.match(/^([a-fA-F0-9:.]+)(\/(\d+))?$/) )
66                 {
67                         if( !RegExp.$2 || ((RegExp.$3 >= 0) && (RegExp.$3 <= 128)) )
68                         {
69                                 var addr = RegExp.$1;
70
71                                 if( addr == '::' )
72                                 {
73                                         return true;
74                                 }
75
76                                 if( addr.indexOf('.') > 0 )
77                                 {
78                                         var off = addr.lastIndexOf(':');
79
80                                         if( !(off && cbi_validators.ip4addr.apply(addr.substr(off+1))) )
81                                                 return false;
82
83                                         addr = addr.substr(0, off) + ':0:0';
84                                 }
85
86                                 if( addr.indexOf('::') >= 0 )
87                                 {
88                                         var colons = 0;
89                                         var fill = '0';
90
91                                         for( var i = 1; i < (addr.length-1); i++ )
92                                                 if( addr.charAt(i) == ':' )
93                                                         colons++;
94
95                                         if( colons > 7 )
96                                                 return false;
97
98                                         for( var i = 0; i < (7 - colons); i++ )
99                                                 fill += ':0';
100
101                                         if (addr.match(/^(.*?)::(.*?)$/))
102                                                 addr = (RegExp.$1 ? RegExp.$1 + ':' : '') + fill +
103                                                        (RegExp.$2 ? ':' + RegExp.$2 : '');
104                                 }
105
106                                 return (addr.match(/^(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}$/) != null);
107                         }
108                 }
109
110                 return false;
111         },
112
113         'port': function()
114         {
115                 return cbi_validators.integer.apply(this) &&
116                         (this >= 0) && (this <= 65535);
117         },
118
119         'portrange': function()
120         {
121                 if (this.match(/^(\d+)-(\d+)$/))
122                 {
123                         var p1 = RegExp.$1;
124                         var p2 = RegExp.$2;
125
126                         return cbi_validators.port.apply(p1) &&
127                                cbi_validators.port.apply(p2) &&
128                                (parseInt(p1) <= parseInt(p2))
129                         ;
130                 }
131                 else
132                 {
133                         return cbi_validators.port.apply(this);
134                 }
135         },
136
137         'macaddr': function()
138         {
139                 return (this.match(/^([a-fA-F0-9]{2}:){5}[a-fA-F0-9]{2}$/) != null);
140         },
141
142         'host': function()
143         {
144                 return cbi_validators.hostname.apply(this) ||
145                         cbi_validators.ipaddr.apply(this);
146         },
147
148         'hostname': function()
149         {
150                 if (this.length <= 253)
151                         return (this.match(/^[a-zA-Z0-9]+$/) != null ||
152                                 (this.match(/^[a-zA-Z0-9_][a-zA-Z0-9_\-.]*[a-zA-Z0-9]$/) &&
153                                  this.match(/[^0-9.]/)));
154
155                 return false;
156         },
157
158         'network': function()
159         {
160                 return cbi_validators.uciname.apply(this) ||
161                         cbi_validators.host.apply(this);
162         },
163
164         'hostport': function()
165         {
166                 var hp = this.split(/:/);
167
168                 if (hp.length == 2)
169                         return (cbi_validators.host.apply(hp[0]) &&
170                                 cbi_validators.port.apply(hp[1]));
171
172                 return false;
173         },
174
175         'ipaddrport': function()
176         {
177                 var hp = this.split(/:/);
178
179                 if (hp.length == 2)
180                         return (cbi_validators.ipaddr.apply(hp[0]) &&
181                                 cbi_validators.port.apply(hp[1]));
182
183                 return false;
184         },
185
186         'wpakey': function()
187         {
188                 var v = this;
189
190                 if( v.length == 64 )
191                         return (v.match(/^[a-fA-F0-9]{64}$/) != null);
192                 else
193                         return (v.length >= 8) && (v.length <= 63);
194         },
195
196         'wepkey': function()
197         {
198                 var v = this;
199
200                 if ( v.substr(0,2) == 's:' )
201                         v = v.substr(2);
202
203                 if( (v.length == 10) || (v.length == 26) )
204                         return (v.match(/^[a-fA-F0-9]{10,26}$/) != null);
205                 else
206                         return (v.length == 5) || (v.length == 13);
207         },
208
209         'uciname': function()
210         {
211                 return (this.match(/^[a-zA-Z0-9_]+$/) != null);
212         },
213
214         'range': function(min, max)
215         {
216                 var val = parseFloat(this);
217                 if (!isNaN(min) && !isNaN(max) && !isNaN(val))
218                         return ((val >= min) && (val <= max));
219
220                 return false;
221         },
222
223         'min': function(min)
224         {
225                 var val = parseFloat(this);
226                 if (!isNaN(min) && !isNaN(val))
227                         return (val >= min);
228
229                 return false;
230         },
231
232         'max': function(max)
233         {
234                 var val = parseFloat(this);
235                 if (!isNaN(max) && !isNaN(val))
236                         return (val <= max);
237
238                 return false;
239         },
240
241         'rangelength': function(min, max)
242         {
243                 var val = '' + this;
244                 if (!isNaN(min) && !isNaN(max))
245                         return ((val.length >= min) && (val.length <= max));
246
247                 return false;
248         },
249
250         'minlength': function(min)
251         {
252                 var val = '' + this;
253                 if (!isNaN(min))
254                         return (val.length >= min);
255
256                 return false;
257         },
258
259         'maxlength': function(max)
260         {
261                 var val = '' + this;
262                 if (!isNaN(max))
263                         return (val.length <= max);
264
265                 return false;
266         },
267
268         'or': function()
269         {
270                 for (var i = 0; i < arguments.length; i += 2)
271                 {
272                         if (typeof arguments[i] != 'function')
273                         {
274                                 if (arguments[i] == this)
275                                         return true;
276                                 i--;
277                         }
278                         else if (arguments[i].apply(this, arguments[i+1]))
279                         {
280                                 return true;
281                         }
282                 }
283                 return false;
284         },
285
286         'and': function()
287         {
288                 for (var i = 0; i < arguments.length; i += 2)
289                 {
290                         if (typeof arguments[i] != 'function')
291                         {
292                                 if (arguments[i] != this)
293                                         return false;
294                                 i--;
295                         }
296                         else if (!arguments[i].apply(this, arguments[i+1]))
297                         {
298                                 return false;
299                         }
300                 }
301                 return true;
302         },
303
304         'neg': function()
305         {
306                 return cbi_validators.or.apply(
307                         this.replace(/^[ \t]*![ \t]*/, ''), arguments);
308         },
309
310         'list': function(subvalidator, subargs)
311         {
312                 if (typeof subvalidator != 'function')
313                         return false;
314
315                 var tokens = this.match(/[^ \t]+/g);
316                 for (var i = 0; i < tokens.length; i++)
317                         if (!subvalidator.apply(tokens[i], subargs))
318                                 return false;
319
320                 return true;
321         },
322         'phonedigit': function()
323         {
324                 return (this.match(/^[0-9\*#!\.]+$/) != null);
325         }
326 };
327
328
329 function cbi_d_add(field, dep, next) {
330         var obj = document.getElementById(field);
331         if (obj) {
332                 var entry
333                 for (var i=0; i<cbi_d.length; i++) {
334                         if (cbi_d[i].id == field) {
335                                 entry = cbi_d[i];
336                                 break;
337                         }
338                 }
339                 if (!entry) {
340                         entry = {
341                                 "node": obj,
342                                 "id": field,
343                                 "parent": obj.parentNode.id,
344                                 "next": next,
345                                 "deps": []
346                         };
347                         cbi_d.unshift(entry);
348                 }
349                 entry.deps.push(dep)
350         }
351 }
352
353 function cbi_d_checkvalue(target, ref) {
354         var t = document.getElementById(target);
355         var value;
356
357         if (!t) {
358                 var tl = document.getElementsByName(target);
359
360                 if( tl.length > 0 && (tl[0].type == 'radio' || tl[0].type == 'checkbox'))
361                         for( var i = 0; i < tl.length; i++ )
362                                 if( tl[i].checked ) {
363                                         value = tl[i].value;
364                                         break;
365                                 }
366
367                 value = value ? value : "";
368         } else if (!t.value) {
369                 value = "";
370         } else {
371                 value = t.value;
372
373                 if (t.type == "checkbox") {
374                         value = t.checked ? value : "";
375                 }
376         }
377
378         return (value == ref)
379 }
380
381 function cbi_d_check(deps) {
382         var reverse;
383         var def = false;
384         for (var i=0; i<deps.length; i++) {
385                 var istat = true;
386                 reverse = false;
387                 for (var j in deps[i]) {
388                         if (j == "!reverse") {
389                                 reverse = true;
390                         } else if (j == "!default") {
391                                 def = true;
392                                 istat = false;
393                         } else {
394                                 istat = (istat && cbi_d_checkvalue(j, deps[i][j]))
395                         }
396                 }
397                 if (istat) {
398                         return !reverse;
399                 }
400         }
401         return def;
402 }
403
404 function cbi_d_update() {
405         var state = false;
406         for (var i=0; i<cbi_d.length; i++) {
407                 var entry = cbi_d[i];
408                 var next  = document.getElementById(entry.next)
409                 var node  = document.getElementById(entry.id)
410                 var parent = document.getElementById(entry.parent)
411
412                 if (node && node.parentNode && !cbi_d_check(entry.deps)) {
413                         node.parentNode.removeChild(node);
414                         state = true;
415                         if( entry.parent )
416                                 cbi_c[entry.parent]--;
417                 } else if ((!node || !node.parentNode) && cbi_d_check(entry.deps)) {
418                         if (!next) {
419                                 parent.appendChild(entry.node);
420                         } else {
421                                 next.parentNode.insertBefore(entry.node, next);
422                         }
423                         state = true;
424                         if( entry.parent )
425                                 cbi_c[entry.parent]++;
426                 }
427         }
428
429         if (entry && entry.parent) {
430                 if (!cbi_t_update())
431                         cbi_tag_last(parent);
432         }
433
434         if (state) {
435                 cbi_d_update();
436         }
437 }
438
439 function cbi_bind(obj, type, callback, mode) {
440         if (!obj.addEventListener) {
441                 obj.attachEvent('on' + type,
442                         function(){
443                                 var e = window.event;
444
445                                 if (!e.target && e.srcElement)
446                                         e.target = e.srcElement;
447
448                                 return !!callback(e);
449                         }
450                 );
451         } else {
452                 obj.addEventListener(type, callback, !!mode);
453         }
454         return obj;
455 }
456
457 function cbi_combobox(id, values, def, man) {
458         var selid = "cbi.combobox." + id;
459         if (document.getElementById(selid)) {
460                 return
461         }
462
463         var obj = document.getElementById(id)
464         var sel = document.createElement("select");
465                 sel.id = selid;
466                 sel.className = obj.className.replace(/cbi-input-text/, 'cbi-input-select');
467
468         if (obj.nextSibling) {
469                 obj.parentNode.insertBefore(sel, obj.nextSibling);
470         } else {
471                 obj.parentNode.appendChild(sel);
472         }
473
474         var dt = obj.getAttribute('cbi_datatype');
475         var op = obj.getAttribute('cbi_optional');
476
477         if (dt)
478                 cbi_validate_field(sel, op == 'true', dt);
479
480         if (!values[obj.value]) {
481                 if (obj.value == "") {
482                         var optdef = document.createElement("option");
483                         optdef.value = "";
484                         optdef.appendChild(document.createTextNode(def));
485                         sel.appendChild(optdef);
486                 } else {
487                         var opt = document.createElement("option");
488                         opt.value = obj.value;
489                         opt.selected = "selected";
490                         opt.appendChild(document.createTextNode(obj.value));
491                         sel.appendChild(opt);
492                 }
493         }
494
495         for (var i in values) {
496                 var opt = document.createElement("option");
497                 opt.value = i;
498
499                 if (obj.value == i) {
500                         opt.selected = "selected";
501                 }
502
503                 opt.appendChild(document.createTextNode(values[i]));
504                 sel.appendChild(opt);
505         }
506
507         var optman = document.createElement("option");
508         optman.value = "";
509         optman.appendChild(document.createTextNode(man));
510         sel.appendChild(optman);
511
512         obj.style.display = "none";
513
514         cbi_bind(sel, "change", function() {
515                 if (sel.selectedIndex == sel.options.length - 1) {
516                         obj.style.display = "inline";
517                         sel.parentNode.removeChild(sel);
518                         obj.focus();
519                 } else {
520                         obj.value = sel.options[sel.selectedIndex].value;
521                 }
522
523                 try {
524                         cbi_d_update();
525                 } catch (e) {
526                         //Do nothing
527                 }
528         })
529
530         // Retrigger validation in select
531         sel.focus();
532         sel.blur();
533 }
534
535 function cbi_combobox_init(id, values, def, man) {
536         var obj = document.getElementById(id);
537         cbi_bind(obj, "blur", function() {
538                 cbi_combobox(id, values, def, man)
539         });
540         cbi_combobox(id, values, def, man);
541 }
542
543 function cbi_filebrowser(id, url, defpath) {
544         var field   = document.getElementById(id);
545         var browser = window.open(
546                 url + ( field.value || defpath || '' ) + '?field=' + id,
547                 "luci_filebrowser", "width=300,height=400,left=100,top=200,scrollbars=yes"
548         );
549
550         browser.focus();
551 }
552
553 function cbi_browser_init(id, respath, url, defpath)
554 {
555         function cbi_browser_btnclick(e) {
556                 cbi_filebrowser(id, url, defpath);
557                 return false;
558         }
559
560         var field = document.getElementById(id);
561
562         var btn = document.createElement('img');
563         btn.className = 'cbi-image-button';
564         btn.src = respath + '/cbi/folder.gif';
565         field.parentNode.insertBefore(btn, field.nextSibling);
566
567         cbi_bind(btn, 'click', cbi_browser_btnclick);
568 }
569
570 function cbi_dynlist_init(name, respath, datatype, optional, url, defpath, choices)
571 {
572         var input0 = document.getElementsByName(name)[0];
573         var prefix = input0.name;
574         var parent = input0.parentNode;
575         var holder = input0.placeholder;
576
577         var values;
578
579         function cbi_dynlist_redraw(focus, add, del)
580         {
581                 values = [ ];
582
583                 while (parent.firstChild)
584                 {
585                         var n = parent.firstChild;
586                         var i = parseInt(n.index);
587
588                         if (i != del)
589                         {
590                                 if (n.nodeName.toLowerCase() == 'input')
591                                         values.push(n.value || '');
592                                 else if (n.nodeName.toLowerCase() == 'select')
593                                         values[values.length-1] = n.options[n.selectedIndex].value;
594                         }
595
596                         parent.removeChild(n);
597                 }
598
599                 if (add >= 0)
600                 {
601                         focus = add+1;
602                         values.splice(focus, 0, '');
603                 }
604                 else if (values.length == 0)
605                 {
606                         focus = 0;
607                         values.push('');
608                 }
609
610                 for (var i = 0; i < values.length; i++)
611                 {
612                         var t = document.createElement('input');
613                                 t.id = prefix + '.' + (i+1);
614                                 t.name = prefix;
615                                 t.value = values[i];
616                                 t.type = 'text';
617                                 t.index = i;
618                                 t.className = 'cbi-input-text';
619
620                         if (i == 0 && holder)
621                         {
622                                 t.placeholder = holder;
623                         }
624
625                         var b = document.createElement('img');
626                                 b.src = respath + ((i+1) < values.length ? '/cbi/remove.gif' : '/cbi/add.gif');
627                                 b.className = 'cbi-image-button';
628
629                         parent.appendChild(t);
630                         parent.appendChild(b);
631                         if (datatype == 'file')
632                         {
633                                 cbi_browser_init(t.id, respath, url, defpath);
634                         }
635
636                         parent.appendChild(document.createElement('br'));
637
638                         if (datatype)
639                         {
640                                 cbi_validate_field(t.id, ((i+1) == values.length) || optional, datatype);
641                         }
642
643                         if (choices)
644                         {
645                                 cbi_combobox_init(t.id, choices[0], '', choices[1]);
646                                 b.index = i;
647
648                                 cbi_bind(b, 'keydown',  cbi_dynlist_keydown);
649                                 cbi_bind(b, 'keypress', cbi_dynlist_keypress);
650
651                                 if (i == focus || -i == focus)
652                                         b.focus();
653                         }
654                         else
655                         {
656                                 cbi_bind(t, 'keydown',  cbi_dynlist_keydown);
657                                 cbi_bind(t, 'keypress', cbi_dynlist_keypress);
658
659                                 if (i == focus)
660                                 {
661                                         t.focus();
662                                 }
663                                 else if (-i == focus)
664                                 {
665                                         t.focus();
666
667                                         /* force cursor to end */
668                                         var v = t.value;
669                                         t.value = ' '
670                                         t.value = v;
671                                 }
672                         }
673
674                         cbi_bind(b, 'click', cbi_dynlist_btnclick);
675                 }
676         }
677
678         function cbi_dynlist_keypress(ev)
679         {
680                 ev = ev ? ev : window.event;
681
682                 var se = ev.target ? ev.target : ev.srcElement;
683
684                 if (se.nodeType == 3)
685                         se = se.parentNode;
686
687                 switch (ev.keyCode)
688                 {
689                         /* backspace, delete */
690                         case 8:
691                         case 46:
692                                 if (se.value.length == 0)
693                                 {
694                                         if (ev.preventDefault)
695                                                 ev.preventDefault();
696
697                                         return false;
698                                 }
699
700                                 return true;
701
702                         /* enter, arrow up, arrow down */
703                         case 13:
704                         case 38:
705                         case 40:
706                                 if (ev.preventDefault)
707                                         ev.preventDefault();
708
709                                 return false;
710                 }
711
712                 return true;
713         }
714
715         function cbi_dynlist_keydown(ev)
716         {
717                 ev = ev ? ev : window.event;
718
719                 var se = ev.target ? ev.target : ev.srcElement;
720
721                 if (se.nodeType == 3)
722                         se = se.parentNode;
723
724                 var prev = se.previousSibling;
725                 while (prev && prev.name != name)
726                         prev = prev.previousSibling;
727
728                 var next = se.nextSibling;
729                 while (next && next.name != name)
730                         next = next.nextSibling;
731
732                 /* advance one further in combobox case */
733                 if (next && next.nextSibling.name == name)
734                         next = next.nextSibling;
735
736                 switch (ev.keyCode)
737                 {
738                         /* backspace, delete */
739                         case 8:
740                         case 46:
741                                 var del = (se.nodeName.toLowerCase() == 'select')
742                                         ? true : (se.value.length == 0);
743
744                                 if (del)
745                                 {
746                                         if (ev.preventDefault)
747                                                 ev.preventDefault();
748
749                                         var focus = se.index;
750                                         if (ev.keyCode == 8)
751                                                 focus = -focus+1;
752
753                                         cbi_dynlist_redraw(focus, -1, se.index);
754
755                                         return false;
756                                 }
757
758                                 break;
759
760                         /* enter */
761                         case 13:
762                                 cbi_dynlist_redraw(-1, se.index, -1);
763                                 break;
764
765                         /* arrow up */
766                         case 38:
767                                 if (prev)
768                                         prev.focus();
769
770                                 break;
771
772                         /* arrow down */
773                         case 40:
774                                 if (next)
775                                         next.focus();
776
777                                 break;
778                 }
779
780                 return true;
781         }
782
783         function cbi_dynlist_btnclick(ev)
784         {
785                 ev = ev ? ev : window.event;
786
787                 var se = ev.target ? ev.target : ev.srcElement;
788                 var input = se.previousSibling;
789                 while (input && input.name != name) {
790                         input = input.previousSibling;
791                 }
792
793                 if (se.src.indexOf('remove') > -1)
794                 {
795                         input.value = '';
796
797                         cbi_dynlist_keydown({
798                                 target:  input,
799                                 keyCode: 8
800                         });
801                 }
802                 else
803                 {
804                         cbi_dynlist_keydown({
805                                 target:  input,
806                                 keyCode: 13
807                         });
808                 }
809
810                 return false;
811         }
812
813         cbi_dynlist_redraw(NaN, -1, -1);
814 }
815
816 //Hijacks the CBI form to send via XHR (requires Prototype)
817 function cbi_hijack_forms(layer, win, fail, load) {
818         var forms = layer.getElementsByTagName('form');
819         for (var i=0; i<forms.length; i++) {
820                 $(forms[i]).observe('submit', function(event) {
821                         // Prevent the form from also submitting the regular way
822                         event.stop();
823
824                         // Submit via XHR
825                         event.element().request({
826                                 onSuccess: win,
827                                 onFailure: fail
828                         });
829
830                         if (load) {
831                                 load();
832                         }
833                 });
834         }
835 }
836
837
838 function cbi_t_add(section, tab) {
839         var t = document.getElementById('tab.' + section + '.' + tab);
840         var c = document.getElementById('container.' + section + '.' + tab);
841
842         if( t && c ) {
843                 cbi_t[section] = (cbi_t[section] || [ ]);
844                 cbi_t[section][tab] = { 'tab': t, 'container': c, 'cid': c.id };
845         }
846 }
847
848 function cbi_t_switch(section, tab) {
849         if( cbi_t[section] && cbi_t[section][tab] ) {
850                 var o = cbi_t[section][tab];
851                 var h = document.getElementById('tab.' + section);
852                 for( var tid in cbi_t[section] ) {
853                         var o2 = cbi_t[section][tid];
854                         if( o.tab.id != o2.tab.id ) {
855                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab( |$)/, " cbi-tab-disabled ");
856                                 o2.container.style.display = 'none';
857                         }
858                         else {
859                                 if(h) h.value = tab;
860                                 o2.tab.className = o2.tab.className.replace(/(^| )cbi-tab-disabled( |$)/, " cbi-tab ");
861                                 o2.container.style.display = 'block';
862                         }
863                 }
864         }
865         return false
866 }
867
868 function cbi_t_update() {
869         var hl_tabs = [ ];
870         var updated = false;
871
872         for( var sid in cbi_t )
873                 for( var tid in cbi_t[sid] )
874                 {
875                         if( cbi_c[cbi_t[sid][tid].cid] == 0 ) {
876                                 cbi_t[sid][tid].tab.style.display = 'none';
877                         }
878                         else if( cbi_t[sid][tid].tab && cbi_t[sid][tid].tab.style.display == 'none' ) {
879                                 cbi_t[sid][tid].tab.style.display = '';
880
881                                 var t = cbi_t[sid][tid].tab;
882                                 t.className += ' cbi-tab-highlighted';
883                                 hl_tabs.push(t);
884                         }
885
886                         cbi_tag_last(cbi_t[sid][tid].container);
887                         updated = true;
888                 }
889
890         if( hl_tabs.length > 0 )
891                 window.setTimeout(function() {
892                         for( var i = 0; i < hl_tabs.length; i++ )
893                                 hl_tabs[i].className = hl_tabs[i].className.replace(/ cbi-tab-highlighted/g, '');
894                 }, 750);
895
896         return updated;
897 }
898
899
900 function cbi_validate_form(form, errmsg)
901 {
902         /* if triggered by a section removal or addition, don't validate */
903         if( form.cbi_state == 'add-section' || form.cbi_state == 'del-section' )
904                 return true;
905
906         if( form.cbi_validators )
907         {
908                 for( var i = 0; i < form.cbi_validators.length; i++ )
909                 {
910                         var validator = form.cbi_validators[i];
911                         if( !validator() && errmsg )
912                         {
913                                 alert(errmsg);
914                                 return false;
915                         }
916                 }
917         }
918
919         return true;
920 }
921
922 function cbi_validate_reset(form)
923 {
924         window.setTimeout(
925                 function() { cbi_validate_form(form, null) }, 100
926         );
927
928         return true;
929 }
930
931 function cbi_validate_compile(code)
932 {
933         var pos = 0;
934         var esc = false;
935         var depth = 0;
936         var stack = [ ];
937
938         code += ',';
939
940         for (var i = 0; i < code.length; i++)
941         {
942                 if (esc)
943                 {
944                         esc = false;
945                         continue;
946                 }
947
948                 switch (code.charCodeAt(i))
949                 {
950                 case 92:
951                         esc = true;
952                         break;
953
954                 case 40:
955                 case 44:
956                         if (depth <= 0)
957                         {
958                                 if (pos < i)
959                                 {
960                                         var label = code.substring(pos, i);
961                                                 label = label.replace(/\\(.)/g, '$1');
962                                                 label = label.replace(/^[ \t]+/g, '');
963                                                 label = label.replace(/[ \t]+$/g, '');
964
965                                         if (label && !isNaN(label))
966                                         {
967                                                 stack.push(parseFloat(label));
968                                         }
969                                         else if (label.match(/^(['"]).*\1$/))
970                                         {
971                                                 stack.push(label.replace(/^(['"])(.*)\1$/, '$2'));
972                                         }
973                                         else if (typeof cbi_validators[label] == 'function')
974                                         {
975                                                 stack.push(cbi_validators[label]);
976                                                 stack.push(null);
977                                         }
978                                         else
979                                         {
980                                                 throw "Syntax error, unhandled token '"+label+"'";
981                                         }
982                                 }
983                                 pos = i+1;
984                         }
985                         depth += (code.charCodeAt(i) == 40);
986                         break;
987
988                 case 41:
989                         if (--depth <= 0)
990                         {
991                                 if (typeof stack[stack.length-2] != 'function')
992                                         throw "Syntax error, argument list follows non-function";
993
994                                 stack[stack.length-1] =
995                                         arguments.callee(code.substring(pos, i));
996
997                                 pos = i+1;
998                         }
999                         break;
1000                 }
1001         }
1002
1003         return stack;
1004 }
1005
1006 function cbi_validate_field(cbid, optional, type)
1007 {
1008         var field = (typeof cbid == "string") ? document.getElementById(cbid) : cbid;
1009         var vstack; try { vstack = cbi_validate_compile(type); } catch(e) { };
1010
1011         if (field && vstack && typeof vstack[0] == "function")
1012         {
1013                 var validator = function()
1014                 {
1015                         // is not detached
1016                         if( field.form )
1017                         {
1018                                 field.className = field.className.replace(/ cbi-input-invalid/g, '');
1019
1020                                 // validate value
1021                                 var value = (field.options && field.options.selectedIndex > -1)
1022                                         ? field.options[field.options.selectedIndex].value : field.value;
1023
1024                                 if (!(((value.length == 0) && optional) || vstack[0].apply(value, vstack[1])))
1025                                 {
1026                                         // invalid
1027                                         field.className += ' cbi-input-invalid';
1028                                         return false;
1029                                 }
1030                         }
1031
1032                         return true;
1033                 };
1034
1035                 if( ! field.form.cbi_validators )
1036                         field.form.cbi_validators = [ ];
1037
1038                 field.form.cbi_validators.push(validator);
1039
1040                 cbi_bind(field, "blur",  validator);
1041                 cbi_bind(field, "keyup", validator);
1042
1043                 if (field.nodeName == 'SELECT')
1044                 {
1045                         cbi_bind(field, "change", validator);
1046                         cbi_bind(field, "click",  validator);
1047                 }
1048
1049                 field.setAttribute("cbi_validate", validator);
1050                 field.setAttribute("cbi_datatype", type);
1051                 field.setAttribute("cbi_optional", (!!optional).toString());
1052
1053                 validator();
1054
1055                 var fcbox = document.getElementById('cbi.combobox.' + field.id);
1056                 if (fcbox)
1057                         cbi_validate_field(fcbox, optional, type);
1058         }
1059 }
1060
1061 function cbi_row_swap(elem, up, store)
1062 {
1063         var tr = elem.parentNode;
1064         while (tr && tr.nodeName.toLowerCase() != 'tr')
1065                 tr = tr.parentNode;
1066
1067         if (!tr)
1068                 return false;
1069
1070         var table = tr.parentNode;
1071         while (table && table.nodeName.toLowerCase() != 'table')
1072                 table = table.parentNode;
1073
1074         if (!table)
1075                 return false;
1076
1077         var s = up ? 3 : 2;
1078         var e = up ? table.rows.length : table.rows.length - 1;
1079
1080         for (var idx = s; idx < e; idx++)
1081         {
1082                 if (table.rows[idx] == tr)
1083                 {
1084                         if (up)
1085                                 tr.parentNode.insertBefore(table.rows[idx], table.rows[idx-1]);
1086                         else
1087                                 tr.parentNode.insertBefore(table.rows[idx+1], table.rows[idx]);
1088
1089                         break;
1090                 }
1091         }
1092
1093         var ids = [ ];
1094         for (idx = 2; idx < table.rows.length; idx++)
1095         {
1096                 table.rows[idx].className = table.rows[idx].className.replace(
1097                         /cbi-rowstyle-[12]/, 'cbi-rowstyle-' + (1 + (idx % 2))
1098                 );
1099
1100                 if (table.rows[idx].id && table.rows[idx].id.match(/-([^\-]+)$/) )
1101                         ids.push(RegExp.$1);
1102         }
1103
1104         var input = document.getElementById(store);
1105         if (input)
1106                 input.value = ids.join(' ');
1107
1108         return false;
1109 }
1110
1111 function cbi_tag_last(container)
1112 {
1113         var last;
1114
1115         for (var i = 0; i < container.childNodes.length; i++)
1116         {
1117                 var c = container.childNodes[i];
1118                 if (c.nodeType == 1 && c.nodeName.toLowerCase() == 'div')
1119                 {
1120                         c.className = c.className.replace(/ cbi-value-last$/, '');
1121                         last = c;
1122                 }
1123         }
1124
1125         if (last)
1126         {
1127                 last.className += ' cbi-value-last';
1128         }
1129 }
1130
1131 String.prototype.serialize = function()
1132 {
1133         var o = this;
1134         switch(typeof(o))
1135         {
1136                 case 'object':
1137                         // null
1138                         if( o == null )
1139                         {
1140                                 return 'null';
1141                         }
1142
1143                         // array
1144                         else if( o.length )
1145                         {
1146                                 var i, s = '';
1147
1148                                 for( var i = 0; i < o.length; i++ )
1149                                         s += (s ? ', ' : '') + String.serialize(o[i]);
1150
1151                                 return '[ ' + s + ' ]';
1152                         }
1153
1154                         // object
1155                         else
1156                         {
1157                                 var k, s = '';
1158
1159                                 for( k in o )
1160                                         s += (s ? ', ' : '') + k + ': ' + String.serialize(o[k]);
1161
1162                                 return '{ ' + s + ' }';
1163                         }
1164
1165                         break;
1166
1167                 case 'string':
1168                         // complex string
1169                         if( o.match(/[^a-zA-Z0-9_,.: -]/) )
1170                                 return 'decodeURIComponent("' + encodeURIComponent(o) + '")';
1171
1172                         // simple string
1173                         else
1174                                 return '"' + o + '"';
1175
1176                         break;
1177
1178                 default:
1179                         return o.toString();
1180         }
1181 }
1182
1183 String.prototype.format = function()
1184 {
1185         if (!RegExp)
1186                 return;
1187
1188         var html_esc = [/&/g, '&#38;', /"/g, '&#34;', /'/g, '&#39;', /</g, '&#60;', />/g, '&#62;'];
1189         var quot_esc = [/"/g, '&#34;', /'/g, '&#39;'];
1190
1191         function esc(s, r) {
1192                 for( var i = 0; i < r.length; i += 2 )
1193                         s = s.replace(r[i], r[i+1]);
1194                 return s;
1195         }
1196
1197         var str = this;
1198         var out = '';
1199         var re = /^(([^%]*)%('.|0|\x20)?(-)?(\d+)?(\.\d+)?(%|b|c|d|u|f|o|s|x|X|q|h|j|t|m))/;
1200         var a = b = [], numSubstitutions = 0, numMatches = 0;
1201
1202         while( a = re.exec(str) )
1203         {
1204                 var m = a[1];
1205                 var leftpart = a[2], pPad = a[3], pJustify = a[4], pMinLength = a[5];
1206                 var pPrecision = a[6], pType = a[7];
1207
1208                 numMatches++;
1209
1210                 if (pType == '%')
1211                 {
1212                         subst = '%';
1213                 }
1214                 else
1215                 {
1216                         if (numSubstitutions < arguments.length)
1217                         {
1218                                 var param = arguments[numSubstitutions++];
1219
1220                                 var pad = '';
1221                                 if (pPad && pPad.substr(0,1) == "'")
1222                                         pad = leftpart.substr(1,1);
1223                                 else if (pPad)
1224                                         pad = pPad;
1225
1226                                 var justifyRight = true;
1227                                 if (pJustify && pJustify === "-")
1228                                         justifyRight = false;
1229
1230                                 var minLength = -1;
1231                                 if (pMinLength)
1232                                         minLength = parseInt(pMinLength);
1233
1234                                 var precision = -1;
1235                                 if (pPrecision && pType == 'f')
1236                                         precision = parseInt(pPrecision.substring(1));
1237
1238                                 var subst = param;
1239
1240                                 switch(pType)
1241                                 {
1242                                         case 'b':
1243                                                 subst = (parseInt(param) || 0).toString(2);
1244                                                 break;
1245
1246                                         case 'c':
1247                                                 subst = String.fromCharCode(parseInt(param) || 0);
1248                                                 break;
1249
1250                                         case 'd':
1251                                                 subst = (parseInt(param) || 0);
1252                                                 break;
1253
1254                                         case 'u':
1255                                                 subst = Math.abs(parseInt(param) || 0);
1256                                                 break;
1257
1258                                         case 'f':
1259                                                 subst = (precision > -1)
1260                                                         ? ((parseFloat(param) || 0.0)).toFixed(precision)
1261                                                         : (parseFloat(param) || 0.0);
1262                                                 break;
1263
1264                                         case 'o':
1265                                                 subst = (parseInt(param) || 0).toString(8);
1266                                                 break;
1267
1268                                         case 's':
1269                                                 subst = param;
1270                                                 break;
1271
1272                                         case 'x':
1273                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toLowerCase();
1274                                                 break;
1275
1276                                         case 'X':
1277                                                 subst = ('' + (parseInt(param) || 0).toString(16)).toUpperCase();
1278                                                 break;
1279
1280                                         case 'h':
1281                                                 subst = esc(param, html_esc);
1282                                                 break;
1283
1284                                         case 'q':
1285                                                 subst = esc(param, quot_esc);
1286                                                 break;
1287
1288                                         case 'j':
1289                                                 subst = String.serialize(param);
1290                                                 break;
1291
1292                                         case 't':
1293                                                 var td = 0;
1294                                                 var th = 0;
1295                                                 var tm = 0;
1296                                                 var ts = (param || 0);
1297
1298                                                 if (ts > 60) {
1299                                                         tm = Math.floor(ts / 60);
1300                                                         ts = (ts % 60);
1301                                                 }
1302
1303                                                 if (tm > 60) {
1304                                                         th = Math.floor(tm / 60);
1305                                                         tm = (tm % 60);
1306                                                 }
1307
1308                                                 if (th > 24) {
1309                                                         td = Math.floor(th / 24);
1310                                                         th = (th % 24);
1311                                                 }
1312
1313                                                 subst = (td > 0)
1314                                                         ? String.format('%dd %dh %dm %ds', td, th, tm, ts)
1315                                                         : String.format('%dh %dm %ds', th, tm, ts);
1316
1317                                                 break;
1318
1319                                         case 'm':
1320                                                 var mf = pMinLength ? parseInt(pMinLength) : 1000;
1321                                                 var pr = pPrecision ? Math.floor(10*parseFloat('0'+pPrecision)) : 2;
1322
1323                                                 var i = 0;
1324                                                 var val = parseFloat(param || 0);
1325                                                 var units = [ '', 'K', 'M', 'G', 'T', 'P', 'E' ];
1326
1327                                                 for (i = 0; (i < units.length) && (val > mf); i++)
1328                                                         val /= mf;
1329
1330                                                 subst = val.toFixed(pr) + ' ' + units[i];
1331                                                 break;
1332                                 }
1333                         }
1334                 }
1335
1336                 out += leftpart + subst;
1337                 str = str.substr(m.length);
1338         }
1339
1340         return out + str;
1341 }
1342
1343 String.prototype.nobr = function()
1344 {
1345         return this.replace(/[\s\n]+/g, '&#160;');
1346 }
1347
1348 String.serialize = function()
1349 {
1350         var a = [ ];
1351         for (var i = 1; i < arguments.length; i++)
1352                 a.push(arguments[i]);
1353         return ''.serialize.apply(arguments[0], a);
1354 }
1355
1356 String.format = function()
1357 {
1358         var a = [ ];
1359         for (var i = 1; i < arguments.length; i++)
1360                 a.push(arguments[i]);
1361         return ''.format.apply(arguments[0], a);
1362 }
1363
1364 String.nobr = function()
1365 {
1366         var a = [ ];
1367         for (var i = 1; i < arguments.length; i++)
1368                 a.push(arguments[i]);
1369         return ''.nobr.apply(arguments[0], a);
1370 }