This repository has been archived by the owner on Feb 14, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 192
/
gravityforms.js
2461 lines (1878 loc) · 77.7 KB
/
gravityforms.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
// "prop" method fix for previous versions of jQuery (1.5 and below)
if( typeof jQuery.fn.prop === 'undefined' ) {
jQuery.fn.prop = jQuery.fn.attr;
}
jQuery(document).ready(function(){
//Formatting free form currency fields to currency
jQuery(document).bind('gform_post_render', gformBindFormatPricingFields);
});
function gformBindFormatPricingFields(){
// Namespace the event and remove before adding to prevent double binding.
jQuery(".ginput_amount, .ginput_donation_amount").off('change.gform').on("change.gform", function(){
gformFormatPricingField(this);
});
jQuery(".ginput_amount, .ginput_donation_amount").each(function(){
gformFormatPricingField(this);
});
}
//------------------------------------------------
//---------- CURRENCY ----------------------------
//------------------------------------------------
function Currency(currency){
this.currency = currency;
this.toNumber = function(text){
if(this.isNumeric(text)) {
return parseFloat(text);
}
return gformCleanNumber(text, this.currency["symbol_right"], this.currency["symbol_left"], this.currency["decimal_separator"]);
};
/**
* Attempts to clean the specified number and formats it as currency.
*
* @since 2.1.1.16 Allow the overriding of numerical checks.
*
* @param number int Number to be formatted. It can be a clean number, or an already formatted number.
* @param isNumeric bool Whether or not the number is guaranteed to be a clean, unformatted number.
* When false the function will attempt to clean the number. Defaults to false.
*
* @return string A number formatted as currency.
*/
this.toMoney = function(number, isNumeric){
isNumeric = isNumeric || false; //isNumeric is an optional parameter. Defaults to false
if( ! isNumeric ) {
//Cleaning number, removing all formatting
number = gformCleanNumber(number, this.currency["symbol_right"], this.currency["symbol_left"], this.currency["decimal_separator"]);
}
if(number === false) {
return "";
}
number = number + "";
negative = "";
if(number[0] == "-"){
number = parseFloat(number.substr(1));
negative = '-';
}
money = this.numberFormat(number, this.currency["decimals"], this.currency["decimal_separator"], this.currency["thousand_separator"]);
if ( money == '0.00' ){
negative = '';
}
var symbol_left = this.currency["symbol_left"] ? this.currency["symbol_left"] + this.currency["symbol_padding"] : "";
var symbol_right = this.currency["symbol_right"] ? this.currency["symbol_padding"] + this.currency["symbol_right"] : "";
money = negative + this.htmlDecode(symbol_left) + money + this.htmlDecode(symbol_right);
return money;
};
/**
* Formats a number given the specified parameters.
*
* @since Unknown
*
* @param number int Number to be formatted. Must be a clean, unformatted format.
* @param decimals int Number of decimals that the output should contain.
* @param dec_point string Character to use as the decimal separator. Defaults to ".".
* @param thousands_sep string Character to use as the thousand separator. Defaults to ",".
* @param padded bool Pads output with zeroes if the number is exact. For example, 1.200.
*
* @return string The formatted number.
*/
this.numberFormat = function(number, decimals, dec_point, thousands_sep, padded){
padded = typeof padded == 'undefined' ? true : padded;
number = (number+'').replace(',', '').replace(' ', '');
var n = !isFinite(+number) ? 0 : +number,
prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep, dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
s = '',
toFixedFix = function (n, prec) {
var k = Math.pow(10, prec);
return '' + Math.round(n * k) / k;
};
if(decimals == '0') {
n = n + 0.0000000001; // getting around floating point arithmetic issue when rounding. ( i.e. 4.005 is represented as 4.004999999999 and gets rounded to 4.00 instead of 4.01 )
s = ('' + Math.round(n)).split('.');
} else
if(decimals == -1) {
s = ('' + n).split('.');
} else {
n = n + 0.0000000001; // getting around floating point arithmetic issue when rounding. ( i.e. 4.005 is represented as 4.004999999999 and gets rounded to 4.00 instead of 4.01 )
// Fix for IE parseFloat(0.55).toFixed(0) = 0;
s = toFixedFix(n, prec).split('.');
}
if (s[0].length > 3) {
s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
}
if(padded) {
if ((s[1] || '').length < prec) {
s[1] = s[1] || '';
s[1] += new Array(prec - s[1].length + 1).join('0');
}
}
return s.join(dec);
}
this.isNumeric = function(number){
return gformIsNumber(number);
};
this.htmlDecode = function(text) {
var c,m,d = text;
// look for numerical entities "
var arr=d.match(/&#[0-9]{1,5};/g);
// if no matches found in string then skip
if(arr!=null){
for(var x=0;x<arr.length;x++){
m = arr[x];
c = m.substring(2,m.length-1); //get numeric part which is refernce to unicode character
// if its a valid number we can decode
if(c >= -32768 && c <= 65535){
// decode every single match within string
d = d.replace(m, String.fromCharCode(c));
}else{
d = d.replace(m, ""); //invalid so replace with nada
}
}
}
return d;
};
}
/**
* Gets a formatted number and returns a clean "decimal dot" number.
*
* Note: Input must be formatted according to the specified parameters (symbol_right, symbol_left, decimal_separator).
* @example input -> $1.20, output -> 1.2
*
* @since 2.1.1.16 Modified to support additional param in Currency.toMoney.
*
* @param text string The currency-formatted number.
* @param symbol_right string The symbol used on the right.
* @param symbol_left string The symbol used on the left.
* @param decimal_separator string The decimal separator being used.
*
* @return float The unformatted numerical value.
*/
function gformCleanNumber(text, symbol_right, symbol_left, decimal_separator){
var clean_number = '',
float_number = '',
digit = '',
is_negative = false;
//converting to a string if a number as passed
text = text + " ";
//Removing symbol in unicode format (i.e. ᅜ)
text = text.replace(/&.*?;/g, "");
//Removing symbol from text
text = text.replace(symbol_right, "");
text = text.replace(symbol_left, "");
//Removing all non-numeric characters
for(var i=0; i<text.length; i++){
digit = text.substr(i,1);
if( (parseInt(digit,10) >= 0 && parseInt(digit,10) <= 9) || digit == decimal_separator )
clean_number += digit;
else if(digit == '-')
is_negative = true;
}
//Removing thousand separators but keeping decimal point
for(var i=0; i<clean_number.length; i++) {
digit = clean_number.substr(i,1);
if (digit >= '0' && digit <= '9')
float_number += digit;
else if(digit == decimal_separator){
float_number += ".";
}
}
if(is_negative)
float_number = "-" + float_number;
return gformIsNumber(float_number) ? parseFloat(float_number) : false;
}
function gformGetDecimalSeparator(numberFormat){
var s;
switch (numberFormat){
case 'currency' :
var currency = new Currency(gf_global.gf_currency_config);
s = currency.currency["decimal_separator"];
break;
case 'decimal_comma' :
s = ',';
break;
default :
s = "."
}
return s;
}
function gformIsNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function gformIsNumeric(value, number_format){
switch(number_format){
case "decimal_dot" :
var r = new RegExp("^(-?[0-9]{1,3}(?:,?[0-9]{3})*(?:\.[0-9]+)?)$");
return r.test(value);
break;
case "decimal_comma" :
var r = new RegExp("^(-?[0-9]{1,3}(?:\.?[0-9]{3})*(?:,[0-9]+)?)$");
return r.test(value);
break;
}
return false;
}
//------------------------------------------------
//---------- MULTI-PAGE --------------------------
//------------------------------------------------
function gformDeleteUploadedFile(formId, fieldId, deleteButton){
var parent = jQuery("#field_" + formId + "_" + fieldId);
var fileIndex = jQuery(deleteButton).parent().index();
parent.find(".ginput_preview").eq(fileIndex).remove();
//displaying single file upload field
parent.find('input[type="file"],.validation_message,#extensions_message_' + formId + '_' + fieldId).removeClass("gform_hidden");
//displaying post image label
parent.find(".ginput_post_image_file").show();
//clearing post image meta fields
parent.find("input[type=\"text\"]").val('');
//removing file from uploaded meta
var filesJson = jQuery('#gform_uploaded_files_' + formId).val();
if(filesJson){
var files = jQuery.secureEvalJSON(filesJson);
if(files) {
var inputName = "input_" + fieldId;
var $multfile = parent.find("#gform_multifile_upload_" + formId + "_" + fieldId );
if( $multfile.length > 0 ) {
files[inputName].splice(fileIndex, 1);
var settings = $multfile.data('settings');
var max = settings.gf_vars.max_files;
jQuery("#" + settings.gf_vars.message_id).html('');
if(files[inputName].length < max)
gfMultiFileUploader.toggleDisabled(settings, false);
} else {
files[inputName] = null;
}
jQuery('#gform_uploaded_files_' + formId).val(jQuery.toJSON(files));
}
}
}
//------------------------------------------------
//---------- PRICE -------------------------------
//------------------------------------------------
var _gformPriceFields = new Array();
var _anyProductSelected;
function gformIsHidden(element){
return element.parents('.gfield').not(".gfield_hidden_product").css("display") == "none";
}
function gformCalculateTotalPrice(formId){
if(!_gformPriceFields[formId])
return;
var price = 0;
_anyProductSelected = false; //Will be used by gformCalculateProductPrice().
for(var i=0; i<_gformPriceFields[formId].length; i++){
price += gformCalculateProductPrice(formId, _gformPriceFields[formId][i]);
}
//add shipping price if a product has been selected
if(_anyProductSelected){
//shipping price
var shipping = gformGetShippingPrice(formId)
price += shipping;
}
//gform_product_total filter. Allows uers to perform custom price calculation
if(window["gform_product_total"])
price = window["gform_product_total"](formId, price);
price = gform.applyFilters('gform_product_total', price, formId);
//updating total
var totalElement = jQuery(".ginput_total_" + formId);
if( totalElement.length > 0 ) {
var currentTotal = totalElement.next().val(),
formattedTotal = gformFormatMoney(price, true);
if (currentTotal != price) {
totalElement.next().val(price).change();
}
if (formattedTotal != totalElement.first().text()) {
totalElement.html(formattedTotal);
}
}
}
function gformGetShippingPrice(formId){
var shippingField = jQuery(".gfield_shipping_" + formId + " input[type=\"hidden\"], .gfield_shipping_" + formId + " select, .gfield_shipping_" + formId + " input:checked");
var shipping = 0;
if(shippingField.length == 1 && !gformIsHidden(shippingField)){
if(shippingField.attr("type") && shippingField.attr("type").toLowerCase() == "hidden")
shipping = shippingField.val();
else
shipping = gformGetPrice(shippingField.val());
}
return gformToNumber(shipping);
}
function gformGetFieldId(element){
var id = jQuery(element).attr("id");
var pieces = id.split("_");
if(pieces.length <=0)
return 0;
var fieldId = pieces[pieces.length-1];
return fieldId;
}
function gformCalculateProductPrice(form_id, productFieldId){
var suffix = '_' + form_id + '_' + productFieldId;
//Drop down auto-calculating labels
jQuery('.gfield_option' + suffix + ', .gfield_shipping_' + form_id).find('select').each(function(){
var dropdown_field = jQuery(this);
var selected_price = gformGetPrice(dropdown_field.val());
var field_id = dropdown_field.attr('id').split('_')[2];
dropdown_field.children('option').each(function(){
var choice_element = jQuery(this);
var label = gformGetOptionLabel(choice_element, choice_element.val(), selected_price, form_id, field_id);
choice_element.html(label);
});
});
//Checkboxes labels with prices
jQuery('.gfield_option' + suffix).find('.gfield_checkbox').find('input:checkbox').each(function(){
var checkbox_item = jQuery(this);
var id = checkbox_item.attr('id');
var field_id = id.split('_')[2];
var label_id = id.replace('choice_', '#label_');
var label_element = jQuery(label_id);
var label = gformGetOptionLabel(label_element, checkbox_item.val(), 0, form_id, field_id);
label_element.html(label);
});
//Radio button auto-calculating lables
jQuery('.gfield_option' + suffix + ', .gfield_shipping_' + form_id).find('.gfield_radio').each(function(){
var selected_price = 0;
var radio_field = jQuery(this);
var id = radio_field.attr('id');
var fieldId = id.split('_')[2];
var selected_value = radio_field.find('input:radio:checked').val();
if(selected_value)
selected_price = gformGetPrice(selected_value);
radio_field.find('input:radio').each(function(){
var radio_item = jQuery(this);
var label_id = radio_item.attr('id').replace('choice_', '#label_');
var label_element = jQuery(label_id);
if ( label_element ) {
var label = gformGetOptionLabel(label_element, radio_item.val(), selected_price, form_id, fieldId);
label_element.html(label);
}
});
});
var price = gformGetBasePrice(form_id, productFieldId);
var quantity = gformGetProductQuantity( form_id, productFieldId );
//calculating options if quantity is more than 0 (a product was selected).
if( quantity > 0 ) {
jQuery('.gfield_option' + suffix).find('input:checked, select').each(function(){
if(!gformIsHidden(jQuery(this)))
price += gformGetPrice(jQuery(this).val());
});
//setting global variable if quantity is more than 0 (a product was selected). Will be used when calculating total
_anyProductSelected = true;
}
price = price * quantity;
price = gformRoundPrice(price) ;
return price;
}
function gformGetProductQuantity(formId, productFieldId) {
//If product is not selected
if (!gformIsProductSelected(formId, productFieldId)) {
return 0;
}
var quantity,
quantityInput = jQuery('#ginput_quantity_' + formId + '_' + productFieldId),
numberFormat;
if (gformIsHidden(quantityInput)) {
return 0;
}
if (quantityInput.length > 0) {
quantity = quantityInput.val();
} else {
quantityInput = jQuery('.gfield_quantity_' + formId + '_' + productFieldId + ' :input');
quantity = 1;
if (quantityInput.length > 0) {
quantity = quantityInput.val();
var htmlId = quantityInput.attr('id'),
fieldId = gf_get_input_id_by_html_id(htmlId);
numberFormat = gf_get_field_number_format( fieldId, formId, 'value' );
}
}
if (!numberFormat)
numberFormat = 'currency';
var decimalSeparator = gformGetDecimalSeparator(numberFormat);
quantity = gformCleanNumber(quantity, '', '', decimalSeparator);
if (!quantity)
quantity = 0;
return quantity;
}
function gformIsProductSelected( formId, productFieldId ) {
var suffix = "_" + formId + "_" + productFieldId;
var productField = jQuery("#ginput_base_price" + suffix + ", .gfield_donation" + suffix + " input[type=\"text\"], .gfield_product" + suffix + " .ginput_amount");
if( productField.val() && ! gformIsHidden(productField) ){
return true;
}
else
{
productField = jQuery(".gfield_product" + suffix + " select, .gfield_product" + suffix + " input:checked, .gfield_donation" + suffix + " select, .gfield_donation" + suffix + " input:checked");
if( productField.val() && ! gformIsHidden(productField) ){
return true;
}
}
return false;
}
function gformGetBasePrice(formId, productFieldId){
var suffix = "_" + formId + "_" + productFieldId;
var price = 0;
var productField = jQuery("#ginput_base_price" + suffix+ ", .gfield_donation" + suffix + " input[type=\"text\"], .gfield_product" + suffix + " .ginput_amount");
if(productField.length > 0){
price = productField.val();
//If field is hidden by conditional logic, don't count it for the total
if(gformIsHidden(productField)){
price = 0;
}
}
else
{
productField = jQuery(".gfield_product" + suffix + " select, .gfield_product" + suffix + " input:checked, .gfield_donation" + suffix + " select, .gfield_donation" + suffix + " input:checked");
var val = productField.val();
if(val){
val = val.split("|");
price = val.length > 1 ? val[1] : 0;
}
//If field is hidden by conditional logic, don't count it for the total
if(gformIsHidden(productField))
price = 0;
}
var c = new Currency(gf_global.gf_currency_config);
price = c.toNumber(price);
return price === false ? 0 : price;
}
function gformFormatMoney(text, isNumeric){
if(!gf_global.gf_currency_config)
return text;
var currency = new Currency(gf_global.gf_currency_config);
return currency.toMoney(text, isNumeric);
}
function gformFormatPricingField(element){
if(gf_global.gf_currency_config){
var currency = new Currency(gf_global.gf_currency_config);
var price = currency.toMoney(jQuery(element).val());
jQuery(element).val(price);
}
}
function gformToNumber(text){
var currency = new Currency(gf_global.gf_currency_config);
return currency.toNumber(text);
}
function gformGetPriceDifference(currentPrice, newPrice){
//getting price difference
var diff = parseFloat(newPrice) - parseFloat(currentPrice);
price = gformFormatMoney(diff, true);
if(diff > 0)
price = "+" + price;
return price;
}
function gformGetOptionLabel(element, selected_value, current_price, form_id, field_id){
element = jQuery(element);
var price = gformGetPrice(selected_value);
var current_diff = element.attr('price');
var original_label = element.html().replace(/<span(.*)<\/span>/i, "").replace(current_diff, "");
var diff = gformGetPriceDifference(current_price, price);
diff = gformToNumber(diff) == 0 ? "" : " " + diff;
element.attr('price', diff);
//don't add <span> for drop down items (not supported)
var price_label = element[0].tagName.toLowerCase() == "option" ? " " + diff : "<span class='ginput_price'>" + diff + "</span>";
var label = original_label + price_label;
//calling hook to allow for custom option formatting
if(window["gform_format_option_label"])
label = gform_format_option_label(label, original_label, price_label, current_price, price, form_id, field_id);
return label;
}
function gformGetProductIds(parent_class, element){
var classes = jQuery(element).hasClass(parent_class) ? jQuery(element).attr("class").split(" ") : jQuery(element).parents("." + parent_class).attr("class").split(" ");
for(var i=0; i<classes.length; i++){
if(classes[i].substr(0, parent_class.length) == parent_class && classes[i] != parent_class)
return {formId: classes[i].split("_")[2], productFieldId: classes[i].split("_")[3]};
}
return {formId:0, fieldId:0};
}
function gformGetPrice(text){
var val = text.split("|");
var currency = new Currency(gf_global.gf_currency_config);
if(val.length > 1 && currency.toNumber(val[1]) !== false)
return currency.toNumber(val[1]);
return 0;
}
function gformRoundPrice(price){
var currency = new Currency(gf_global.gf_currency_config);
var roundedPrice = currency.numberFormat( price, currency.currency['decimals'], '.', '' );
return parseFloat( roundedPrice );
}
function gformRegisterPriceField(item){
if(!_gformPriceFields[item.formId])
_gformPriceFields[item.formId] = new Array();
//ignore price fields that have already been registered
for(var i=0; i<_gformPriceFields[item.formId].length; i++)
if(_gformPriceFields[item.formId][i] == item.productFieldId)
return;
//registering new price field
_gformPriceFields[item.formId].push(item.productFieldId);
}
function gformInitPriceFields(){
jQuery(".gfield_price").each(function(){
var productIds = gformGetProductIds("gfield_price", this);
gformRegisterPriceField(productIds);
jQuery( this ).on( 'change', 'input[type="text"], input[type="number"], select', function() {
var productIds = gformGetProductIds("gfield_price", this);
if(productIds.formId == 0)
productIds = gformGetProductIds("gfield_shipping", this);
jQuery(document).trigger('gform_price_change', [productIds, this]);
gformCalculateTotalPrice(productIds.formId);
});
jQuery( this ).on( 'click', 'input[type="radio"], input[type="checkbox"]', function() {
var productIds = gformGetProductIds("gfield_price", this);
if(productIds.formId == 0)
productIds = gformGetProductIds("gfield_shipping", this);
jQuery(document).trigger('gform_price_change', [productIds, this]);
gformCalculateTotalPrice(productIds.formId);
});
});
for(formId in _gformPriceFields){
//needed when implementing for in loops
if(!_gformPriceFields.hasOwnProperty(formId))
continue;
gformCalculateTotalPrice(formId);
}
}
//-------------------------------------------
//---------- PASSWORD -----------------------
//-------------------------------------------
function gformShowPasswordStrength(fieldId){
var password = document.getElementById( fieldId ).value,
confirm = document.getElementById( fieldId + '_2' ) ? document.getElementById( fieldId + '_2' ).value : '';
var result = gformPasswordStrength( password, confirm ),
text = window[ 'gf_text' ][ "password_" + result ],
resultClass = result === 'unknown' ? 'blank' : result;
jQuery("#" + fieldId + "_strength").val(result);
jQuery("#" + fieldId + "_strength_indicator").removeClass("blank mismatch short good bad strong").addClass(resultClass).html(text);
}
// Password strength meter
function gformPasswordStrength( password1, password2 ) {
if ( password1.length <= 0 ) {
return 'blank';
}
var strength = wp.passwordStrength.meter( password1, wp.passwordStrength.userInputBlacklist(), password2 );
switch ( strength ) {
case -1:
return 'unknown';
case 2:
return 'bad';
case 3:
return 'good';
case 4:
return 'strong';
case 5:
return 'mismatch';
default:
return 'short';
}
}
function gformToggleShowPassword( fieldId ) {
var $password = jQuery( '#' + fieldId ),
$button = $password.parent().find( 'button' ),
$icon = $button.find( 'span' ),
currentType = $password.attr( 'type' );
switch ( currentType ) {
case 'password':
$password.attr( 'type', 'text' );
$button.attr( 'label', $button.attr( 'data-label-hide' ) );
$icon.removeClass( 'dashicons-hidden' ).addClass( 'dashicons-visibility' );
break;
case 'text':
$password.attr( 'type', 'password' );
$button.attr( 'label', $button.attr( 'data-label-show' ) );
$icon.removeClass( 'dashicons-visibility' ).addClass( 'dashicons-hidden' );
break;
}
}
//----------------------------
//------ CHECKBOX FIELD ------
//----------------------------
function gformToggleCheckboxes( toggleCheckbox ) {
var $toggle = jQuery( toggleCheckbox ).parent(),
$toggleLabel = $toggle.find( 'label' ),
$checkboxes = $toggle.parent().find( 'li:not( .gchoice_select_all )' ),
formId = gf_get_form_id_by_html_id( $toggle.parents( '.gfield' ).attr( 'id' ) ),
calcObj = rgars( window, 'gf_global/gfcalc/' + formId );
// Set checkboxes state.
$checkboxes.each( function() {
// Set checkbox checked state.
jQuery( 'input[type="checkbox"]', this ).prop( 'checked', toggleCheckbox.checked ).trigger( 'change' );
// Execute onclick event.
if ( typeof jQuery( 'input[type="checkbox"]', this )[0].onclick === 'function' ) {
jQuery( 'input[type="checkbox"]', this )[0].onclick();
}
} );
// Change toggle label.
if ( toggleCheckbox.checked ) {
$toggleLabel.html( $toggleLabel.data( 'label-deselect' ) );
} else {
$toggleLabel.html( $toggleLabel.data( 'label-select' ) );
}
if ( calcObj ) {
calcObj.runCalcs( formId, calcObj.formulaFields );
}
}
//----------------------------
//------ LIST FIELD ----------
//----------------------------
function gformAddListItem( addButton, max ) {
var $addButton = jQuery( addButton );
if( $addButton.hasClass( 'gfield_icon_disabled' ) ) {
return;
}
var $group = $addButton.parents( '.gfield_list_group' ),
$clone = $group.clone(),
$container = $group.parents( '.gfield_list_container' ),
tabindex = $clone.find( ':input:last' ).attr( 'tabindex' );
// reset all inputs to empty state
$clone
.find( 'input, select, textarea' ).attr( 'tabindex', tabindex )
.not( ':checkbox, :radio' ).val( '' );
$clone.find( ':checkbox, :radio' ).prop( 'checked', false );
$clone = gform.applyFilters( 'gform_list_item_pre_add', $clone, $group );
$group.after( $clone );
gformToggleIcons( $container, max );
gformAdjustClasses( $container );
gform.doAction( 'gform_list_post_item_add', $clone, $container );
}
function gformDeleteListItem( deleteButton, max ) {
var $deleteButton = jQuery( deleteButton ),
$group = $deleteButton.parents( '.gfield_list_group' ),
$container = $group.parents( '.gfield_list_container' );
$group.remove();
gformToggleIcons( $container, max );
gformAdjustClasses( $container );
gform.doAction( 'gform_list_post_item_delete', $container );
}
function gformAdjustClasses( $container ) {
var $groups = $container.find( '.gfield_list_group' );
$groups.each( function( i ) {
var $group = jQuery( this ),
oddEvenClass = ( i + 1 ) % 2 == 0 ? 'gfield_list_row_even' : 'gfield_list_row_odd';
$group.removeClass( 'gfield_list_row_odd gfield_list_row_even' ).addClass( oddEvenClass );
} );
}
function gformToggleIcons( $container, max ) {
var groupCount = $container.find( '.gfield_list_group' ).length,
$addButtons = $container.find( '.add_list_item' );
$container.find( '.delete_list_item' ).css( 'visibility', groupCount == 1 ? 'hidden' : 'visible' );
if ( max > 0 && groupCount >= max ) {
// store original title in the add button
$addButtons.data( 'title', $container.find( '.add_list_item' ).attr( 'title' ) );
$addButtons.addClass( 'gfield_icon_disabled' ).attr( 'title', '' );
} else if( max > 0 ) {
$addButtons.removeClass( 'gfield_icon_disabled' );
if( $addButtons.data( 'title' ) ) {
$addButtons.attr( 'title', $addButtons.data( 'title' ) );
}
}
}
//-----------------------------------
//--------- REPEATER FIELD ----------
//-----------------------------------
function gformAddRepeaterItem( addButton, max ) {
var $addButton = jQuery( addButton );
if( $addButton.hasClass( 'gfield_icon_disabled' ) ) {
return;
}
var $item = $addButton.closest( '.gfield_repeater_item' ),
$clone = $item.clone(),
$container = $item.closest( '.gfield_repeater_container' ),
tabindex = $clone.find( ':input:last' ).attr( 'tabindex' );
// reset all inputs to empty state
$clone
.find( 'input[type!="hidden"], select, textarea' ).attr( 'tabindex', tabindex )
.not( ':checkbox, :radio' ).val( '' );
$clone.find( ':checkbox, :radio' ).prop( 'checked', false );
$clone.find('.validation_message').remove();
$clone = gform.applyFilters( 'gform_repeater_item_pre_add', $clone, $item );
$item.after( $clone );
var $cells = $clone.children('.gfield_repeater_cell');
$cells.each(function () {
var $subContainer = jQuery(this).find('.gfield_repeater_container').first();
if ($subContainer.length > 0) {
resetContainerItems = function ($c) {
$c.children('.gfield_repeater_items').children('.gfield_repeater_item').each(function (i) {
var $children = jQuery(this).children('.gfield_repeater_cell');
$children.each(function () {
var $subSubContainer = jQuery(this).find('.gfield_repeater_container').first();
if ($subSubContainer.length > 0) {
resetContainerItems($subSubContainer);
}
})
})
$c.children('.gfield_repeater_items').children('.gfield_repeater_item').not(':first').remove();
}
resetContainerItems($subContainer);
}
})
gformResetRepeaterAttributes($container);
if ( typeof gformInitDatepicker == 'function' ) {
$container.find('.ui-datepicker-trigger').remove();
$container.find('.hasDatepicker').removeClass('hasDatepicker');
gformInitDatepicker();
}
gformBindFormatPricingFields();
gformToggleRepeaterButtons( $container, max );
gform.doAction('gform_repeater_post_item_add', $clone, $container);
}
function gformDeleteRepeaterItem(deleteButton, max) {
var $deleteButton = jQuery(deleteButton),
$group = $deleteButton.closest('.gfield_repeater_item'),
$container = $group.closest('.gfield_repeater_container');
$group.remove();
gformResetRepeaterAttributes($container);
gformToggleRepeaterButtons($container, max);
gform.doAction('gform_repeater_post_item_delete', $container);
}
function gformResetRepeaterAttributes($container, depth, row) {
var cachedRadioSelection = null;
if (typeof depth === 'undefined') {
depth = 0;
}
if (typeof row === 'undefined') {
row = 0;
}
$container.children('.gfield_repeater_items').children('.gfield_repeater_item').each(function () {
var $children = jQuery(this).children('.gfield_repeater_cell');
$children.each(function () {
var $cell = jQuery(this);
var $subContainer = jQuery(this).find('.gfield_repeater_container').first();
if ($subContainer.length > 0) {
var newDepth = depth + 1;
gformResetRepeaterAttributes($subContainer, newDepth, row);
return;
}
jQuery(this).find('input, select, textarea, :checkbox, :radio').each(function () {
var $this = jQuery(this);
var name = $this.attr('name');
if ( typeof name == 'undefined' ) {
return;