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