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