Passed
Pull Request — master (#132)
by
unknown
15:02 queued 06:44
created

qucosa.js ➔ ... ➔ fieldset.each   D

Complexity

Conditions 13
Paths 36

Size

Total Lines 44
Code Lines 36

Duplication

Lines 44
Ratio 100 %

Importance

Changes 3
Bugs 1 Features 0
Metric Value
cc 13
eloc 36
c 3
b 1
f 0
nc 36
nop 0
dl 44
loc 44
rs 4.2

How to fix   Complexity   

Complexity

Complex classes like qucosa.js ➔ ... ➔ fieldset.each often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
/**
2
 * This file is part of the TYPO3 CMS project.
3
 *
4
 * It is free software; you can redistribute it and/or modify it under
5
 * the terms of the GNU General Public License, either version 2
6
 * of the License, or any later version.
7
 *
8
 * For the full copyright and license information, please read the
9
 * LICENSE.txt file that was distributed with this source code.
10
 *
11
 * The TYPO3 project - inspiring people to share!
12
 */
13 View Code Duplication
$(document).ready(function() {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
14
    jQuery('#new-document-form').trigger('reset');
15
    documentListConfirmDialog('#confirmDiscard');
16
    documentListConfirmDialog('#confirmPublish');
17
    documentListConfirmDialog('#confirmUpdate');
18
    documentListConfirmDialog('#confirmActivate');
19
    documentListConfirmDialog('#confirmInactivate');
20
    documentListConfirmDialog('#confirmRestore');
21
    documentListConfirmDialog('#confirmDelete');
22
    datepicker();
23
    jQuery('[data-toggle="tooltip"]').tooltip();
24
    var $disableForm = jQuery('form[data-disabled]').attr('data-disabled');
25
    if ($disableForm) {
26
        jQuery('.input-field').each(function() {
27
            jQuery(this).attr('disabled', 'disabled');
28
        });
29
        jQuery('.rem_file_group').each(function() {
30
            jQuery(this).attr('disabled', 'disabled');
31
        });
32
        jQuery('.add_file_group').each(function() {
33
            jQuery(this).attr('disabled', 'disabled');
34
        });
35
        jQuery('.input_file_upload').each(function() {
36
            jQuery(this).attr('disabled', 'disabled');
37
        });
38
        jQuery('.add_field').each(function() {
39
            jQuery(this).attr('disabled', 'disabled');
40
        });
41
        jQuery('.add_group').each(function() {
42
            jQuery(this).attr('disabled', 'disabled');
43
        });
44
        jQuery('.rem_field').each(function() {
45
            jQuery(this).attr('disabled', 'disabled');
46
        });
47
        jQuery('.rem_group').each(function() {
48
            jQuery(this).attr('disabled', 'disabled');
49
        });
50
        jQuery('.fill_out_service_urn').each(function() {
51
            jQuery(this).attr('disabled', 'disabled');
52
        });
53
    }
54
    buttonFillOutServiceUrn();
55
    jQuery(".tx-dpf").on("click", ".rem_group", function() {
56
        jQuery(this).parents('fieldset').fadeOut(300, function() {
57
            jQuery(this).remove();
58
        });
59
        return false;
60
    });
61
    jQuery(".tx-dpf").on("click", ".rem_file_group", deleteFile);
62
    jQuery(".tx-dpf").on("click", ".rem_secondary_upload", function() {
63
        var dataIndex = jQuery(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
64
        jQuery(this).parents('.fs_file_group').fadeOut(300, function() {
65
            jQuery(this).remove();
66
        });
67
        return false;
68
    });
69
    jQuery(".tx-dpf").on("click", ".rem_field", function() {
70
        var dataIndex = jQuery(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
71
        var dataField = jQuery(this).data("field");
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
72
        jQuery(this).parents('.form-group').fadeOut(300, function() {
73
            jQuery(this).remove();
74
        });
75
        return false;
76
    });
77
    // Add metadata group
78
    jQuery(".tx-dpf").on("click", ".add_group", addGroup);
79
    jQuery(".tx-dpf").on("click", ".add_file_group", addGroup);
80
    jQuery(".tx-dpf").on("click", ".add_field", addField);
81
    jQuery(".tx-dpf").on("click", ".fill_out_service_urn", fillOutServiceUrn);
82
    jQuery(".tx-dpf").on("keyup", "input.urn", buttonFillOutServiceUrn);
83
    jQuery(".tx-dpf").on("click", "#next", continuousScroll);
84
    jQuery(".form-submit").on("click", "#save", validateFormAndSave);
85
    jQuery(".form-submit").on("click", "#validate", validateFormOnly);
86
87
    // hide 'more results' link
88
    var countResults = $('#search-results :not(thead) tr').length;
89
    var resultCount = $('#next').data('resultCount');
90
91
    if (countResults < resultCount) {
92
        jQuery("#next").hide();
93
    }
94
95
    addRemoveFileButton();
96
97
    previousNextFormPage();
98
99
    var gnd = jQuery('.gnd');
100
    if(gnd.length > 0) {
101
        gnd.each(function() {
102
            setGndAutocomplete(jQuery(this).data("field"),  jQuery(this).data("groupindex"));
103
        });
104
    }
105
106
    inputWithOptions();
107
108
});
109
110
var validateFormAndSave = function() {
111
    jQuery("#validDocument").val("0");
112
    if (validateForm()) {
113
        jQuery("#validDocument").val("1");
114
115
        jQuery("#new-document-form #save").prop("disabled", true);
116
117
        jQuery('#new-document-form').submit();
118
119
        return true;
120
    }
121
    return false;
122
}
123
var validateFormOnly = function() {
124
    if (validateForm()) {
125
        showFormSuccess();
126
    }
127
    return false;
128
}
129
var validateForm = function() {
130
    var error = false;
131
    jQuery('span.mandatory-error').remove();
132
    jQuery('div.alert').remove();
133
    jQuery('.tx-dpf-tabs li a').each(function() {
134
        jQuery(this).removeClass('mandatory-error');
135
    });
136
    // check mandatory groups
137
    jQuery('fieldset[data-mandatory=1]').each(function() {
138
        var fieldset = jQuery(this);
139
        if (hasMandatoryInputs(fieldset)) {
140
            if (checkMandatoryInputs(fieldset)) {
141
                jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
142
                showFormError();
143
                error = true;
144
                markPage(fieldset, true);
145
            }
146
        } else {
147
            if (checkFilledInputs(fieldset)) {
148
                jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_one_required + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_one_required seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_one_required */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
149
                showFormError();
150
                error = true;
151
                markPage(fieldset, true);
152
                error = true;
153
            }
154
        }
155
    });
156
    jQuery('fieldset[id=primary_file]').each(function() {
157
        var fieldset = jQuery(this);
158
        if (checkPrimaryFile(fieldset)) {
159
            jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertBefore(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
160
            showFormError();
161
            error = true;
162
            markPage(fieldset, true);
163
        }
164
    });
165
    // check non mandatory groups
166
    jQuery('fieldset[data-mandatory=""]').each(function() {
167
        var fieldset = jQuery(this);
168
        var filledInputs = 0;
169
        jQuery(this).find('.input-field').each(function() {
170
            if (jQuery(this).val() && jQuery(this).attr('data-default') != '1') {
171
                filledInputs++;
172
            }
173
            jQuery(this).removeClass('mandatory-error');
174
        });
175
        // if there are fields with a value then mandatory fields
176
        // are relevant.
177
        if (filledInputs) {
178
            if (checkMandatoryInputs(fieldset)) {
179
                jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_group_mandatory + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_group_mandatory seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_group_mandatory */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
180
                showFormError();
181
                markPage(fieldset, true);
182
                error = true;
183
            }
184
        }
185
    });
186
    jQuery('fieldset').each(function() {
187
        var fieldset = jQuery(this);
188
        fieldset.find('.input-field').each(function() {
189
            jQuery(this).removeClass('invalid-error');
190
            var validation = jQuery(this).attr('data-regexp');
191
            if (jQuery(this).val() && jQuery(this).val().length > 0 && validation && validation.length > 0) {
192
                try {
193
                    var regexp = new RegExp(validation);
194
                    var res = jQuery(this).val().match(regexp);
195
                    if (!(res && res.length == 1 && res[0] == jQuery(this).val())) {
0 ignored issues
show
Best Practice introduced by
Comparing res.length to 1 using the == operator is not safe. Consider using === instead.
Loading history...
196
                        jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_invalid seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_invalid */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
197
                        jQuery(this).addClass('invalid-error');
198
                        showFormError();
199
                        markPage(fieldset, true);
200
                        error = true;
201
                    }
202
                } catch (err) {
203
                    jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
204
                    jQuery(this).addClass('invalid-error');
205
                    showFormError();
206
                    markPage(fieldset, true);
207
                    error = true;
208
                }
209
            } else {
210
                var validateDate = jQuery(this).attr('data-datatype') == 'DATE';
211
                if (jQuery(this).val() && jQuery(this).val().length > 0 && validateDate && !isDate(jQuery(this).val())) {
212
                    jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + jQuery(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
213
                    jQuery(this).addClass('invalid-error');
214
                    showFormError();
215
                    markPage(fieldset, true);
216
                    error = true;
217
                }
218
            }
219
220
            var maxLength = jQuery(this).attr('data-maxlength');
221
            if (maxLength && maxLength > 0) {
222
                if (jQuery(this).val().length > maxLength) {
223
                    var max_lengrth_msg = form_error_msg_field_max_length.replace(/%s/gi, maxLength);
0 ignored issues
show
Bug introduced by
The variable form_error_msg_field_max_length seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_field_max_length */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
224
                    jQuery('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + max_lengrth_msg + jQuery(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
225
                    jQuery(this).addClass('invalid-error');
226
                    showFormError();
227
                    markPage(fieldset, true);
228
                    error = true;
229
                }
230
            }
231
        });
232
    });
233
234
    return !error;
235
}
236
var showFormError = function() {
237
    jQuery('.tx-dpf div.alert-danger').remove();
238
    jQuery('<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg + '</div>').insertBefore(jQuery('.tx-dpf form').first());
0 ignored issues
show
Bug introduced by
The variable form_error_msg seems to be never declared. If this is a global, consider adding a /** global: form_error_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
239
    jQuery("html, body").animate({
240
        scrollTop: 0
241
    }, 200);
242
}
243
var showFormSuccess = function() {
244
    jQuery('.tx-dpf div.alert-danger').remove();
245
    jQuery('<div class="alert alert-success" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_success_msg + '</div>').insertBefore(jQuery('.tx-dpf form').first());
0 ignored issues
show
Bug introduced by
The variable form_success_msg seems to be never declared. If this is a global, consider adding a /** global: form_success_msg */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
246
    jQuery("html, body").animate({
247
        scrollTop: 0
248
    }, 200);
249
}
250
var hasMandatoryInputs = function(fieldset) {
251
    var inputs = fieldset.find(".input-field[data-mandatory=1]");
252
    return inputs.length > 0
253
}
254
var markPage = function(fieldset, error) {
255
    var pageId = fieldset.parent().attr('id');
256
    var page = jQuery('.tx-dpf-tabs li a[href=#' + pageId + ']');
257
    if (error) {
258
        page.addClass('mandatory-error');
259
    } else {
260
        page.removeClass('mandatory-error');
261
    }
262
}
263
var checkMandatoryInputs = function(fieldset) {
264
    var mandatoryError = false;
265
    fieldset.find(".input-field[data-mandatory=1]").each(function() {
266
        var id = jQuery(this).attr('id');
267
        if ((jQuery(this).attr('type') != 'checkbox' && !jQuery(this).val()) || (jQuery(this).attr('type') == 'checkbox' && (jQuery("#" + id + ":checked").length != 1 || !jQuery("#" + id + ":checked")))) {
0 ignored issues
show
Best Practice introduced by
Comparing jQuery("#" + id + ":checked").length to 1 using the != operator is not safe. Consider using !== instead.
Loading history...
268
            mandatoryError = mandatoryError || true;
269
            jQuery(this).addClass('mandatory-error');
270
        } else {
271
            jQuery(this).removeClass('mandatory-error');
272
        }
273
    });
274
    return mandatoryError;
275
}
276
var checkPrimaryFile = function(fieldset) {
277
    var mandatoryError = false;
278
    fieldset.find("input#inp_primaryFile[data-virtual!=1]").each(function() {
279
        if (!jQuery(this).val()) {
280
            mandatoryError = mandatoryError || true;
281
            jQuery(this).addClass('mandatory-error');
282
        } else {
283
            jQuery(this).removeClass('mandatory-error');
284
        }
285
    });
286
    return mandatoryError;
287
}
288
var checkFilledInputs = function(fieldset) {
289
    var filledInputs = 0;
290
    fieldset.find('.input-field').each(function() {
291
        if (jQuery(this).val()) {
292
            filledInputs++;
293
        }
294
        jQuery(this).removeClass('mandatory-error');
295
    });
296
    return filledInputs < 1;
297
}
298
var addGroup = function() {
299
    var element = jQuery(this);
300
    // Get the group uid
301
    var dataGroup = jQuery(this).attr('data-group');
302
    // Number of the next group item
303
    var groupIndex = parseInt(jQuery(this).attr('data-index')) + 1;
304
    jQuery(this).attr('data-index', groupIndex);
305
    var ajaxURL = jQuery(this).attr('data-ajax');
306
    var params = buildAjaxParams(ajaxURL, "groupIndex", groupIndex);
307
    //do the ajax-call
308
    jQuery.post(ajaxURL, params, function(group) {
309
        var group = jQuery(group).find("fieldset");
310
        // add the new group
311
        jQuery(group).css({
312
            'display': 'none'
313
        }).insertAfter(jQuery('fieldset[data-group="' + dataGroup + '"]').last());
314
        var height = jQuery('fieldset[data-group="' + dataGroup + '"]').last().outerHeight(true)
315
        jQuery('html, body').animate({
316
            scrollTop: element.offset().top - height
317
        }, 400, function() {
318
            jQuery(group).fadeIn();
319
        });
320
        buttonFillOutServiceUrn();
321
        datepicker();
322
        addRemoveFileButton();
323
324
        // gnd autocomplete for new groups
325
        var gndField = jQuery(group).find('.gnd');
326
        if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
327
            setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
328
        }
329
    });
330
    return false;
331
}
332
var addField = function() {
333
    var addButton = jQuery(this);
334
    // Get the field uid
335
    var dataField = jQuery(this).attr('data-field');
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
336
    // Number of the next field item
337
    var fieldIndex = parseInt(jQuery(this).attr('data-index')) + 1;
338
    jQuery(this).attr('data-index', fieldIndex);
339
    var ajaxURL = jQuery(this).attr('data-ajax');
340
    var params = buildAjaxParams(ajaxURL, "fieldIndex", fieldIndex);
341
    //do the ajax-call
342
    jQuery.post(ajaxURL, params, function(element) {
343
        var field = jQuery(element).find("#new-element").children();
344
        jQuery(field).css({
345
            'display': 'none'
346
        }).insertBefore(addButton).fadeIn();
347
        buttonFillOutServiceUrn();
348
        datepicker();
349
350
        // gnd autocomplete for new fields
351
        var gndField = jQuery(element).find('.gnd');
352
        if (gndField.length != 0) {
0 ignored issues
show
Best Practice introduced by
Comparing gndField.length to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
353
            setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
354
        }
355
    });
356
    return false;
357
}
358
var deleteFile = function() {
359
    var fileGroup = jQuery(this).parent().parent();
360
    var ajaxURL = jQuery(this).attr('data-ajax');
361
    var params = {}
362
        //do the ajax-call
363
    jQuery.post(ajaxURL, params, function(element) {
364
        var field = jQuery(element).find("#new-element").children();
365
        jQuery(fileGroup).replaceWith(field);
366
    });
367
    return false;
368
}
369
370
function buildAjaxParams(ajaxURL, indexName, index) {
371
    var res = ajaxURL.match(/(tx\w+?)%/); // get param name
372
    var params = {};
373
    var indexParam = {};
374
    if (res && res[1]) {
375
        indexParam[indexName] = index;
376
        params[res[1]] = indexParam;
377
    }
378
    return params;
379
}
380
var fillOutServiceUrn = function() {
381
    // Get the field uid
382
    var fieldUid = jQuery(this).attr('data-field');
383
    var fieldIndex = jQuery(this).attr('data-index');
384
    var groupUid = jQuery(this).attr('data-group');
385
    var groupIndex = jQuery(this).attr('data-groupindex');
386
    var ajaxURL = jQuery(this).attr('data-ajax');
387
    var qucosaId = jQuery('#qucosaid').val();
388
    var params = {};
0 ignored issues
show
Unused Code introduced by
The assignment to variable params seems to be never used. Consider removing it.
Loading history...
389
    if (qucosaId) {
390
        params = buildAjaxParams(ajaxURL, "qucosaId", qucosaId);
391
    } else {
392
        params = buildAjaxParams(ajaxURL, "qucosaId", "");
393
    }
394
395
    var group = $(this).closest(".fs_group");
396
397
    //do the ajax-call
398
    jQuery.getJSON(ajaxURL, params, function(element) {
399
400
        group.find('.alert-filloutservice-urn').remove();
401
402
        if (element.error) {
403
            var errorMsg = $('<div class="alert alert-danger alert-filloutservice-urn" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg_filloutservice + '</div>');
0 ignored issues
show
Bug introduced by
The variable form_error_msg_filloutservice seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_filloutservice */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
404
            errorMsg.insertAfter(group.find('legend'));
405
            $("html, body").animate({scrollTop: group.offset().top}, 200);
406
        } else {
407
            jQuery('#qucosaid').val(element.qucosaId);
408
            jQuery('#qucosaUrn').val(element.value);
409
            var inputField = jQuery('.input-field[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"][data-group="' + groupUid + '"][data-groupindex="' + groupIndex + '"]');
410
            inputField.val(element.value);
411
            buttonFillOutServiceUrn();
412
        }
413
    });
414
    return false;
415
}
416
var buttonFillOutServiceUrn = function() {
417
    jQuery('input.urn').each(function() {
418
        var fieldUid = jQuery(this).attr('data-field');
419
        var fieldIndex = jQuery(this).attr('data-index');
420
        var groupUid = jQuery(this).attr('data-group');
0 ignored issues
show
Unused Code introduced by
The variable groupUid seems to be never used. Consider removing it.
Loading history...
421
        var groupIndex = jQuery(this).attr('data-groupindex');
0 ignored issues
show
Unused Code introduced by
The variable groupIndex seems to be never used. Consider removing it.
Loading history...
422
        var fillOutButton = jQuery('.fill_out_service_urn[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"]');
423
        if ((jQuery(this).val() && jQuery(this).val().length > 0) || hasQucosaUrn()) {
424
            fillOutButton.hide();
425
        } else {
426
            fillOutButton.show();
427
        }
428
    });
429
    return false;
430
}
431
var hasQucosaUrn = function() {
432
    var result = false;
433
    var qucosaUrn = jQuery('#qucosaUrn').val();
434
    jQuery('input.urn').each(function() {
435
        var currentUrn = jQuery(this).val();
436
        if (currentUrn && qucosaUrn && (currentUrn == qucosaUrn)) {
437
            result = result || true;
438
        }
439
    });
440
    return result;
441
}
442
var continuousScroll = function() {
443
    var ajaxURL = jQuery("#next").attr('href');
444
    jQuery.ajax({
445
        url: ajaxURL,
446
        success: function(html) {
447
            if (html) {
448
                jQuery(html).find("table tbody tr").each(function() {
449
                    jQuery("#search-results tbody tr").last().parent().append(this);
450
                });
451
                if (jQuery(html).find("table tbody tr").length <= 0) {
452
                    jQuery("#next").hide();
453
                }
454
            } else {
455
                jQuery("#next").hide();
456
            }
457
        }
458
    });
459
    return false;
460
}
461
$(window).scroll(function() {
462
    if ($(this).scrollTop() > 330) {
463
        $(".tx-dpf-tab-container").addClass("sticky");
464
    } else {
465
        $(".tx-dpf-tab-container").removeClass("sticky");
466
    }
467
});
468
var datepicker = function() {
469
    var language = jQuery('div.tx-dpf[data-language]').first().attr('data-language');
470
    if (!language) language = "en";
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
471
    jQuery('.datetimepicker').datetimepicker({
472
        useCurrent: false,
473
        format: 'DD.MM.YYYY',
474
        locale: language,
475
        keepInvalid: true
476
    }).on("keydown", function(e){
477
        if (e.which == 13) {
478
            $('.datetimepicker').closest('form').submit();
479
        }
480
    });
481
}
482
var isDate = function(value) {
483
    if (value == '') return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
484
    var rxDatePattern = /^(\d{1,2})(\.)(\d{1,2})(\.)(\d{4})$/; //Declare Regex
485
    var dtArray = value.match(rxDatePattern); // is format OK?
486
    if (dtArray == null) return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
Best Practice introduced by
Comparing dtArray to null using the == operator is not safe. Consider using === instead.
Loading history...
487
    //Checks for mm/dd/yyyy format.
488
    var dtMonth = dtArray[3];
489
    var dtDay = dtArray[1];
490
    var dtYear = dtArray[5];
491
    if (dtMonth < 1 || dtMonth > 12) {
492
        return false;
493
    } else if (dtDay < 1 || dtDay > 31) {
494
        return false;
495
    } else if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) {
496
        return false;
497
    } else if (dtMonth == 2) {
498
        var isleap = (dtYear % 4 == 0 && (dtYear % 100 != 0 || dtYear % 400 == 0));
0 ignored issues
show
Best Practice introduced by
Comparing dtYear % 100 to 0 using the != operator is not safe. Consider using !== instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 400 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
Best Practice introduced by
Comparing dtYear % 4 to 0 using the == operator is not safe. Consider using === instead.
Loading history...
499
        if (dtDay > 29 || (dtDay == 29 && !isleap)) return false;
0 ignored issues
show
Coding Style Best Practice introduced by
Curly braces around statements make for more readable code and help prevent bugs when you add further statements.

Consider adding curly braces around all statements when they are executed conditionally. This is optional if there is only one statement, but leaving them out can lead to unexpected behaviour if another statement is added later.

Consider:

if (a > 0)
    b = 42;

If you or someone else later decides to put another statement in, only the first statement will be executed.

if (a > 0)
    console.log("a > 0");
    b = 42;

In this case the statement b = 42 will always be executed, while the logging statement will be executed conditionally.

if (a > 0) {
    console.log("a > 0");
    b = 42;
}

ensures that the proper code will be executed conditionally no matter how many statements are added or removed.

Loading history...
500
    }
501
    return true;
502
}
503
var documentListConfirmDialog = function(dialogId) {
504
    jQuery(dialogId).modal({
505
        show: false,
506
        backdrop: 'static'
507
    });
508
    jQuery(dialogId).on('show.bs.modal', function(e) {
509
        jQuery(this).find('#discardDocument').attr('href', jQuery(e.relatedTarget).attr('href'));
510
        var bodyText = jQuery(this).find('.modal-body p').html();
511
        var title = jQuery(e.relatedTarget).attr('data-documenttitle');
512
        jQuery(this).find('.modal-body p').html(bodyText.replace('%s', title));
513
        jQuery(e.relatedTarget).parent().parent().addClass('danger marked-for-removal');
514
    });
515
    jQuery(dialogId).on('hidden.bs.modal', function(e) {
0 ignored issues
show
Unused Code introduced by
The parameter e is not used and could be removed.

This check looks for parameters in functions that are not used in the function body and are not followed by other parameters which are used inside the function.

Loading history...
516
        jQuery('.marked-for-removal').removeClass('danger marked-for-removal');
517
    });
518
}
519
520
function addRemoveFileButton() {
521
    $('.rem_file').unbind('click');
522
    $('.rem_file').bind('click', function (evt) {
523
        evt.preventDefault();
524
        $(this).siblings('.input_file_upload').val('');
525
    })
526
}
527
528
529
function gndNothingFound(fieldId, groupIndex) {
530
        var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
531
532
        if (gndInputField.data('old_gnd_field_value')) {
533
            gndInputField.val(gndInputField.data('old_gnd_field_value'));
534
        } else {
535
            gndInputField.val();
536
        }
537
538
        var gndFieldId = gndInputField.data('gndfield');
539
        var linkedGroupIndex = gndInputField.data('groupindex');
540
        var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
541
542
        if (gndLinkedInputField.data('old_gnd_field_id')) {
543
            gndLinkedInputField.val(gndLinkedInputField.data('old_gnd_field_id'));
544
        } else {
545
            gndLinkedInputField.val();
546
        }
547
548
        /** global: form_error_msg_nothing_found */
549
        jQuery('<div id="gnd-nothing-found" class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg_nothing_found + '</div>').insertBefore(gndInputField.closest('.form-container'));
0 ignored issues
show
Bug introduced by
The variable form_error_msg_nothing_found seems to be never declared. If this is a global, consider adding a /** global: form_error_msg_nothing_found */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
550
551
        gndInputField.bind("keypress click", function () {
552
            jQuery("#gnd-nothing-found").remove();
553
        });
554
555
    gndLinkedInputField.bind("keypress click", function () {
556
        jQuery("#gnd-nothing-found").remove();
557
    });
558
559
}
560
561
function setGndAutocomplete(fieldId, groupIndex) {
562
    // GND autocomplete
563
    var ajaxURL = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').attr('data-ajax');
564
565
    var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
566
    var gndFieldId = gndInputField.data('gndfield');
567
    var linkedGroupIndex = gndInputField.data('groupindex');
568
    var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
569
570
    gndInputField.attr('data-old_gnd_field_value',gndInputField.val());
571
    gndLinkedInputField.attr('data-old_gnd_field_id',gndLinkedInputField.val());
572
573
    // Get the name of the parameter array (tx_dpf_...),
574
    // the name depends on whether the call is from the frontend or the backend
575
    var res = ajaxURL.match(/(tx_dpf\w+?)%/);
576
    var paramName = "tx_dpf_qucosaform[search]";
577
    if (res && res[1]) {
578
        paramName = res[1]+"[search]";
579
    }
580
581
    $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').autocomplete({
582
        source: function (request, response) {
583
584
            $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val('');
585
586
            var requestData = {};
587
            requestData[paramName] = request.term.replace(" ", "+");
588
            $.ajax({
589
                type: 'POST',
590
                url: ajaxURL,
591
                data: requestData,
592
                dataType: 'json',
593
                timeout: 10000,
594
                success: function (data) {
595
                   if (data) {
596
                       response(data);
597
                   } else {
598
                       gndNothingFound(fieldId, groupIndex);
599
                       response([]);
600
                   }
601
                },
602
                error: function () {
603
                    gndNothingFound(fieldId, groupIndex);
604
                    response([]);
605
                }
606
            });
607
        },
608
        minLength: 3,
609
        select: function (event, ui) {
610
            gndFieldId = jQuery(event.target).data('gndfield');
611
            linkedGroupIndex = jQuery(event.target).data('groupindex');
612
            $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val(ui.item.gnd);
613
        },
614
    }).autocomplete( "instance" )._renderItem = function( ul, item ) {
615
        return $( "<li>" )
616
            .append( "<div class='gnd-autocomplete'><span class='gnd-value' style='display:none;'>" + item.value + "</span>" +
617
                "<span class='gnd-label'>" + item.label + "</span></div>"
618
            )
619
            .appendTo( ul );
620
    };
621
}
622
623
var previousNextFormPage = function() {
624
625
    $('.prev-next-buttons button').click(function (e) {
626
        var activePage = $('.tx-dpf-tabs').find('li.active');
627
        var newActivePage = activePage;
0 ignored issues
show
Unused Code introduced by
The assignment to variable newActivePage seems to be never used. Consider removing it.
Loading history...
628
629
        if ($(this).attr('id') == 'next-form-page') {
630
            newActivePage = activePage.next();
631
        } else {
632
            newActivePage = activePage.prev();
633
        }
634
635
        if (newActivePage.length > 0) {
636
            activePage.removeClass('active');
637
            activePage.find('a').attr('aria-expanded', 'false');
638
            $('.tab-content').find('div.active').removeClass('active');
639
640
            newActivePage.addClass('active');
641
            newActivePage.find('a').attr('aria-expanded', 'true');
642
            $('.tab-content').find(newActivePage.find('a').attr('href')).addClass('active');
643
644
            updatePrevNextButtons(newActivePage);
645
646
            $('html, body').animate({
647
                scrollTop:$('.tx-dpf').offset().top
648
            },'fast');
649
        }
650
651
        e.preventDefault();
652
653
    });
654
655
    updatePrevNextButtons($('.tx-dpf-tabs li.active'));
656
657
    $('.tx-dpf-tabs li').click(function(){
658
        updatePrevNextButtons($(this));
659
    });
660
661
}
662
663
var updatePrevNextButtons = function(activePage) {
664
665
    if (activePage.prev().length < 1) {
666
        $('#prev-form-page').addClass('disabled');
667
    } else {
668
        $('#prev-form-page').removeClass('disabled');
669
    }
670
    if (activePage.next().length < 1) {
671
        $('#next-form-page').addClass('disabled');
672
    } else {
673
        $('#next-form-page').removeClass('disabled');
674
    }
675
}
676
677
var inputWithOptions = function() {
678
679
    $.widget( "custom.dropdownoptions", {
680
        _create: function() {
681
682
            var availableTags = [];
683
            var test = this.element
0 ignored issues
show
Unused Code introduced by
The variable test seems to be never used. Consider removing it.
Loading history...
684
                .closest(".dropdown-options")
685
                .find(".dropdown-options-values li")
686
                .each(function(){
687
                    if (jQuery(this).text().length > 0) {
688
                        availableTags.push(jQuery(this).text());
689
                    }
690
                });
691
692
            this.element
693
                .addClass( ".dropdown-options-input" )
694
                .autocomplete({
695
                    minLength: 0,
696
                    source: availableTags
697
                });
698
699
            this._createShowAllButton();
700
        },
701
        _createShowAllButton: function() {
702
703
            var input = this.element;
704
705
            wasOpen = false;
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
706
707
            input
708
                .closest(".dropdown-options")
709
                .find(".dropdown-options-toggle")
710
                .on( "mousedown", function() {
711
                    wasOpen = input.autocomplete( "widget" ).is( ":visible" );
0 ignored issues
show
Bug introduced by
The variable wasOpen seems to be never declared. Assigning variables without defining them first makes them global. If this was intended, consider making it explicit like using window.wasOpen.
Loading history...
712
                })
713
                .on( "click", function() {
714
                    input.trigger( "focus" );
715
                    if ( wasOpen ) {
716
                        return;
717
                    }
718
                    input.autocomplete( "search", "" );
719
720
                });
721
            input
722
                .on( "click", function() {
723
                    input.autocomplete( "search", "" );
724
                });
725
        }
726
    });
727
728
    $( ".dropdown-options-input" ).dropdownoptions();
729
}