-
Notifications
You must be signed in to change notification settings - Fork 66
/
nitrogen.js
1779 lines (1542 loc) · 61.7 KB
/
nitrogen.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
// vim: sw=4 ts=4 et
// The idea is to have one high level
// Nitrogen object, created from NitrogenClass, that
// encapsulates everything in order to prevent collisions.
var nitrogen_jqm_loaded=false;
const WebSocketStatus = {
NOT_ATTEMPTED: -2,
TRYING_TO_CONNECT: -1,
NOT_ENABLED: 0,
CONNECTED: 1
};
function NitrogenClass(o) {
this.$url = document.location.href;
this.$div = document;
// How frequently to check if the browser has gone to sleep.
// If the browser wakes up from sleep, do a quick ping test to make sure websockets are still connected
this.$sleep_check_interval = 2000;
this.$last_sleep_time = null;
this.$ping_sent = null;
// If a ping is longer than this, websockets are likely disconnected
this.$ping_timeout = 3000;
this.$ping_test_running=false;
// This is the starting value for the websocket reconnection interval.
// It's how many milliseconds to attempt to reconnect after a disconnect. It will quadruple until it reaches $max_websocket_reconnect_interval below
this.$websocket_reconnect_interval = 25;
this.$websocket_reconnect_timer_start = null;
this.$current_websocket_reconnect_interval = 25;
this.$max_websocket_reconnect_interval = 30000;
this.$websocket_closing_timeout = 1000; //if websockets take longer than 1000 seconds to close, just mark them closed and ignore
this.$websocket_closing_timer = null;
// If no websocket messages are received in 30000 milliseconds, this will trigger a ping test with the server
this.$websocket_inactivity_interval = 30000;
this.$websocket_connecting_start=0;
this.$last_websocket_received=0;
this.$anchor_root_path = document;
this.$params = new Object();
this.$event_queue = new Array();
this.$event_is_running = false;
this.$event_success_fun = null;
this.$event_error_fun = null;
this.$event_data_type = "text";
this.$event_obj = null;
this.$event_timeout = null;
this.$system_event_queue = new Array();
this.$system_event_is_running = false;
this.$system_event_obj = null;
this.$system_event_timeout = null;
this.$system_reconnection_events = Array();
this.$last_system_event = null;
this.$going_away = false;
this.$maybe_going_away = false;
this.$live_validation_data_field = "LV_live_validation";
this.$before_postback_list = new Array();
this.$js_dependencies = new Array();
this.$websocket = null;
this.$websockets_enabled = false; // default to off
this.$websocket_status = WebSocketStatus.NOT_ATTEMPTED;
this.$websockets_ever_succeeded = false;
this.$websocket_reconnect_timer = null;
this.$websocket_handlers = new Array();
this.$disconnected = false;
this.$allow_redirect = true;
this.$redirect_prompt = "Are you sure you want to leave?";
return this;
}
/*** EVAL CONTROL ***/
// Control the evaulation yourself. If you'd rather capture the responses on
// your own and evaulate them at your control, you would rebind Nitrogen.$eval.
// After loading nitrogen.js, add:
//
// <script>
// NitrogenClass.prototype.$eval = function(data) {
// ... do your own evaluation ...
// }
// </script>
NitrogenClass.prototype.$eval = function(data) {
return eval(data);
}
/*** PRIVATE METHODS ***/
NitrogenClass.prototype.$path_alias = function(path) {
if (path === 'page') {
return document;
} else {
return path;
}
}
NitrogenClass.prototype.$anchor = function(anchor, target) {
this.$anchor_path = this.$path_alias(anchor);
this.$target_path = this.$path_alias(target);
}
NitrogenClass.prototype.$anchor_root = function(anchor_root) {
this.$anchor_root_path = anchor_root;
}
NitrogenClass.prototype.$set_param = function(key, value) {
this.$params[key] = value;
}
NitrogenClass.prototype.$destroy = function() {
document.comet_started = false;
this.$going_away = true;
// Clear the system event queue and abort any pending system events.
this.$system_event_queue = new Array();
if( this.$system_event_obj !== null ) {
this.$system_event_obj.abort();
}
if(this.$websocket) {
this.$websocket.close();
}
this.$system_event_is_running = false;
// Let the event loop keep running until the event queue is empty.
}
/*** EVENT QUEUE ***/
NitrogenClass.prototype.$queue_event = function(vessel, validationGroup, onInvalid, eventContext, extraParam, ajaxSettings) {
// Put an event on the event_queue.
this.$event_queue.push({
vessel : vessel,
validationGroup : validationGroup,
onInvalid : onInvalid,
eventContext : eventContext,
extraParam : extraParam,
ajaxSettings : ajaxSettings
});
}
NitrogenClass.prototype.$queue_system_event = function(eventContext) {
// Put an event on the event_queue.
this.$system_event_queue.push({
eventContext : eventContext
});
}
NitrogenClass.prototype.$requeue_last_system_event = function() {
// This event never ran, so we need to put it at the beginning of the queue
this.$system_event_queue.unshift(this.$last_system_event);
//this.$last_system_event = null;
}
NitrogenClass.prototype.$requeue_last_event = function() {
this.$event_queue.unshift(this.$last_event);
}
NitrogenClass.prototype.$is_disconnected = function() {
return this.$disconnected;
};
NitrogenClass.prototype.$set_disconnected_no_notice = function(disconnected) {
this.$disconnected = disconnected;
}
NitrogenClass.prototype.$set_disconnected = function(disconnected) {
this.$set_disconnected_no_notice(disconnected);
if(disconnected) {
//We're going to wait just two seconds to determine if we're really disconnected - the system might reconnect quickly.
var n = this;
n.$console_log("We're disconnected, and if we're not reconnected within 2 seconds, we'll show the disconnected bar");
setTimeout(function() {
if(n.$disconnected) {
// if we're still disconnected after 2 seconds, we can show the disconnected bar
n.$console_log("It has been 2 seconds. Time to show the disconnected bar.");
n.$show_disconnected_notice();
}
}, 2000);
}
else {
// but unlike showing the disconnected notice, we want to immediately acknowledge reconnection
this.$hide_disconnected_notice_worked();
}
};
NitrogenClass.prototype.$register_system_reconnection_event = function(tag, fun) {
this.$system_reconnection_events.push({tag:tag, fun:fun});
};
NitrogenClass.prototype.$cancel_system_reconnection_event = function(tag) {
for(var i=0; i<this.$system_reconnection_events.length; i++) {
if(this.$system_reconnection_events[i].tag==tag) {
this.$system_reconnection_events.splice(i, 1);
return;
}
}
};
NitrogenClass.prototype.$reconnect_system = function() {
if(this.$is_disconnected()) {
for(var i=0; i<this.$system_reconnection_events.length; i++) {
this.$system_reconnection_events[i].fun();
}
this.$set_disconnected(false);
this.$system_reconnection_events = [];
}
}
NitrogenClass.prototype.$event_loop = function() {
// Create a local copy of this for setTimeout callbacks.
var this2 = this;
var now = this.$get_time();
// If a system event has been running for longer than 20 seconds, then something is wrong - kill the event
if(this.$system_event_is_running && this.$system_event_obj !== null && now > this.$system_event_started + 20000) {
this.$cancel_system_event();
}
// Similarly, if a normal event has been running fir longer than 20 seconds, kill it too
if(this.$event_is_running && this.$event_obj !== null && now > this.$event_started + 20000) {
this.$cancel_event();
}
// Wait until we know if websockets will work before we run any events.
if ([WebSocketStatus.NOT_ENABLED, WebSocketStatus.CONNECTED].includes(this.$websocket_status)) {
// If no events are running and an event is queued, then fire it.
if (!this.$system_event_is_running && this.$system_event_queue.length > 0) {
var o = this.$system_event_queue.shift();
this.$last_system_event = o;
this.$system_event_started = now;
this.$do_system_event(o.eventContext);
}
// If no events are running and an event is queued, then fire it.
if (!this.$event_is_running && this.$event_queue.length > 0) {
var o = this.$event_queue.shift();
this.$last_event = o;
this.$event_started = now;
this.$do_event(o.vessel, o.validationGroup, o.onInvalid, o.eventContext, o.extraParam, o.ajaxSettings);
}
}
if (this.$system_event_queue.length == 0 || this.$event_queue.length == 0) {
if( this.$going_away ) {
// $destroy has been called for this Nitrogen object
// and the event queue is empty - let the event loop stop.
return;
}
else {
// No more events, sleep for 50 ms...
setTimeout( function() { this2.$event_loop() }, 50);
return;
}
}
// Events queued, but one is running, sleep for 10 ms...
if (this.$event_is_running || this.$system_event_is_running) {
setTimeout( function() { this2.$event_loop() }, 10);
return;
}
// Events queued, loop and grab it...
setTimeout( function() { this2.$event_loop() }, 1);
}
/*** NOTICE BAR AT THE TOP ***/
//notice_type == error|warning|ok
NitrogenClass.prototype.$show_notice_bar = function(notice_type, msg) {
var notice_bar = document.getElementById("nitrogen-notice-bar");
if (null === notice_bar) {
notice_bar = document.createElement("div");
notice_bar.setAttribute("id", "nitrogen-notice-bar");
document.body.insertBefore(notice_bar, document.body.firstChild);
}
notice_bar.setAttribute("class", "visible is-" + notice_type);
notice_bar.innerHTML = msg;
}
NitrogenClass.prototype.$hide_notice_bar = function() {
var notice_bar = document.getElementById("nitrogen-notice-bar");
if ( null === notice_bar ) {
return;
}
// Reset classes to default, where the bar is hidden.
// It's okay to leave the bar in the DOM because if it comes
// back it will transition in again instead of appearing abruptly.
notice_bar.removeAttribute("class");
notice_bar.innerHTML = "";
}
NitrogenClass.prototype.$show_disconnected_notice = function() {
if(!this.$going_away && !this.$maybe_going_away) {
var msg = "⚡ Connection Broken! Attempting to reconnect... ⚡";
this.$show_notice_bar("error", msg);
}
}
NitrogenClass.prototype.$hide_disconnected_notice = function() {
this.$hide_notice_bar();
}
NitrogenClass.prototype.$hide_disconnected_notice_worked = function() {
var notice_bar = document.getElementById("nitrogen-notice-bar");
if (null === notice_bar) {
return;
}
// Is the purpose of `$().is(':visible')` to prevent jank when
// removing a notice that's sliding out? or is it only to
// determine if the notice bar is present on the page?
if (notice_bar.clientHeight > 0) {
this.$show_notice_bar("ok", "Reconnected!");
this.$hide_disconnected_notice();
}
}
/*** VALIDATE AND SERIALIZE ***/
NitrogenClass.prototype.$before_postback = function(f) {
this.$before_postback_list.push(f);
}
NitrogenClass.prototype.$execute_before_postbacks = function() {
var before_list = this.$before_postback_list;
for(var i=0; i<before_list.length; i++) {
try{
before_list[i]();
}catch(ex){
}
}
}
NitrogenClass.prototype.$validate_and_serialize = function(vessel, validationGroup) {
// Check validatation, build object of params...
var is_valid = true,
params = {},
n = this;
this.$execute_before_postbacks();
var inputs;
if(vessel == null)
inputs = jQuery(":input");
else
inputs = jQuery(vessel).find(":input");
var all_inputs = jQuery(inputs).not(".no_postback");
jQuery(all_inputs).each(function(i) {
var LV = Nitrogen.$get_validation(this);
if (LV && LV.group == validationGroup && !LV.validate()) {
// Set a flag, but keep validating to show all messages.
is_valid = false;
} else {
// Skip any unchecked radio boxes.
if ((this.type=="radio" || this.type=="checkbox") && !this.checked) return;
// Skip multi-select boxes with nothing selected
if (this.type=="select-multiple" && ($(this).val()==null || ($(this).val().length==0))) return;
// Skip any plain buttons or submit buttons
if (this.type=='button' || this.type=='submit') return;
// Skip elements that aren't nitrogen elements (they won't have a
// properly named Nitrogen 'id')
var id = n.$make_id(this);
if(id == "") return;
// It's a good element. Let's get the value, and return convert to
// an empty string if it's null
var val = $(this).val();
//console.log(val);
if(val == null || (this.type=="select-multiple" && val.length==0))
val = "";
// Add to the parameter list to send to the server
params[id] = val;
}
});
// Return the params if valid. Otherwise, return null.
return is_valid && params || null;
}
NitrogenClass.prototype.$add_validation = function(element, args) {
if($(element)){
if(!$(element).data(Nitrogen.$live_validation_data_field))
$(element).data(Nitrogen.$live_validation_data_field, new LiveValidation(element, args));
return Nitrogen.$get_validation(element);
} else
return null;
}
NitrogenClass.prototype.$get_validation = function(element) {
return $(element).data(Nitrogen.$live_validation_data_field);
}
// TODO: This needs to be made smarter. Right now, I'm pretty sure elements have
// single validation groups, while it should be a list of groups that get validated
NitrogenClass.prototype.$destroy_specific_validation = function(trigger, target) {
var v = Nitrogen.$get_validation(target);
if(v.group==trigger)
Nitrogen.$destroy_target_validation(target);
}
NitrogenClass.prototype.$destroy_target_validation = function(element) {
var v = Nitrogen.$get_validation(element);
if(v) {
v.destroy();
$(element).data(Nitrogen.$live_validation_data_field,null);
}
}
NitrogenClass.prototype.$destroy_validation_group = function(validationGroup) {
jQuery(":input").not(".no_postback").each(function(i) {
var LV = Nitrogen.$get_validation(this);
if( LV && LV.group == validationGroup) {
Nitrogen.$destroy_target_validation(this);
}
});
}
NitrogenClass.prototype.$destroy_all_validation = function() {
$("*").each(function() {
Nitrogen.$destroy_target_validation(this);
});
}
NitrogenClass.prototype.$make_id = function(element) {
var a = [];
var re = new RegExp("\.wfid_(.[^\\s]*)", "g");
while(element && element.className) {
var matches = element.className.match(/wfid_([^\s])+/g);
if (matches) {
a.unshift.apply(a, matches);
}
element = element.parentNode;
}
return a.join(".");
}
/*** AJAX METHODS ***/
NitrogenClass.prototype.$show_spinner = function() {
$("div.spinner").show();
}
NitrogenClass.prototype.$hide_spinner = function() {
$("div.spinner").hide();
}
NitrogenClass.prototype.$do_event = function(vessel, validationGroup, onInvalid, eventContext, extraParam, ajaxSettings) {
var n = this;
// Flag to prevent firing multiple postbacks at the same time...
this.$event_is_running = true;
// Run validation...
this.$show_spinner();
var validationParams = this.$validate_and_serialize(vessel, validationGroup);
this.$hide_spinner();
if (validationParams == null) {
this.$event_is_running = false;
this.$event_started = null;
// Since validation failed, call onInvalid callback
if (onInvalid) {
onInvalid();
}
return;
}
// Assemble other parameters...
var params = jQuery.extend({}, n.$params, validationParams, extraParam, { eventContext: eventContext });
var s = jQuery.extend({
dataType: 'text',
cache: false,
success: null,
error: null
}, ajaxSettings);
this.$event_data_type = s.dataType;
this.$event_success_fun = s.success;
this.$event_error_fun = s.error;
this.$show_spinner();
//this.$console_log({postback: params});
if(this.$websockets_enabled) {
delete params["pageContext"];
var bertified = Bert.encode_to_bytearray(Bert.tuple(Bert.atom("nitrogen_postback"), params));
this.$ws_send(bertified.buffer);
}else{
this.$event_obj = jQuery.ajax({
url: this.$url,
type:'post',
data: jQuery.param(params),
dataType: s.dataType,
cache: s.cache,
timeout: 18000,
success: function(data, textStatus) { n.$event_success(data, textStatus) },
error: function(XHR, textStatus, errorThrown) { n.$event_error(XHR, textStatus, errorThrown) }
});
}
}
NitrogenClass.prototype.$cancel_event = function() {
if(this.$event_is_running) {
if(this.$event_obj !== null) {
this.$event_obj.abort();
this.$event_obj = null;
}
this.$event_started = null;
this.$console_log("Running event was cancelled due to taking too long");
this.$set_disconnected(true);
this.$event_is_running = false;
this.$hide_spinner();
}
}
NitrogenClass.prototype.$event_success = function(data, textStatus) {
this.$event_is_running = false;
this.$event_started = null;
this.$last_event = null;
this.$hide_spinner();
if(this.$is_disconnected()) {
this.$reconnect_system();
}
if(typeof this.$event_success_fun == 'function') {
this.$event_success_fun(data, textStatus);
}
else{
this.$eval(data);
}
}
NitrogenClass.prototype.$event_error = function(XHR, textStatus, errorThrown) {
var n = this;
this.$event_started = null;
this.$hide_spinner();
if(textStatus == "timeout") {
this.$console_log("System Event timed out");
n.$set_disconnected(true);
}
if(textStatus == "timeout" || textStatus=="error") {
this.$console_log("Event Error: (" + textStatus + "): " + errorThrown);
setTimeout(function() {
n.$requeue_last_event();
}, 500);
}
this.$event_is_running = false;
if(typeof this.$event_error_fun == 'function') {
this.$event_error_fun(XHR, textStatus, errThrown)
}
}
/*** SYSTEM EVENTS (FOR ASYNC) ***/
NitrogenClass.prototype.$do_system_event = function(eventContext) {
var n = this;
// Flag to prevent firing multiple postbacks at the same time...
n.$system_event_is_running = true;
// Assemble other parameters...
var params = jQuery.extend( {}, n.$params, { eventContext: eventContext, is_system_event: 1 });
if(this.$websockets_enabled) {
delete params["pageContext"];
var bertified = Bert.encode_to_bytearray(Bert.tuple(Bert.atom("nitrogen_postback"), params));
n.$ws_send(bertified.buffer);
}
else{
n.$system_event_obj = $.ajax({
url: this.$url,
type:'post',
data: jQuery.param(params),
dataType: 'text',
cache: false,
timeout: 18000,
success: function(data, textStatus) { n.$system_event_success(data) },
error: function(XHR, textStatus, errorThrown) { n.$system_event_error(XHR, textStatus, errorThrown) }
});
}
}
NitrogenClass.prototype.$cancel_system_event = function() {
if(this.$system_event_is_running) {
this.$system_event_obj.abort();
this.$system_event_started = null;
this.$console_log("Canceling system event for taking too long");
this.$set_disconnected(true);
this.$system_event_is_running = false;
}
}
NitrogenClass.prototype.$system_event_success = function(data) {
var n = this;
if(n.$is_disconnected()) {
n.$reconnect_system();
}
n.$system_event_is_running = false;
n.$system_event_obj = null;
n.$system_event_started = null;
n.$last_system_event = null;
// A system event shouldn't clobber the pageContext.
// Easiest to account for it here.
var pc = n.$params["pageContext"];
n.$eval(data);
n.$set_param("pageContext", pc);
}
NitrogenClass.prototype.$system_event_error = function(XHR, textStatus, errorThrown) {
var n = this;
this.$system_event_started = null;
if(textStatus == "timeout") {
n.$set_disconnected(true);
}
if(textStatus == "timeout" || textStatus=="error") {
this.$console_log("System Event Error: (" + textStatus + "): " + errorThrown);
setTimeout(function() {
n.$requeue_last_system_event();
}, 5000);
}
this.$system_event_is_running = false;
this.$system_event_obj = null;
}
/*** FILE UPLOAD ***/
NitrogenClass.prototype.$send_pending_files = function(form,input) {
var file=null;
if(typeof(form.$nitrogen_pending_files)=="object") {
// not a typo, doing an assignment here
while(file=form.$nitrogen_pending_files.shift()) {
file.submit();
}
}
}
NitrogenClass.prototype.$recalculate_upload_dimensions = function(form) {
// If the provided form is a string, let's get the object with objs() which
// does a little massaging.
if(typeof form == "string") {
form = objs(form);
}
var fakeinput = $(form).find(".upload-button");
var w = $(fakeinput).outerWidth(true);
var h = $(fakeinput).outerHeight(true);
$(form).find(".upload-content:visible").width(w).height(h);
}
NitrogenClass.prototype.$attach_upload_handle_dragdrop = function(form,input,settings) {
var thisNitro = this;
if(typeof(settings) == "undefined")
settings={};
if(typeof (form.$nitrogen_pending_files) == "undefined")
form.$nitrogen_pending_files = [];
thisNitro.$dependency_register_function("/nitrogen/jquery.fileupload.min.js",function() {
var dropzone = $(form).children(".upload_drop");
$(input).fileupload({
dropZone:(settings.droppable ? dropzone : null),
singleFileUploads:true,
sequentialUploads:true,
url:thisNitro.$url,
paramName:"file",
formData: function() {
form.elements["pageContext"].value = thisNitro.$params["pageContext"];
var d = $(form).serializeArray();
return d;
},
start: function(e, data) {
form.pageContext.value = thisNitro.$params["pageContext"];
if(settings.overall_progress)
$(form).children(".upload_overall_progress").progressbar({}).slideDown();
},
progressall: function(e,data) {
if(settings.overall_progress) {
$(form).children(".upload_overall_progress")
.progressbar("option", "value", data.loaded)
.progressbar("option", "max", data.total);
if(data.loaded == data.total) {
$(form).children(".upload_overall_progress").slideUp();
}
}
},
progress: function(e,data) {
var loaded = data.loaded;
$.each(data.files, function(i,f) {
$("li[filename=\"" + f.name + "\"] .upload_progress").progressbar("option", "value", loaded);
});
},
send: function(e,data) {
},
stop: function(e,data) {
},
always: function(e,data) {
},
fail: function(e,data, options) {
Nitrogen.$increment_pending_upload_counter(form,-1);
},
add: function(e,data) {
if(!settings.multiple) {
if (data.files.length>1) {
window.alert("Sorry, you can only upload single files with this element");
return;
}
else if(form.$nitrogen_pending_files.length > 0) {
form.$nitrogen_pending_files = [];
$(form).children(".upload_droplist").html("");
}
}
$.each(data.files,function(i,f) {
// Let's add the visual list of pending files
$(form).children(".upload_droplist")
.prepend($("<li></li>").attr("filename",f.name).prepend([
$("<span>").text(f.name + " (" + thisNitro.$format_filesize(f.size) + ")"),
$("<a>")
.attr("href","javascript:;")
.addClass("upload_delete_file")
.bind("click", function() {
$("li[filename=\"" + f.name + "\"]").slideUp();
thisNitro.$delete_pending_file(form, f.name);
})
.html("×"),
$("<div>")
.addClass("upload_progress")
.progressbar({
max:f.size,
value:0
}),
]));
Nitrogen.$increment_pending_upload_counter(form,1);
});
if(settings.autoupload)
data.submit();
else if(settings.multiple || form.$nitrogen_pending_files.length==0)
form.$nitrogen_pending_files.push(data);
else
form.$nitrogen_pending_files[0] = data;
},
done: function(e,data) {
if(typeof data.result == "string") {
// Good browsers will use XHR file transfers, and so this
// will return a string
var Postback = data.result;
} else if(typeof data.result == "object") {
// Crappy browsers (IE9 and below) will do the transfer
// as with an iframe and return a document-type object
var Postback = data.result[0].body.innerHTML;
} else {
// IE also has data.result as "undefined" on failure
// So let's just treat it as an empty string
var Postback = "";
}
$.globalEval(Postback);
Nitrogen.$increment_pending_upload_counter(form,-1);
}
})
})
}
NitrogenClass.prototype.$delete_pending_file = function(form, name) {
for(var i=0;i<form.$nitrogen_pending_files.length;i++) {
for(var j=0;j<form.$nitrogen_pending_files[i].files.length;j++) {
if(form.$nitrogen_pending_files[i].files[j].name==name) {
form.$nitrogen_pending_files[i].files.splice(j,1);
if(form.$nitrogen_pending_files[i].files.length==0) {
form.$nitrogen_pending_files.splice(i, 1);
}
return;
}
}
}
}
NitrogenClass.prototype.$format_filesize = function(size) {
if(size > 1000000000) return (size/1000000000).toFixed(1) + " GB";
else if(size > 1000000) return (size/1000000).toFixed(1) + " MB";
else if(size > 1000) return (size/1000).toFixed(1) + " KB";
else return size + " B";
}
NitrogenClass.prototype.$increment_pending_upload_counter = function(form,incrementer) {
var counter = $(form).data("pending_uploads");
if(typeof(counter)=="undefined")
counter=0;
counter+=incrementer;
$(form).data("pending_uploads",counter);
if(counter==0) {
Nitrogen.$alert_unfinished_files(form);
}
}
NitrogenClass.prototype.$upload_finished = function(Name) {
$(".upload_droplist").children("li[filename=\"" + Name + "\"]")
.css("text-decoration","line-through")
.addClass("upload_successful")
.fadeOut();
}
NitrogenClass.prototype.$alert_unfinished_files = function(form) {
var files = $(form).find(".upload_droplist li:not(.upload_successful):visible");
if(files.length > 0) {
$(form).find(".upload_droplist li:not(.upload_successful)").css("color","red").fadeOut("slow");
var filenames = $(files).get().map(function(f) { return $(f).text() }).join("\r\n");
window.alert("There was an error uploading the following file(s):\r\n" + filenames + "\r\n\r\nThis is likely due to the file(s) being too large or a misconfiguration on the server");
}
}
/*** PATH LOOKUPS ***/
function obj(path, anchor) {
return objs(path, anchor).get(0);
}
function objs(path, anchor) {
if(typeof path != "string")
throw {invalid_path_in_objs: path};
// Trim the path...
path = jQuery.trim(path);
// If no anchor is specified, then use the last anchor set...
if (!anchor) {
anchor = Nitrogen.$anchor_path;
} else {
anchor = Nitrogen.$path_alias(anchor);
}
// Multiple parts, so split and combine results...
if (path.indexOf(",") != -1) {
var paths=path.split(",");
var a = $();
for (var i=0; i<paths.length; i++) {
a = a.add(objs(paths[i], anchor));
}
return a;
}
// Selector is "page", so return the document...
if (path == "page" || path == ".page") {
return jQuery(document);
}
// Replace "##" with ".wfid_"...
path = path.replace(/##/g, '.wfid_');
// Replace "me" with anchor...
path = path.replace(/\bme\b/g, anchor);
// If this is a single word, then rewrite it to a Nitrogen element id.
if (path.indexOf(" ") == -1 && path.indexOf(".") == -1 && path.indexOf("#") == -1) {
var results = objs(".wfid_" + path, anchor);
// If we found results, then return them...
if (results.length > 0) {
return results;
}
// If no results, and this is not a valid HTML element name, then return. Otherwise,
// keep trying with the assumption that this is an HTML element...
if (results.length == 0 && jQuery.inArray(path.toLowerCase(), Nitrogen.$valid_elements) == -1) {
return jQuery();
}
}
// If path begins with "body", then try matching across the entire
// body...
var re = new RegExp(/^body\b/);
if (re.test(path)) {
return jQuery(path);
}
var anchor_obj = jQuery(Nitrogen.$anchor_root_path).find(anchor);
// Find all results under the anchor...
var results = anchor_obj.find(path);
if (results.length > 0) {
return results;
}
// If no results under the anchor, then try on each parent, moving upwards...
var results = anchor_obj.parentsUntil( Nitrogen.$anchor_root_path );
for (var i=0; i<results.length; i++) {
var results2 = jQuery(results.get(i)).find(path);
if (results2.length > 0) {
return results2;
}
}
// No results, so try in context of entire page.
return jQuery(path);
}
NitrogenClass.prototype.$valid_elements = [
"a", "abbr", "acronym", "address", "applet", "area", "b", "base", "basefont",
"bdo", "big", "blockquote", "body", "br", "button", "caption", "center", "cite",
"code", "col", "colgroup", "dd", "del", "dfn", "dir", "div", "dl", "dt", "em",
"fieldset", "font", "form", "frame", "frameset", "h1", "h2", "h3", "h4",
"h5", "h6", "head", "hr", "html", "i", "iframe", "img", "input", "ins", "isindex",
"kbd", "label", "legend", "li", "link", "map", "menu", "meta", "noframes", "noscript",
"object", "ol", "optgroup", "option", "p", "param", "pre", "q", "s", "samp", "script", "select",
"small", "span", "strike", "strong", "style", "sub", "sup", "table", "tbody", "td", "textarea",
"tfoot", "th", "thead", "title", "tr", "tt", "u", "ul", "var"
];
/*** EVENT WIRING ***/
NitrogenClass.prototype.$observe_event = function(anchor, path, type, func) {
objs(path, anchor).bind(type, func);
}
/*** DYNAMIC UPDATING ***/
NitrogenClass.prototype.$update = function(anchor, path, html) {
objs(path, anchor).html(html);
}
NitrogenClass.prototype.$replace = function(anchor, path, html) {
objs(path, anchor).replaceWith(html);
}
NitrogenClass.prototype.$insert_top = function(anchor, path, html) {
objs(path, anchor).prepend(html);
}
NitrogenClass.prototype.$insert_bottom = function(anchor, path, html) {
objs(path, anchor).append(html);
}
NitrogenClass.prototype.$insert_before = function(anchor, path, html) {
objs(path, anchor).before(html);
}
NitrogenClass.prototype.$insert_after = function(anchor, path, html) {
objs(path, anchor).after(html);
}
NitrogenClass.prototype.$remove = function(anchor, path) {
var x = objs(path, anchor).remove();
$(x).next('.LV_validation_message').remove();
x.remove();
}
/*** REQUIRING SCRIPT BEFORE EXECUTION ***/
/* This process works when a depdendency javascript file is requested, it's
* first registered as a pending dependency, then the ajax request is sent to
* load and execute the script. Additionally, any functions that depend on that
* particular file will not be executed, but will instead be queued for
* execution after the script is finally loaded. When the script finally
* successfully loads, the pending requests depending on that script will be
* executed one at a time. Finally, any calls depending on the script made
* after the script has been loaded will be executed right away.
*/
// Queue up functions to be run when a dependency is loaded. If it's already
// loaded, execute right away. If it's not loaded, start the process of loading
// it.
NitrogenClass.prototype.$dependency_register_function = function(dependency, fun) {
if(this.$is_dependency_loaded(dependency)) {
fun();
}
else {
this.$load_js_dependency(dependency);
this.$js_dependencies[dependency].pending_calls.push(fun);
}
};
// Load the js file (if it's not already pending)
NitrogenClass.prototype.$load_js_dependency = function(url) {
var n = this;
// This check will ensure that a js dependency isn't loaded more than once
if(!n.$is_dependency_initialized(url)) {
n.$init_dependency_if_needed(url);
// Request the file, and when it finishes, mark the file is loaded, and
// execute any pending requests
$.ajax({