Add analytics
[bus.git] / busui / owa / modules / base / js / owa.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
var OWA = {
 
        items: {},
        overlay: '',
        config: {
                ns: 'owa_',
                baseUrl: '',
                hashCookiesToDomain: true
        },
        state: {},
        overlayActive: false,
        
        // depricated
        setSetting: function(name, value) {
                return this.setOption(name, value);
        },
        // depricated
        getSetting: function(name) {
                return this.getOption(name);
        },
        
        setOption: function(name, value) {
                this.config[name] = value;
        },
        
        getOption: function(name) {
                return this.config[name];
        },
        
        initializeStateManager: function() {
                
                if ( ! this.state.hasOwnProperty('init') ) {
                        
                        OWA.debug('initializing state manager...');
                        this.state = new OWA.stateManager();
                }
        },
        
        checkForState: function( store_name ) {
        
                this.initializeStateManager();
                return this.state.isPresent( store_name );
        },
        
        setState : function(store_name, key, value, is_perminant,format, expiration_days) {
        
                this.initializeStateManager();
                return this.state.set(store_name, key, value, is_perminant,format, expiration_days);    
        },
        
        replaceState : function (store_name, value, is_perminant, format, expiration_days) {
        
                this.initializeStateManager();
                return this.state.replaceStore(store_name, value, is_perminant, format, expiration_days);
        },
        
        getStateFromCookie : function(store_name) {
        
                this.initializeStateManager();
                return this.state.getStateFromCookie(store_name);
        },
        
        getState : function(store_name, key) {
                
                this.initializeStateManager();
                return this.state.get(store_name, key);
        },
        
        clearState : function(store_name) {
        
                this.initializeStateManager();
                return this.state.clear(store_name);
        },
        
        getStateStoreFormat: function(store_name) {
        
                this.initializeStateManager();
                return this.state.getStoreFormat(store_name);
        },
        
        setStateStoreFormat: function(store_name, format) {
        
                this.initializeStateManager();
                return this.state.setStoreFormat(store_name, format);
        },
        
        debug: function() {
                
                var debugging = OWA.getSetting('debug') || false; // or true
                
                if ( debugging ) {
                
                        if(window.console) {
                        
                                if (window.console.firebug) { 
                                        console.log.apply(this, arguments);
                                } else {
                                        console.log.apply(console, arguments);
                                }
                        }
                }
        },
        
        setApiEndpoint : function (endpoint) {
                this.config['api_endpoint'] = endpoint;
        },
        
        getApiEndpoint : function() {
                return this.config['api_endpoint'] || this.getSetting('baseUrl') + 'api.php';
        },
        
        loadHeatmap: function(p) {
                var that = this;
                OWA.util.loadScript(OWA.getSetting('baseUrl')+'/modules/base/js/includes/jquery/jquery-1.4.2.min.js', function(){});
                OWA.util.loadCss(OWA.getSetting('baseUrl')+'/modules/base/css/owa.overlay.css', function(){});
                OWA.util.loadScript(OWA.getSetting('baseUrl')+'/modules/base/js/owa.heatmap.js', function(){
                        that.overlay = new OWA.heatmap();
                        //hm.setParams(p);
                        //hm.options.demoMode = true;
                        that.overlay.options.liveMode = true;
                        that.overlay.generate();
                });     
        },
        
        loadPlayer: function() {
                var that = this;
                OWA.debug("Loading Domstream Player");
                OWA.util.loadScript(OWA.getSetting('baseUrl')+'/modules/base/js/includes/jquery/jquery-1.4.2.min.js', function(){});
                OWA.util.loadCss(OWA.getSetting('baseUrl')+'/modules/base/css/owa.overlay.css', function(){});
                OWA.util.loadScript(OWA.getSetting('baseUrl')+'/modules/base/js/owa.player.js', function(){
                        that.overlay = new OWA.player();        
                });     
        },
        
        startOverlaySession: function(p) {
                
                // set global is overlay actve flag
                OWA.overlayActive = true;
                //alert(JSON.stringify(p));
                
                if (p.hasOwnProperty('api_url')) {
                                
                        OWA.setApiEndpoint(p.api_url);
                }
                
            // get param from cookie    
                //var params = OWA.util.parseCookieStringToJson(p);
                var params = p;
                // evaluate the action param
                if (params.action === 'loadHeatmap') {
                        this.loadHeatmap(p);
                } else if (params.action === 'loadPlayer') {
                        this.loadPlayer(p);
                }
                
        },
        
        endOverlaySession : function() {
                                
                OWA.util.eraseCookie('owa_overlay', document.domain);
                OWA.overlayActive = false;
        }
 
 
}
 
OWA.stateManager = function() {
        
        this.cookies = OWA.util.readAllCookies();
        this.init = true;
};
 
OWA.stateManager.prototype = {
        
        init: false,
        cookies: '',
        stores: {},
        storeFormats: {},
        
        isPresent: function( store_name ) {
                
                if ( this.stores.hasOwnProperty( store_name ) ) {
                        return true;
                }
        },
        
        set: function(store_name, key, value, is_perminant,format, expiration_days) {
                
                if ( ! this.isPresent( store_name ) ) {
                        this.load(store_name);
                }
                
                if ( ! this.isPresent( store_name ) ) {
                        OWA.debug('Creating state store (%s)', store_name);
                        this.stores[store_name] = {};
                        // add cookie domain hash
                        if (OWA.getSetting('hashCookiesToDomain')) {
                                this.stores[store_name].cdh = OWA.util.getCookieDomainHash(OWA.getSetting('cookie_domain'));
                        }
                }
                
                if ( key ) {
                        this.stores[store_name][key] = value;
                } else {
                        this.stores[store_name] = value;
                }
                
                if ( ! format ) {
                        
                        // check the orginal format that the state store was loaded from.
                        if (this.storeFormats.hasOwnProperty(store_name)) {
                                format = this.storeFormats[store_name];
                        }
                }
                
                if (format === 'json') {
                        state_value = JSON.stringify(this.stores[store_name]);
                } else {
                        state_value = OWA.util.assocStringFromJson(this.stores[store_name]);
                }
                
                if ( ! expiration_days ) {
                        
                        if ( is_perminant ) {
                                expiration_days =  3600;
                        }
                }
                
                // set or reset the campaign cookie
                OWA.debug('Populating state store (%s) with value: %s', store_name, state_value);
                var domain = OWA.getSetting('cookie_domain') || document.domain;
                // erase cookie
                //OWA.util.eraseCookie( 'owa_'+store_name, domain );
                // set cookie
                OWA.util.setCookie( 'owa_'+store_name, state_value, expiration_days, '/', domain );
        },
        
        replaceStore : function (store_name, value, is_perminant, format, expiration_days) {
                
                OWA.debug('replace state format: %s, value: %s',format, JSON.stringify(value));
                if ( store_name ) {
                
                        if (value) {
                                
                                this.stores[store_name] = value;
                                this.storeFormats[store_name] = format;
                                
                                if (format === 'json') {
                                        cookie_value = JSON.stringify(value);
                                } else {
                                        cookie_value = OWA.util.assocStringFromJson(value);
                                }
                        }
                
                        var domain = OWA.getSetting('cookie_domain') || document.domain;
                        
                        if ( ! expiration_days ) {
                                
                                if ( is_perminant ) {
                                        expiration_days =  3600;
                                }
                        }
                        OWA.debug('About to replace state store (%s) with: %s', store_name, cookie_value);
                        OWA.util.setCookie( 'owa_'+ store_name, cookie_value, expiration_days, '/', domain );
                        
                }
        },
                
        getStateFromCookie : function(store_name) {
                
                var store = unescape( OWA.util.readCookie( OWA.getSetting('ns') + store_name ) );
                if ( store ) {
                        return store;
                }
        },
        
        get : function(store_name, key) {
                
                if ( ! this.isPresent( store_name ) ) {
                        this.load(store_name);
                }
                
                if ( this.isPresent( store_name ) ) {
                        if ( key ) {
                                if ( this.stores[store_name].hasOwnProperty( key ) ) {          
                                        return this.stores[store_name][key];
                                }               
                        } else {
                                return this.stores[store_name];
                        }
                } else {
                        OWA.debug('No state store (%s) was found', store_name);
                        return '';
                }
                
        },
        
        getCookieValues: function(cookie_name) {
                
                if (this.cookies.hasOwnProperty(cookie_name)) {
                        return this.cookies[cookie_name];
                }
        },
        
        load: function(store_name) {
                
                var state = '';
                var cookie_values = this.getCookieValues( OWA.getSetting('ns') + store_name );
                
                if (cookie_values) {
                         
                        for (var i=0;i < cookie_values.length;i++) {
                                
                                
                                var raw_cookie_value = unescape( cookie_values[i] );
                                var cookie_value = OWA.util.decodeCookieValue( raw_cookie_value );
                                //OWA.debug(raw_cookie_value);
                                var format = OWA.util.getCookieValueFormat( raw_cookie_value );
                        
                                if ( OWA.getSetting('hashCookiesToDomain') ) {
                                        var domain = OWA.getSetting('cookie_domain');
                                        var dhash = OWA.util.getCookieDomainHash(domain);
                                
                                        if ( cookie_value.hasOwnProperty( 'cdh' ) ) {
                                                OWA.debug( 'Cookie value cdh: %s, domain hash: %s', cookie_value.cdh, dhash );
                                                if ( cookie_value.cdh == dhash ) {
                                                        OWA.debug('Cookie: %s, index: %s domain hash matches current cookie domain. Loading...', store_name, i);
                                                        state = cookie_value;
                                                        break;
                                                } else {
                                                        OWA.debug('Cookie: %s, index: %s domain hash does not match current cookie domain. Not loading.', store_name, i);
                                                }
                                        } else {
                                                //OWA.debug(cookie_value);
                                                OWA.debug('Cookie: %s, index: %s has no domain hash. Not going to Load it.', store_name, i);
                                        }
                                
                                } else {
                                        // just get the last cookie set by that name
                                        var lastIndex = cookie_values.length -1 ;
                                        if (i === lastIndex) {
                                                state = cookie_value;
                                        }
                                }
                        }
                }       
                        
                if ( state ) {                  
                        this.stores[store_name] = state;
                        this.storeFormats[store_name] = format;
                        OWA.debug('Loaded state store: %s with: %s', store_name, JSON.stringify(state));
                } else {
                        
                        OWA.debug('No state for store: %s was found. Nothing to Load.', store_name);
                }
        },
        
        clear: function(store_name) {
                // delete cookie
                this.stores[store_name] = '';
                OWA.util.eraseCookie(OWA.getSetting('ns') + store_name);
        },
        
        getStoreFormat: function(store_name) {
                
                return this.storeFormats[store_name];
        },
        
        setStoreFormat: function(store_name, format) {
                
                this.storeFormats[store_name] = format;
        }
};
 
 
OWA.util =  {
 
        ns: function(string) {
        
                return OWA.config.ns + string;
        
        },
        
        nsAll: function(obj) {
        
                var nsObj = new Object();
                
                for(param in obj) {  // print out the params
                if (obj.hasOwnProperty(param)) {
                        nsObj[OWA.config.ns+param] = obj[param];
                }
                }
                
                return nsObj;
    },
    
    getScript: function(file, path) {
    
        jQuery.getScript(path + file);
        
        return;
    
    },
    
    makeUrl: function(template, uri, params) {
                var url = jQuery.sprintf(template, uri, jQuery.param(OWA.util.nsAll(params)));
                //alert(url);
                return url;
        },
        
        createCookie: function (name,value,days,domain) {
                if (days) {
                        var date = new Date();
                        date.setTime(date.getTime()+(days*24*60*60*1000));
                        var expires = "; expires="+date.toGMTString();
                }
                else var expires = "";
                document.cookie = name+"="+value+expires+"; path=/";
        },
 
        setCookie: function (name,value,days,path,domain,secure) {
                var date = new Date();
                date.setTime(date.getTime()+(days*24*60*60*1000));
                
                document.cookie = name + "=" + escape (value) +
            ((days) ? "; expires=" + date.toGMTString() : "") +
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            ((secure) ? "; secure" : "");
        },
        
        readAllCookies: function() {
        
                OWA.debug('Reading all cookies...');
                //var dhash = '';
                var jar = {};
                //var nameEQ = name + "=";
                var ca = document.cookie.split(';');
                
                if (ca) {
                        OWA.debug(document.cookie);
                        for(var i=0;i < ca.length;i++) {
                                
                                cat = OWA.util.trim(ca[i]);
                                var pos = OWA.util.strpos(cat, '=');
                                var key = cat.substring(0,pos);
                                var value = cat.substring(pos+1, cat.length);
                                //OWA.debug('key %s, value %s', key, value);
                                // create cookie jar array for that key
                                // this is needed because you can have multiple cookies with the same name
                                if ( ! jar.hasOwnProperty(key) ) {
                                        jar[key] = [];
                                }
                                // add the value to the array
                                jar[key].push(value);
                        }
                        
                        OWA.debug(JSON.stringify(jar));
                        return jar;
                }
        },
        
        /**
         * Reads and returns values from cookies.
         *
         * NOTE: this function returns an array of values as there can be
         * more than one cookie with the same name.
         *
         * @return      array
         */
        readCookie: function (name) {
                OWA.debug('Attempting to read cookie: %s', name);
                var jar = OWA.util.readAllCookies();
                if ( jar ) {
                        if ( jar.hasOwnProperty(name) ) {
                                return jar[name];
                        } else {
                                return '';
                        }
                }
        },
        
        eraseCookie: function (name, domain) {
                OWA.debug(document.cookie);
                if ( ! domain ) {
                        domain = OWA.getSetting('cookie_domain') || document.domain;
                }
                OWA.debug("erasing cookie: " + name + " in domain: " +domain);
                this.setCookie(name,"",-1,"/",domain);
                // attempt to read the cookie again to see if its there under another valid domain
                var test = OWA.util.readCookie(name);
                // if so then try the alternate domain                          
                if (test) {
                        
                        var period = domain.substr(0,1);
                        OWA.debug('period: '+period);
                        if (period === '.') {
                                var domain2 = domain.substr(1);
                                OWA.debug("erasing " + name + " in domain2: " + domain2);
                                this.setCookie(name,"",-2,"/", domain2);
                                
                                        
                        } else {
                                //      domain = '.'+ domain
                                OWA.debug("erasing " + name + " in domain3: " + domain);
                                this.setCookie(name,"",-2,"/",domain);  
                        }
                        //OWA.debug("erasing " + name + " in domain: ");
                        //this.setCookie(name,"",-2,"/");       
                }
                
        },
        
        eraseMultipleCookies: function(names, domain) {
                
                for (var i=0; i < names.length; i++) {
                        this.eraseCookie(names[i], domain);
                }
        },
        
        loadScript: function (url, callback){
 
               return LazyLoad.js(url, callback);
        },
 
        loadCss: function (url, callback){
 
            return LazyLoad.css(url, callback);
        },
        
        parseCookieString: function parseQuery(v) {
                var queryAsAssoc = new Array();
                var queryString = unescape(v);
                var keyValues = queryString.split("|||");
                //alert(keyValues);
                for (var i in keyValues) {
                        if (keyValues.hasOwnProperty(i)) {
                                var key = keyValues[i].split("=>");
                                queryAsAssoc[key[0]] = key[1];
                        }
                        //alert(key[0] +"="+ key[1]);
                }
                
                return queryAsAssoc;
        },
        
        parseCookieStringToJson: function parseQuery(v) {
                var queryAsObj = new Object;
                var queryString = unescape(v);
                var keyValues = queryString.split("|||");
                //alert(keyValues);
                for (var i in keyValues) {
                        if (keyValues.hasOwnProperty(i)) {
                                var key = keyValues[i].split("=>");
                                queryAsObj[key[0]] = key[1];
                                //alert(key[0] +"="+ key[1]);
                        }
                }
                //alert (queryAsObj.period);
                return queryAsObj;
        },
        
        nsParams: function(obj) {
                var new_obj = new Object;
                
                for(param in obj) {
                        if (obj.hasOwnProperty(param)) {
                                new_obj['owa_'+ param] = obj[param];
                        }
                }
                
                return new_obj;
        },
        
        urlEncode : function(str) {
                // URL-encodes string  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/urlencode
            // +   original by: Philip Peterson
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: AJ
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: travc
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Lars Fischer
            // +      input by: Ratheous
            // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Joris
            // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
            // %          note 1: This reflects PHP 5.3/6.0+ behavior
            // %        note 2: Please be aware that this function expects to encode into UTF-8 encoded strings, as found on
            // %        note 2: pages served as UTF-8
            // *     example 1: urlencode('Kevin van Zonneveld!');
            // *     returns 1: 'Kevin+van+Zonneveld%21'
            // *     example 2: urlencode('http://kevin.vanzonneveld.net/');
            // *     returns 2: 'http%3A%2F%2Fkevin.vanzonneveld.net%2F'
            // *     example 3: urlencode('http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a');
            // *     returns 3: 'http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a'
            str = (str+'').toString();
            
            // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
            // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
            return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
        
        },
        
        urldecode : function (str) {
            // Decodes URL-encoded string  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/urldecode
            // +   original by: Philip Peterson
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: AJ
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Brett Zamir (http://brett-zamir.me)
            // +      input by: travc
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Lars Fischer
            // +      input by: Ratheous
            // +   improved by: Orlando
            // +      reimplemented by: Brett Zamir (http://brett-zamir.me)
            // +      bugfixed by: Rob
            // %        note 1: info on what encoding functions to use from: http://xkr.us/articles/javascript/encode-compare/
            // %        note 2: Please be aware that this function expects to decode from UTF-8 encoded strings, as found on
            // %        note 2: pages served as UTF-8
            // *     example 1: urldecode('Kevin+van+Zonneveld%21');
            // *     returns 1: 'Kevin van Zonneveld!'
            // *     example 2: urldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
            // *     returns 2: 'http://kevin.vanzonneveld.net/'
            // *     example 3: urldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
            // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
            
            return decodeURIComponent(str.replace(/\+/g, '%20'));
        },
        
        parseUrlParams : function(url) {
                
                var _GET = {};
                for(var i,a,m,n,o,v,p=location.href.split(/[?&]/),l=p.length,k=1;k<l;k++)
                        if( (m=p[k].match(/(.*?)(\..*?|\[.*?\])?=([^#]*)/)) && m.length==4){
                                n=decodeURI(m[1]).toLowerCase(),o=_GET,v=decodeURI(m[3]);
                                if(m[2])
                                        for(a=decodeURI(m[2]).replace(/\[\s*\]/g,"[-1]").split(/[\.\[\]]/),i=0;i<a.length;i++)
                                                o=o[n]?o[n]:o[n]=(parseInt(a[i])==a[i])?[]:{}, n=a[i].replace(/^["\'](.*)["\']$/,"$1");
                                                n!='-1'?o[n]=v:o[o.length]=v;
                        }
                
                return _GET;
        },
        
        strpos : function(haystack, needle, offset) {
            // Finds position of first occurrence of a string within another  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/strpos
            // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Onno Marsman    
            // +   bugfixed by: Daniel Esteban
            // +   improved by: Brett Zamir (http://brett-zamir.me)
            // *     example 1: strpos('Kevin van Zonneveld', 'e', 5);
            // *     returns 1: 14
            var i = (haystack+'').indexOf(needle, (offset || 0));
            return i === -1 ? false : i;
        },
        
        strCountOccurances : function(haystack, needle) {
                return haystack.split(needle).length - 1;
        },
        
        implode : function(glue, pieces) {
            // Joins array elements placing glue string between items and return one string  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/implode
            // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Waldo Malqui Silva
            // +   improved by: Itsacon (http://www.itsacon.net/)
            // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
            // *     example 1: implode(' ', ['Kevin', 'van', 'Zonneveld']);
            // *     returns 1: 'Kevin van Zonneveld'
            // *     example 2: implode(' ', {first:'Kevin', last: 'van Zonneveld'});
            // *     returns 2: 'Kevin van Zonneveld'
            var i = '', retVal='', tGlue='';
            if (arguments.length === 1) {
                pieces = glue;
                glue = '';
            }
            if (typeof(pieces) === 'object') {
                if (pieces instanceof Array) {
                    return pieces.join(glue);
                }
                else {
                    for (i in pieces) {
                        retVal += tGlue + pieces[i];
                        tGlue = glue;
                    }
                    return retVal;
                }
            }
            else {
                return pieces;
            }
        },
        
        checkForState: function( store_name ) {
        
                return OWA.checkForState( store_name );
        },
        
        setState : function(store_name, key, value, is_perminant,format, expiration_days) {
                
                return OWA.setState(store_name, key, value, is_perminant,format, expiration_days);
        },
        
        replaceState : function (store_name, value, is_perminant, format, expiration_days) {
 
                return OWA.replaceState(store_name, value, is_perminant, format, expiration_days);
        },
        
        getRawState : function(store_name) {
                
                return OWA.getStateFromCookie(store_name);
        },
        
        getState : function(store_name, key) {
                
                return OWA.getState(store_name, key);
        },
        
        clearState : function(store_name) {
                
                return OWA.clearState(store_name);
        },
        
        getCookieValueFormat : function(cstring) {
                var format = '';
                var check = cstring.substr(0,1);                        
                if (check === '{') {
                        format = 'json';
                } else {
                        format = 'assoc';
                }
                
                return format;
        },
        
        decodeCookieValue : function(string) {
                
                var format = OWA.util.getCookieValueFormat(string);
                var value = '';
                //OWA.debug('decodeCookieValue - string: %s, format: %s', string, format);              
                if (format === 'json') {
                        value = JSON.parse(string);
                
                } else {
                        value = OWA.util.jsonFromAssocString(string);
                }
                OWA.debug('decodeCookieValue - string: %s, format: %s, value: %s', string, format, JSON.stringify(value));              
                return value;
        },
        
        encodeJsonForCookie : function(json_obj, format) {
                
                format = format || 'assoc';
                
                if (format === 'json') {
                        return JSON.stringify(json_obj);
                } else {
                        return OWA.util.assocStringFromJson(json_obj);
                }
        },
        
        getCookieDomainHash: function(domain) {
                // must be string
                return OWA.util.dechex(OWA.util.crc32(domain));
        },
        
        loadStateJson : function(store_name) {
                var store = unescape(OWA.util.readCookie( OWA.getSetting('ns') + store_name ) );
                if (store) {
                        state = JSON.parse(store);
                }
                OWA.state[store_name] = state;
                OWA.debug('state store %s: %s', store_name, JSON.stringify(state));
        },
 
        is_array : function (input) {
                return typeof(input)=='object'&&(input instanceof Array);       
        },
        
        // Returns true if variable is an object  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/is_object
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
        is_object : function (mixed_var) {
 
            if (mixed_var instanceof Array) {
                return false;
            } else {
                return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
            }
        },
        
        countObjectProperties : function( obj ) {
                
        var size = 0, key;
        for (key in obj) {
                if (obj.hasOwnProperty(key)) size++;
        }
        return size;
        },
        
        jsonFromAssocString : function(str, inner, outer) {
                
                inner = inner || '=>';
                outer = outer || '|||';
                
                if (str){
                
                        if (!this.strpos(str, inner)) {
        
                                return str;
                                
                        } else {
                                
                                var assoc = {};
                                outer_array = str.split(outer);
                                //OWA.debug('outer array: %s', JSON.stringify(outer_array));
                                for (var i = 0, n = outer_array.length; i < n; i++) {
                                
                                        var inside_array = outer_array[i].split(inner);
                                        
                                        assoc[inside_array[0]] = inside_array[1];
                                }       
                        }
                        
                        //OWA.debug('jsonFromAssocString: ' + JSON.stringify(assoc));
                        return assoc;
                }
        },
        
        assocStringFromJson : function(obj) {
                
                var string = '';
                var i = 0;
                var count = OWA.util.countObjectProperties(obj);
                
                for (prop in obj) {
                        i++;
                        string += prop + '=>' + obj[prop];
                        
                        if (i < count) {
                                string += '|||';
                        }
                }
                //OWA.debug('OWA.util.assocStringFromJson: %s', string);
                return string;  
        
        },
        
        getDomainFromUrl : function (url, strip_www) {
                
                var domain = url.split(/\/+/g)[1];
                
                if (strip_www === true) {
                        var fp = domain.split('.')[0];
                        
                        if (fp === 'www') {
                                return domain.substring(4);
                        } else {
                                return domain;
                        }
                        
                } else {
                        return domain;
                }
        },
        
        getCurrentUnixTimestamp : function() {
                return Math.round(new Date().getTime() / 1000);
        },
        
        generateHash : function(value) {
        
                return this.crc32(value);
        },
        
        generateRandomGuid : function(salt) {
                var time = this.getCurrentUnixTimestamp();
                var random = this.rand();
                return this.generateHash(time + random + salt);
        },
        
        crc32 : function ( str ) {
            // Calculate the crc32 polynomial of a string  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/crc32
            // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
            // +   improved by: T0bsn
            // -    depends on: utf8_encode
            // *     example 1: crc32('Kevin van Zonneveld');
            // *     returns 1: 1249991249
            str = this.utf8_encode(str);
            var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
         
            var crc = 0;
            var x = 0;
            var y = 0;
         
            crc = crc ^ (-1);
            for (var i = 0, iTop = str.length; i < iTop; i++) {
                y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
                x = "0x" + table.substr( y * 9, 8 );
                crc = ( crc >>> 8 ) ^ x;
            }
         
            return crc ^ (-1);
        },
        
        utf8_encode : function ( argString ) {
            // Encodes an ISO-8859-1 string to UTF-8  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/utf8_encode
            // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: sowberry
            // +    tweaked by: Jack
            // +   bugfixed by: Onno Marsman
            // +   improved by: Yves Sucaet
            // +   bugfixed by: Onno Marsman
            // +   bugfixed by: Ulrich
            // *     example 1: utf8_encode('Kevin van Zonneveld');
            // *     returns 1: 'Kevin van Zonneveld'
            var string = (argString+''); // .replace(/\r\n/g, "\n").replace(/\r/g, "\n");
         
            var utftext = "";
            var start, end;
            var stringl = 0;
         
            start = end = 0;
            stringl = string.length;
            for (var n = 0; n < stringl; n++) {
                var c1 = string.charCodeAt(n);
                var enc = null;
         
                if (c1 < 128) {
                    end++;
                } else if (c1 > 127 && c1 < 2048) {
                    enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
                } else {
                    enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
                }
                if (enc !== null) {
                    if (end > start) {
                        utftext += string.substring(start, end);
                    }
                    utftext += enc;
                    start = end = n+1;
                }
            }
         
            if (end > start) {
                utftext += string.substring(start, string.length);
            }
         
            return utftext;
        },
        
        utf8_decode : function( str_data ) {
                // Converts a UTF-8 encoded string to ISO-8859-1  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/utf8_decode
            // +   original by: Webtoolkit.info (http://www.webtoolkit.info/)
            // +      input by: Aman Gupta
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: Norman "zEh" Fuchs
            // +   bugfixed by: hitwork
            // +   bugfixed by: Onno Marsman
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // *     example 1: utf8_decode('Kevin van Zonneveld');
            // *     returns 1: 'Kevin van Zonneveld'
            var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
            
            str_data += '';
            
            while ( i < str_data.length ) {
                c1 = str_data.charCodeAt(i);
                if (c1 < 128) {
                    tmp_arr[ac++] = String.fromCharCode(c1);
                    i++;
                } else if ((c1 > 191) && (c1 < 224)) {
                    c2 = str_data.charCodeAt(i+1);
                    tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
                    i += 2;
                } else {
                    c2 = str_data.charCodeAt(i+1);
                    c3 = str_data.charCodeAt(i+2);
                    tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                    i += 3;
                }
            }
         
            return tmp_arr.join('');
        },
        
        trim : function (str, charlist) {
            // Strips whitespace from the beginning and end of a string  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/trim
            // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: mdsjack (http://www.mdsjack.bo.it)
            // +   improved by: Alexander Ermolaev (http://snippets.dzone.com/user/AlexanderErmolaev)
            // +      input by: Erkekjetter
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: DxGx
            // +   improved by: Steven Levithan (http://blog.stevenlevithan.com)
            // +    tweaked by: Jack
            // +   bugfixed by: Onno Marsman
            // *     example 1: trim('    Kevin van Zonneveld    ');
            // *     returns 1: 'Kevin van Zonneveld'
            // *     example 2: trim('Hello World', 'Hdle');
            // *     returns 2: 'o Wor'
            // *     example 3: trim(16, 1);
            // *     returns 3: 6
            var whitespace, l = 0, i = 0;
            str += '';
            
            if (!charlist) {
                // default list
                whitespace = " \n\r\t\f\x0b\xa0\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u200b\u2028\u2029\u3000";
            } else {
                // preg_quote custom list
                charlist += '';
                whitespace = charlist.replace(/([\[\]\(\)\.\?\/\*\{\}\+\$\^\:])/g, '$1');
            }
            
            l = str.length;
            for (i = 0; i < l; i++) {
                if (whitespace.indexOf(str.charAt(i)) === -1) {
                    str = str.substring(i);
                    break;
                }
            }
            
            l = str.length;
            for (i = l - 1; i >= 0; i--) {
                if (whitespace.indexOf(str.charAt(i)) === -1) {
                    str = str.substring(0, i + 1);
                    break;
                }
            }
            
            return whitespace.indexOf(str.charAt(0)) === -1 ? str : '';
        },
        
        rand : function(min, max) {
            // Returns a random number  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/rand
            // +   original by: Leslie Hoare
            // +   bugfixed by: Onno Marsman
            // *     example 1: rand(1, 1);
            // *     returns 1: 1
            
            var argc = arguments.length;
            if (argc === 0) {
                min = 0;
                max = 2147483647;
            } else if (argc === 1) {
                throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
            }
            return Math.floor(Math.random() * (max - min + 1)) + min;
        },
        
        base64_encode: function (data) {
            // Encodes string using MIME base64 algorithm  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/base64_encode
            // +   original by: Tyler Akins (http://rumkin.com)
            // +   improved by: Bayron Guevara
            // +   improved by: Thunder.m
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   bugfixed by: Pellentesque Malesuada
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // -    depends on: utf8_encode
            // *     example 1: base64_encode('Kevin van Zonneveld');
            // *     returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
            // mozilla has this native
            // - but breaks in 2.0.0.12!
            //if (typeof this.window['atob'] == 'function') {
            //    return atob(data);
            //}
                
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
         
            if (!data) {
                return data;
            }
         
            data = this.utf8_encode(data+'');
            
            do { // pack three octets into four hexets
                o1 = data.charCodeAt(i++);
                o2 = data.charCodeAt(i++);
                o3 = data.charCodeAt(i++);
         
                bits = o1<<16 | o2<<8 | o3;
         
                h1 = bits>>18 & 0x3f;
                h2 = bits>>12 & 0x3f;
                h3 = bits>>6 & 0x3f;
                h4 = bits & 0x3f;
         
                // use hexets to index into b64, and append result to encoded string
                tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
            } while (i < data.length);
            
            enc = tmp_arr.join('');
            
            switch (data.length % 3) {
                case 1:
                    enc = enc.slice(0, -2) + '==';
                break;
                case 2:
                    enc = enc.slice(0, -1) + '=';
                break;
            }
         
            return enc;
        },
        
        base64_decode: function (data) {
            // Decodes string using MIME base64 algorithm  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/base64_decode
            // +   original by: Tyler Akins (http://rumkin.com)
            // +   improved by: Thunder.m
            // +      input by: Aman Gupta
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   bugfixed by: Onno Marsman
            // +   bugfixed by: Pellentesque Malesuada
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // -    depends on: utf8_decode
            // *     example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==');
            // *     returns 1: 'Kevin van Zonneveld'
            // mozilla has this native
            // - but breaks in 2.0.0.12!
            //if (typeof this.window['btoa'] == 'function') {
            //    return btoa(data);
            //}
         
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
         
            if (!data) {
                return data;
            }
         
            data += '';
         
            do {  // unpack four hexets into three octets using index points in b64
                h1 = b64.indexOf(data.charAt(i++));
                h2 = b64.indexOf(data.charAt(i++));
                h3 = b64.indexOf(data.charAt(i++));
                h4 = b64.indexOf(data.charAt(i++));
         
                bits = h1<<18 | h2<<12 | h3<<6 | h4;
         
                o1 = bits>>16 & 0xff;
                o2 = bits>>8 & 0xff;
                o3 = bits & 0xff;
         
                if (h3 == 64) {
                    tmp_arr[ac++] = String.fromCharCode(o1);
                } else if (h4 == 64) {
                    tmp_arr[ac++] = String.fromCharCode(o1, o2);
                } else {
                    tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
                }
            } while (i < data.length);
         
            dec = tmp_arr.join('');
            dec = this.utf8_decode(dec);
         
            return dec;
        },
        
        sprintf : function( ) {
            // Return a formatted string  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/sprintf
            // +   original by: Ash Searle (http://hexmen.com/blog/)
            // + namespaced by: Michael White (http://getsprink.com)
            // +    tweaked by: Jack
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: Paulo Freitas
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +      input by: Brett Zamir (http://brett-zamir.me)
            // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // *     example 1: sprintf("%01.2f", 123.1);
            // *     returns 1: 123.10
            // *     example 2: sprintf("[%10s]", 'monkey');
            // *     returns 2: '[    monkey]'
            // *     example 3: sprintf("[%'#10s]", 'monkey');
            // *     returns 3: '[####monkey]'
            var regex = /%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g;
            var a = arguments, i = 0, format = a[i++];
         
            // pad()
            var pad = function (str, len, chr, leftJustify) {
                if (!chr) {chr = ' ';}
                var padding = (str.length >= len) ? '' : Array(1 + len - str.length >>> 0).join(chr);
                return leftJustify ? str + padding : padding + str;
            };
         
            // justify()
            var justify = function (value, prefix, leftJustify, minWidth, zeroPad, customPadChar) {
                var diff = minWidth - value.length;
                if (diff > 0) {
                    if (leftJustify || !zeroPad) {
                        value = pad(value, minWidth, customPadChar, leftJustify);
                    } else {
                        value = value.slice(0, prefix.length) + pad('', diff, '0', true) + value.slice(prefix.length);
                    }
                }
                return value;
            };
         
            // formatBaseX()
            var formatBaseX = function (value, base, prefix, leftJustify, minWidth, precision, zeroPad) {
                // Note: casts negative numbers to positive ones
                var number = value >>> 0;
                prefix = prefix && number && {'2': '0b', '8': '0', '16': '0x'}[base] || '';
                value = prefix + pad(number.toString(base), precision || 0, '0', false);
                return justify(value, prefix, leftJustify, minWidth, zeroPad);
            };
         
            // formatString()
            var formatString = function (value, leftJustify, minWidth, precision, zeroPad, customPadChar) {
                if (precision != null) {
                    value = value.slice(0, precision);
                }
                return justify(value, '', leftJustify, minWidth, zeroPad, customPadChar);
            };
         
            // doFormat()
            var doFormat = function (substring, valueIndex, flags, minWidth, _, precision, type) {
                var number;
                var prefix;
                var method;
                var textTransform;
                var value;
         
                if (substring == '%%') {return '%';}
         
                // parse flags
                var leftJustify = false, positivePrefix = '', zeroPad = false, prefixBaseX = false, customPadChar = ' ';
                var flagsl = flags.length;
                for (var j = 0; flags && j < flagsl; j++) {
                    switch (flags.charAt(j)) {
                        case ' ': positivePrefix = ' '; break;
                        case '+': positivePrefix = '+'; break;
                        case '-': leftJustify = true; break;
                        case "'": customPadChar = flags.charAt(j+1); break;
                        case '0': zeroPad = true; break;
                        case '#': prefixBaseX = true; break;
                    }
                }
         
                // parameters may be null, undefined, empty-string or real valued
                // we want to ignore null, undefined and empty-string values
                if (!minWidth) {
                    minWidth = 0;
                } else if (minWidth == '*') {
                    minWidth = +a[i++];
                } else if (minWidth.charAt(0) == '*') {
                    minWidth = +a[minWidth.slice(1, -1)];
                } else {
                    minWidth = +minWidth;
                }
         
                // Note: undocumented perl feature:
                if (minWidth < 0) {
                    minWidth = -minWidth;
                    leftJustify = true;
                }
         
                if (!isFinite(minWidth)) {
                    throw new Error('sprintf: (minimum-)width must be finite');
                }
         
                if (!precision) {
                    precision = 'fFeE'.indexOf(type) > -1 ? 6 : (type == 'd') ? 0 : undefined;
                } else if (precision == '*') {
                    precision = +a[i++];
                } else if (precision.charAt(0) == '*') {
                    precision = +a[precision.slice(1, -1)];
                } else {
                    precision = +precision;
                }
         
                // grab value using valueIndex if required?
                value = valueIndex ? a[valueIndex.slice(0, -1)] : a[i++];
         
                switch (type) {
                    case 's': return formatString(String(value), leftJustify, minWidth, precision, zeroPad, customPadChar);
                    case 'c': return formatString(String.fromCharCode(+value), leftJustify, minWidth, precision, zeroPad);
                    case 'b': return formatBaseX(value, 2, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
                    case 'o': return formatBaseX(value, 8, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
                    case 'x': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
                    case 'X': return formatBaseX(value, 16, prefixBaseX, leftJustify, minWidth, precision, zeroPad).toUpperCase();
                    case 'u': return formatBaseX(value, 10, prefixBaseX, leftJustify, minWidth, precision, zeroPad);
                    case 'i':
                    case 'd':
                        number = parseInt(+value, 10);
                        prefix = number < 0 ? '-' : positivePrefix;
                        value = prefix + pad(String(Math.abs(number)), precision, '0', false);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad);
                    case 'e':
                    case 'E':
                    case 'f':
                    case 'F':
                    case 'g':
                    case 'G':
                        number = +value;
                        prefix = number < 0 ? '-' : positivePrefix;
                        method = ['toExponential', 'toFixed', 'toPrecision']['efg'.indexOf(type.toLowerCase())];
                        textTransform = ['toString', 'toUpperCase']['eEfFgG'.indexOf(type) % 2];
                        value = prefix + Math.abs(number)[method](precision);
                        return justify(value, prefix, leftJustify, minWidth, zeroPad)[textTransform]();
                    default: return substring;
                }
            };
         
            return format.replace(regex, doFormat);
        },
        
        clone : function (mixed) {
                
                var newObj = (mixed instanceof Array) ? [] : {};
                for (i in mixed) {
                        if (mixed[i] && (typeof mixed[i] == "object") ) {
                                newObj[i] = OWA.util.clone(mixed[i]);
                        } else {
                                newObj[i] = mixed[i];
                        }
                }
                return newObj;
        },
        
        strtolower : function( str ) {
                
                return (str+'').toLowerCase();
        },
        
        in_array : function(needle, haystack, argStrict) {
            // Checks if the given value exists in the array  
            // 
            // version: 1008.1718
            // discuss at: http://phpjs.org/functions/in_array
            // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +   improved by: vlado houba
            // +   input by: Billy
            // +   bugfixed by: Brett Zamir (http://brett-zamir.me)
            // *     example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
            // *     returns 1: true
            // *     example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'});
            // *     returns 2: false
            // *     example 3: in_array(1, ['1', '2', '3']);
            // *     returns 3: true
            // *     example 3: in_array(1, ['1', '2', '3'], false);
            // *     returns 3: true
            // *     example 4: in_array(1, ['1', '2', '3'], true);
            // *     returns 4: false
            var key = '', strict = !!argStrict;
         
            if (strict) {
                for (key in haystack) {
                    if (haystack[key] === needle) {
                        return true;
                    }
                }
            } else {
                for (key in haystack) {
                    if (haystack[key] == needle) {
                        return true;
                    }
                }
            }
         
            return false;
        },
        
        dechex: function (number) {
            // Returns a string containing a hexadecimal representation of the given number  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/dechex
            // +   original by: Philippe Baumann
            // +   bugfixed by: Onno Marsman
            // +   improved by: http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript
            // +   input by: pilus
            // *     example 1: dechex(10);
            // *     returns 1: 'a'
            // *     example 2: dechex(47);
            // *     returns 2: '2f'
            // *     example 3: dechex(-1415723993);
            // *     returns 3: 'ab9dc427'
            if (number < 0) {
                number = 0xFFFFFFFF + number + 1;
            }
            return parseInt(number, 10).toString(16);
        },
        
        explode: function (delimiter, string, limit) {
            // Splits a string on string separator and return array of components. 
            // If limit is positive only limit number of components is returned. 
            // If limit is negative all components except the last abs(limit) are returned.  
            // 
            // version: 1009.2513
            // discuss at: http://phpjs.org/functions/explode
            // +     original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +     improved by: kenneth
            // +     improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // +     improved by: d3x
            // +     bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
            // *     example 1: explode(' ', 'Kevin van Zonneveld');
            // *     returns 1: {0: 'Kevin', 1: 'van', 2: 'Zonneveld'}
            // *     example 2: explode('=', 'a=bc=d', 2);
            // *     returns 2: ['a', 'bc=d']
         
            var emptyArray = { 0: '' };
            
            // third argument is not required
            if ( arguments.length < 2 ||
                typeof arguments[0] == 'undefined' ||
                typeof arguments[1] == 'undefined' ) {
                return null;
            }
         
            if ( delimiter === '' ||
                delimiter === false ||
                delimiter === null ) {
                return false;
            }
         
            if ( typeof delimiter == 'function' ||
                typeof delimiter == 'object' ||
                typeof string == 'function' ||
                typeof string == 'object' ) {
                return emptyArray;
            }
         
            if ( delimiter === true ) {
                delimiter = '1';
            }
            
            if (!limit) {
                return string.toString().split(delimiter.toString());
            } else {
                // support for limit argument
                var splitted = string.toString().split(delimiter.toString());
                var partA = splitted.splice(0, limit - 1);
                var partB = splitted.join(delimiter.toString());
                partA.push(partB);
                return partA;
            }
        }       
}