Passed
Pull Request — master (#126)
by
unknown
17:37
created

Resources/Public/JavaScript/QucosaBe.js   F

Complexity

Total Complexity 153
Complexity/F 1.84

Size

Lines of Code 715
Function Count 83

Duplication

Duplicated Lines 715
Ratio 100 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 0
eloc 462
nc 34836480
dl 715
loc 715
rs 2
c 5
b 0
f 0
wmc 153
mnd 3
bc 142
fnc 83
bpm 1.7108
cpm 1.8433
noi 32

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complexity

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Resources/Public/JavaScript/QucosaBe.js 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
14 View Code Duplication
define(['jquery', 'TYPO3/CMS/Dpf/jquery-ui','twbs/bootstrap-datetimepicker'], function($) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
15
16
    var documentListConfirmDialog = function(dialogId) {
17
        $(dialogId).modal({
18
            show: false,
19
            backdrop: 'static'
20
        });
21
        $(dialogId).on('show.bs.modal', function(e) {
22
            $(this).find('#discardDocument').attr('href', $(e.relatedTarget).attr('href'));
23
            var bodyText = $(this).find('.modal-body p').html();
24
            var title = $(e.relatedTarget).attr('data-documenttitle');
25
            $(this).find('.modal-body p').html(bodyText.replace('%s', title));
26
            $(e.relatedTarget).parent().parent().addClass('danger marked-for-removal');
27
        });
28
        $(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...
29
            $('.marked-for-removal').removeClass('danger marked-for-removal');
30
        });
31
    }
32
33
    var datepicker = function() {
34
        $(".datetimepicker").datetimepicker({
35
                useCurrent: false,
36
                keepInvalid: false,
37
                format: "DD.MM.YYYY"
38
        });
39
    }
40
41
    var buttonFillOutServiceUrn = function() {
42
        $('input.urn').each(function() {
43
            var fieldUid = $(this).attr('data-field');
44
            var fieldIndex = $(this).attr('data-index');
45
            var groupUid = $(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...
46
            var groupIndex = $(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...
47
            var fillOutButton = $('.fill_out_service_urn[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"]');
48
            if (($(this).val() && $(this).val().length > 0) || hasQucosaUrn()) {
49
                fillOutButton.hide();
50
            } else {
51
                fillOutButton.show();
52
            }
53
        });
54
        return false;
55
    }
56
57
    var hasQucosaUrn = function() {
58
        var result = false;
59
        var qucosaUrn = $('#qucosaUrn').val();
60
        $('input.urn').each(function() {
61
            var currentUrn = $(this).val();
62
            if (currentUrn && qucosaUrn && (currentUrn == qucosaUrn)) {
63
                result = result || true;
64
            }
65
        });
66
        return result;
67
    }
68
69
70
    var validateFormAndSave = function() {
71
        $("#validDocument").val("0");
72
        if (validateForm()) {
73
            $("#validDocument").val("1");
74
            $("#new-document-form #save").prop("disabled", true);
75
            $('#new-document-form').submit();
76
            return true;
77
        }
78
        return false;
79
    }
80
81
    var validateFormOnly = function() {
82
        if (validateForm()) {
83
            showFormSuccess();
84
        }
85
        return false;
86
    }
87
88
    var validateForm = function() {
89
        var error = false;
90
        $('span.mandatory-error').remove();
91
        $('div.alert').remove();
92
        $('.tx-dpf-tabs li a').each(function() {
93
            $(this).removeClass('mandatory-error');
94
        });
95
96
        // check mandatory groups
97
        $('fieldset[data-mandatory=1]').each(function() {
98
            var fieldset = $(this);
99
            if (hasMandatoryInputs(fieldset)) {
100
                if (checkMandatoryInputs(fieldset)) {
101
                    $('<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...
102
                    showFormError();
103
                    error = true;
104
                    markPage(fieldset, true);
105
                }
106
            } else {
107
                if (checkFilledInputs(fieldset)) {
108
                    $('<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...
109
                    showFormError();
110
                    error = true;
111
                    markPage(fieldset, true);
112
                    error = true;
113
                }
114
            }
115
        });
116
117
        $('fieldset[id=primary_file]').each(function() {
118
            var fieldset = $(this);
119
            if (checkPrimaryFile(fieldset)) {
120
                $('<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...
121
                showFormError();
122
                error = true;
123
                markPage(fieldset, true);
124
            }
125
        });
126
127
        // check non mandatory groups
128
        $('fieldset[data-mandatory=""]').each(function() {
129
            var fieldset = $(this);
130
            var filledInputs = 0;
131
            $(this).find('.input-field').each(function() {
132
                if ($(this).val() && $(this).attr('data-default') != '1') {
133
                    filledInputs++;
134
                }
135
                $(this).removeClass('mandatory-error');
136
            });
137
138
            // if there are fields with a value then mandatory fields
139
            // are relevant.
140
            if (filledInputs) {
141
                if (checkMandatoryInputs(fieldset)) {
142
                    $('<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...
143
                    showFormError();
144
                    markPage(fieldset, true);
145
                    error = true;
146
                    }
147
                }
148
        });
149
150
        $('fieldset').each(function() {
151
        var fieldset = $(this);
152
        fieldset.find('.input-field').each(function() {
153
            $(this).removeClass('invalid-error');
154
            var validation = $(this).attr('data-regexp');
155
            if ($(this).val() && $(this).val().length > 0 && validation && validation.length > 0) {
156
                try {
157
                    var regexp = new RegExp(validation);
158
                    var res = $(this).val().match(regexp);
159
                    if (!(res && res.length == 1 && res[0] == $(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...
160
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(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...
161
                    $(this).addClass('invalid-error');
162
                    showFormError();
163
                    markPage(fieldset, true);
164
                    error = true;
165
                    }
166
                } catch (err) {
167
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
168
                    $(this).addClass('invalid-error');
169
                    showFormError();
170
                    markPage(fieldset, true);
171
                    error = true;
172
                    }
173
            } else {
174
                var validateDate = $(this).attr('data-datatype') == 'DATE';
175
                if ($(this).val() && $(this).val().length > 0 && validateDate && !isDate($(this).val())) {
176
                    $('<div class="alert alert-warning" role="alert"><span class="glyphicon glyphicon glyphicon-warning-sign pull-right"></span>' + form_error_msg_field_invalid + ': ' + $(this).attr('data-label') + '</div>').insertAfter(fieldset.find('legend').last());
177
                    $(this).addClass('invalid-error');
178
                    showFormError();
179
                    markPage(fieldset, true);
180
                    error = true;
181
                }
182
            }
183
        });
184
        /*        if (checkPrimaryFile(fieldset)) {
185
              $('<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());
186
              showFormError();
187
              error = true;
188
              markPage(fieldset,true);
189
            }
190
          */
191
        });
192
        return !error;
193
    }
194
195
    var showFormError = function() {
196
        $('.tx-dpf div.alert-danger').remove();
197
        $('<div class="alert alert-danger" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_error_msg + '</div>').insertBefore($('.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...
198
        $("html, body").animate({scrollTop: 0}, 200);
199
    }
200
201
    var showFormSuccess = function() {
202
        $('.tx-dpf div.alert-danger').remove();
203
        $('<div class="alert alert-success" role="alert"><span class="glyphicon glyphicon glyphicon-fire pull-right"></span>' + form_success_msg + '</div>').insertBefore($('.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...
204
        $("html, body").animate({scrollTop: 0}, 200);
205
    }
206
207
    var hasMandatoryInputs = function(fieldset) {
208
        var inputs = fieldset.find(".input-field[data-mandatory=1]");
209
        return inputs.length > 0;
210
    }
211
212
    var markPage = function(fieldset, error) {
213
        var pageId = fieldset.parent().attr('id');
214
        var page = $('.tx-dpf-tabs li a[href=#' + pageId + ']');
215
        if (error) {
216
            page.addClass('mandatory-error');
217
        } else {
218
            page.removeClass('mandatory-error');
219
        }
220
    }
221
222
    var checkMandatoryInputs = function(fieldset) {
223
        var mandatoryError = false;
224
        fieldset.find(".input-field[data-mandatory=1]").each(function() {
225
            var id = $(this).attr('id');
226
            if (($(this).attr('type') != 'checkbox' && !$(this).val()) || ($(this).attr('type') == 'checkbox' && ($("#" + id + ":checked").length != 1 || !$("#" + id + ":checked")))) {
0 ignored issues
show
Best Practice introduced by
Comparing $("#" + id + ":checked").length to 1 using the != operator is not safe. Consider using !== instead.
Loading history...
227
                mandatoryError = mandatoryError || true;
228
                $(this).addClass('mandatory-error');
229
            } else {
230
                $(this).removeClass('mandatory-error');
231
            }
232
        });
233
        //markPage(fieldset,mandatoryError);
234
        return mandatoryError;
235
    }
236
237
    var checkPrimaryFile = function(fieldset) {
238
        var mandatoryError = false;
239
        fieldset.find("input#inp_primaryFile[data-virtual!=1]").each(function() {
240
            if (!$(this).val()) {
241
                mandatoryError = mandatoryError || true;
242
                $(this).addClass('mandatory-error');
243
            } else {
244
                $(this).removeClass('mandatory-error');
245
            }
246
        });
247
        //  markPage(fieldset,mandatoryError);
248
        return mandatoryError;
249
    }
250
251
    var checkFilledInputs = function(fieldset) {
252
        var filledInputs = 0;
253
        fieldset.find('.input-field').each(function() {
254
            if ($(this).val()) {
255
                filledInputs++;
256
            }
257
            $(this).removeClass('mandatory-error');
258
        });
259
        //markPage(fieldset,filledInputs < 1);
260
        return filledInputs < 1;
261
    }
262
263
    var addGroup = function() {
264
        var element = $(this);
265
        // Get the group uid
266
        var dataGroup = $(this).attr('data-group');
267
        // Number of the next group item
268
        // var groupIndex = $(this).parent().find('fieldset[data-group="'+dataGroup+'"]').length;
269
        var groupIndex = parseInt($(this).attr('data-index')) + 1;
270
        $(this).attr('data-index', groupIndex);
271
        var ajaxURL = $(this).attr('data-ajax');
272
        var params = buildAjaxParams(ajaxURL, "groupIndex", groupIndex);
273
        //do the ajax-call
274
        $.post(ajaxURL, params, function(group) {
275
            var group = $(group).find("fieldset");
276
            // add the new group
277
            $(group)
278
                .css({'display': 'none'})
279
                .insertAfter($('fieldset[data-group="' + dataGroup + '"]').last());
280
281
            var height = $('fieldset[data-group="' + dataGroup + '"]')
282
                .last()
283
                .outerHeight(true)
284
285
            $('html, body')
286
                .animate({scrollTop: element.offset().top - height}, 400, function() {$(group).fadeIn();});
287
288
            buttonFillOutServiceUrn();
289
            datepicker();
290
            addRemoveFileButton();
291
292
            // gnd autocomplete for new groups
293
            var gndField = $(group).find('.gnd');
294
            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...
295
                setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
296
            }
297
        });
298
        return false;
299
    }
300
301
    var addField = function() {
302
        var addButton = $(this);
303
        // Get the field uid
304
        var dataField = $(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...
305
        // Number of the next field item
306
        var fieldIndex = parseInt($(this).attr('data-index')) + 1;
307
        $(this).attr('data-index', fieldIndex);
308
        var ajaxURL = $(this).attr('data-ajax');
309
        var params = buildAjaxParams(ajaxURL, "fieldIndex", fieldIndex);
310
        //do the ajax-call
311
        $.post(ajaxURL, params, function(element) {
312
            var field = $(element).find("#new-element").children();
313
            $(field).css({'display': 'none'})
314
                .insertBefore(addButton).fadeIn();
315
            buttonFillOutServiceUrn();
316
            datepicker();
317
318
            // gnd autocomplete for new fields
319
            var gndField = $(group).find('.gnd');
0 ignored issues
show
Bug introduced by
The variable group seems to be never declared. If this is a global, consider adding a /** global: group */ 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...
320
            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...
321
                setGndAutocomplete(gndField.data('field'),gndField.data('groupindex'));
322
            }
323
324
            //  var height =$('input[data-field="'+dataField+'"][data-index="'+fieldIndex+'"]').last().outerHeight(true)
325
            // $('html, body').animate({
326
            //   scrollTop: element.offset().top - height
327
            //}, 400);
328
        });
329
        return false;
330
    }
331
332
    var deleteFile = function() {
333
        var fileGroup = $(this).parent().parent();
334
        //$(this).parent().remove();
335
        var ajaxURL = $(this).attr('data-ajax');
336
        //var params = buildAjaxParams(ajaxURL,"fileUid",fieldIndex);
337
        var params = {};
338
        //do the ajax-call
339
        $.post(ajaxURL, params, function(element) {
340
            var field = $(element).find("#new-element").children();
341
            $(fileGroup).replaceWith(field);
342
        });
343
        return false;
344
    }
345
346
    function buildAjaxParams(ajaxURL, indexName, index) {
347
        var res = ajaxURL.match(/(tx\w+?)%/); // get param name
348
        var params = {};
349
        var indexParam = {};
350
        if (res && res[1]) {
351
            indexParam[indexName] = index;
352
            params[res[1]] = indexParam;
353
        }
354
        return params;
355
    }
356
357
    var fillOutServiceUrn = function() {
358
        // Get the field uid
359
        var fieldUid = $(this).attr('data-field');
360
        var fieldIndex = $(this).attr('data-index');
361
        var groupUid = $(this).attr('data-group');
362
        var groupIndex = $(this).attr('data-groupindex');
363
        var ajaxURL = $(this).attr('data-ajax');
364
        var qucosaId = $('#qucosaid').val();
365
        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...
366
367
        if (qucosaId) {
368
            params = buildAjaxParams(ajaxURL, "qucosaId", qucosaId);
369
        } else {
370
            params = buildAjaxParams(ajaxURL, "qucosaId", "");
371
        }
372
373
        //do the ajax-call
374
        $.getJSON(ajaxURL, params, function(element) {
375
            $('#qucosaid').val(element.qucosaId);
376
            $('#qucosaUrn').val(element.value);
377
            //var inputField = $('.input-field[data-field="'+ fieldUid +'"][data-index="'+ fieldIndex +'"]');
378
            var inputField = $('.input-field[data-field="' + fieldUid + '"][data-index="' + fieldIndex + '"][data-group="' + groupUid + '"][data-groupindex="' + groupIndex + '"]');
379
            inputField.val(element.value);
380
            //var fillOutButton = $('.fill_out_service_urn[data-field="'+ fieldUid +'"][data-index="'+ fieldIndex +'"]');
381
            //fillOutButton.hide();
382
            buttonFillOutServiceUrn();
383
        });
384
        return false;
385
    }
386
387
    var continuousScroll = function() {
388
        var ajaxURL = $("#next").attr('href');
389
        $.ajax({
390
            url: ajaxURL,
391
            success: function(html) {
392
                if (html) {
393
                    $(html).find("table tbody tr").each(function() {
394
                        $("#search-results tbody tr").last().parent().append(this);
395
                    });
396
                    if ($(html).find("table tbody tr").length <= 0) {
397
                        $("#next").hide();
398
                    }
399
                } else {
400
                    $("#next").hide();
401
                }
402
            }
403
        });
404
        return false;
405
    }
406
407
    var isDate = function(value) {
408
        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...
409
        var rxDatePattern = /^(\d{1,2})(\.)(\d{1,2})(\.)(\d{4})$/; //Declare Regex
410
        var dtArray = value.match(rxDatePattern); // is format OK?
411
        if (dtArray == null) return false;
0 ignored issues
show
Best Practice introduced by
Comparing dtArray to null using the == operator is not safe. Consider using === instead.
Loading history...
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...
412
        //Checks for mm/dd/yyyy format.
413
        var dtMonth = dtArray[3];
414
        var dtDay = dtArray[1];
415
        var dtYear = dtArray[5];
416
        if (dtMonth < 1 || dtMonth > 12) {
417
            return false;
418
        }
419
        if (dtDay < 1 || dtDay > 31) {
420
            return false;
421
        }
422
        if ((dtMonth == 4 || dtMonth == 6 || dtMonth == 9 || dtMonth == 11) && dtDay == 31) {
423
            return false;
424
        }
425
        if (dtMonth == 2) {
426
            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...
427
            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...
428
        }
429
        return true;
430
    }
431
432
    function addRemoveFileButton() {
433
        $('.rem_file').unbind('click');
434
        $('.rem_file').bind('click', function (evt) {
435
            evt.preventDefault();
436
            $(this).siblings('.input_file_upload').val('');
437
        });
438
    }
439
440
    function gndNothingFound(fieldId, groupIndex) {
441
        var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
442
443
        if (gndInputField.data('old_gnd_field_value')) {
444
            gndInputField.val(gndInputField.data('old_gnd_field_value'));
445
        } else {
446
            gndInputField.val();
447
        }
448
449
        var gndFieldId = gndInputField.data('gndfield');
450
        var linkedGroupIndex = gndInputField.data('groupindex');
451
        var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
452
453
        if (gndLinkedInputField.data('old_gnd_field_id')) {
454
            gndLinkedInputField.val(gndLinkedInputField.data('old_gnd_field_id'));
455
        } else {
456
            gndLinkedInputField.val();
457
        }
458
459
        /** global: form_error_msg_nothing_found */
460
        $('<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...
461
462
        gndInputField.bind("keypress click", function () {
463
            $("#gnd-nothing-found").remove();
464
        });
465
466
        gndLinkedInputField.bind("keypress click", function () {
467
            $("#gnd-nothing-found").remove();
468
        });
469
470
    }
471
472
    function setGndAutocomplete(fieldId, groupIndex) {
473
        // GND autocomplete
474
        var ajaxURL = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').attr('data-ajax');
475
476
        var gndInputField = $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]');
477
        var gndFieldId = gndInputField.data('gndfield');
478
        var linkedGroupIndex = gndInputField.data('groupindex');
479
        var gndLinkedInputField = $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]');
480
481
        gndInputField.attr('data-old_gnd_field_value',gndInputField.val());
482
        gndLinkedInputField.attr('data-old_gnd_field_id',gndLinkedInputField.val());
483
484
        // Get the name of the parameter array (tx_dpf_...),
485
        // the name depends on whether the call is from the frontend or the backend
486
        var res = ajaxURL.match(/(tx_dpf\w+?)%/);
487
        var paramName = "tx_dpf_qucosaform[search]";
488
        if (res && res[1]) {
489
            paramName = res[1]+"[search]";
490
        }
491
492
        $('.gnd[data-field="' + fieldId + '"][data-groupindex="' + groupIndex + '"]').autocomplete({
493
            source: function (request, response) {
494
495
                $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val('');
496
497
                var requestData = {};
498
                requestData[paramName] = request.term.replace(" ", "+");
499
                $.ajax({
500
                    type: 'POST',
501
                    url: ajaxURL,
502
                    data: requestData,
503
                    dataType: 'json',
504
                    timeout: 10000,
505
                    success: function (data) {
506
                        if (data) {
507
                            response(data);
508
                        } else {
509
                            gndNothingFound(fieldId, groupIndex);
510
                            response([]);
511
                        }
512
                    },
513
                    error: function () {
514
                        gndNothingFound(fieldId, groupIndex);
515
                        response([]);
516
                    }
517
                });
518
            },
519
            minLength: 3,
520
            select: function (event, ui) {
521
                gndFieldId = $(event.target).data('gndfield');
522
                linkedGroupIndex = $(event.target).data('groupindex');
523
                $('input[data-field="' + gndFieldId + '"][data-groupindex="' + linkedGroupIndex + '"]').val(ui.item.gnd);
524
            },
525
        }).autocomplete( "instance" )._renderItem = function( ul, item ) {
526
            return $( "<li>" )
527
                .append( "<div class='gnd-autocomplete'><span class='gnd-value' style='display:none;'>" + item.value + "</span>" +
528
                    "<span class='gnd-label'>" + item.label + "</span></div>"
529
                )
530
                .appendTo( ul );
531
        };
532
    }
533
534
    var previousNextFormPage = function() {
535
536
        $('.prev-next-buttons button').click(function (e) {
537
            var activePage = $('.tx-dpf-tabs').find('li.active');
538
            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...
539
540
            if ($(this).attr('id') == 'next-form-page') {
541
                newActivePage = activePage.next();
542
            } else {
543
                newActivePage = activePage.prev();
544
            }
545
546
            if (newActivePage.length > 0) {
547
                activePage.removeClass('active');
548
                activePage.find('a').attr('aria-expanded', 'false');
549
                $('.tab-content').find('div.active').removeClass('active');
550
551
                newActivePage.addClass('active');
552
                newActivePage.find('a').attr('aria-expanded', 'true');
553
                $('.tab-content').find(newActivePage.find('a').attr('href')).addClass('active');
554
555
                updatePrevNextButtons(newActivePage);
556
557
                $('html, body').animate({
558
                    scrollTop:$('.tx-dpf').offset().top
559
                },'fast');
560
            }
561
562
            e.preventDefault();
563
564
        });
565
566
        updatePrevNextButtons($('.tx-dpf-tabs li.active'));
567
568
        $('.tx-dpf-tabs li').click(function(){
569
            updatePrevNextButtons($(this));
570
        });
571
572
    }
573
574
    var updatePrevNextButtons = function(activePage) {
575
576
        if (activePage.prev().length < 1) {
577
            $('#prev-form-page').addClass('disabled');
578
        } else {
579
            $('#prev-form-page').removeClass('disabled');
580
        }
581
        if (activePage.next().length < 1) {
582
            $('#next-form-page').addClass('disabled');
583
        } else {
584
            $('#next-form-page').removeClass('disabled');
585
        }
586
    }
587
588
    var inputWithOptions = function() {
589
590
        $.widget( "custom.dropdownoptions", {
591
            _create: function() {
592
593
                var availableTags = [];
594
                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...
595
                    .closest(".dropdown-options")
596
                    .find(".dropdown-options-values li")
597
                    .each(function(){
598
                        if ($(this).text().length > 0) {
599
                            availableTags.push($(this).text());
600
                        }
601
                    });
602
603
                this.element
604
                    .addClass( ".dropdown-options-input" )
605
                    .autocomplete({
606
                        minLength: 0,
607
                        source: availableTags
608
                    });
609
610
                this._createShowAllButton();
611
            },
612
            _createShowAllButton: function() {
613
614
                var input = this.element;
615
616
                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...
617
618
                input
619
                    .closest(".dropdown-options")
620
                    .find(".dropdown-options-toggle")
621
                    .on( "mousedown", function() {
622
                        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...
623
                    })
624
                    .on( "click", function() {
625
                        input.trigger( "focus" );
626
                        if ( wasOpen ) {
627
                            return;
628
                        }
629
                        input.autocomplete( "search", "" );
630
631
                    });
632
                input
633
                    .on( "click", function() {
634
                        input.autocomplete( "search", "" );
635
                    });
636
            }
637
        });
638
639
        $( ".dropdown-options-input" ).dropdownoptions();
640
    }
641
642
    $(window).scroll(function() {
643
        if ($(this).scrollTop() > 330) {
644
            $(".tx-dpf-tab-container").addClass("sticky");
645
        } else {
646
            $(".tx-dpf-tab-container").removeClass("sticky");
647
        }
648
    });
649
650
    $(document).ready(function() {
651
        $('#new-document-form').trigger('reset');
652
        documentListConfirmDialog('#confirmDiscard');
653
        documentListConfirmDialog('#confirmPublish');
654
        documentListConfirmDialog('#confirmUpdate');
655
        documentListConfirmDialog('#confirmActivate');
656
        documentListConfirmDialog('#confirmInactivate');
657
        documentListConfirmDialog('#confirmRestore');
658
        documentListConfirmDialog('#confirmDelete');
659
660
        datepicker();
661
662
        $('[data-toggle="tooltip"]').tooltip();
663
        var $disableForm = $('form[data-disabled]').attr('data-disabled');
664
        if ($disableForm) {
665
            $('.input-field').each(function() {$(this).attr('disabled', 'disabled');});
666
            $('.rem_file_group').each(function() {$(this).attr('disabled', 'disabled');});
667
            $('.add_file_group').each(function() {$(this).attr('disabled', 'disabled');});
668
            $('.input_file_upload').each(function() {$(this).attr('disabled', 'disabled');});
669
            $('.add_field').each(function() {$(this).attr('disabled', 'disabled');});
670
            $('.add_group').each(function() {$(this).attr('disabled', 'disabled');});
671
            $('.rem_field').each(function() {$(this).attr('disabled', 'disabled');});
672
            $('.rem_group').each(function() {$(this).attr('disabled', 'disabled');});
673
            $('.fill_out_service_urn').each(function() {$(this).attr('disabled', 'disabled');});
674
        }
675
676
        buttonFillOutServiceUrn();
677
678
        $(".tx-dpf").on("click", ".rem_group", function() {
679
            $(this).parents('fieldset').fadeOut(300, function() {$(this).remove();});
680
            return false;
681
        });
682
        $(".tx-dpf").on("click", ".rem_file_group", deleteFile);
683
        $(".tx-dpf").on("click", ".rem_secondary_upload", function() {
684
            var dataIndex = $(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
685
            $(this).parents('.fs_file_group').fadeOut(300, function() {$(this).remove();});
686
            return false;
687
        });
688
        $(".tx-dpf").on("click", ".rem_field", function() {
689
            var dataIndex = $(this).data("index");
0 ignored issues
show
Unused Code introduced by
The variable dataIndex seems to be never used. Consider removing it.
Loading history...
690
            var dataField = $(this).data("field");
0 ignored issues
show
Unused Code introduced by
The variable dataField seems to be never used. Consider removing it.
Loading history...
691
            $(this).parents('.form-group').fadeOut(300, function() {$(this).remove();});
692
            return false;
693
        });
694
        // Add metadata group
695
        $(".tx-dpf").on("click", ".add_group", addGroup);
696
        $(".tx-dpf").on("click", ".add_file_group", addGroup);
697
        $(".tx-dpf").on("click", ".add_field", addField);
698
        $(".tx-dpf").on("click", ".fill_out_service_urn", fillOutServiceUrn);
699
        $(".tx-dpf").on("keyup", "input.urn", buttonFillOutServiceUrn);
700
        //$(window).on("scroll", "", continuousScroll);
701
        $(".tx-dpf").on("click", "#next", continuousScroll);
702
        // $(".form-submit").on("click","#save",
703
        $(".form-submit").on("click", "#save", validateFormAndSave);
704
        $(".form-submit").on("click", "#validate", validateFormOnly);
705
706
        // hide 'more results' link
707
        var countResults = $('#search-results :not(thead) tr').length;
708
        var resultCount = $('#next').data('resultCount');
709
710
        if (countResults < resultCount) {
711
            $("#next").hide();
712
        }
713
714
        addRemoveFileButton();
715
716
        previousNextFormPage();
717
718
        var gnd = $('.gnd');
719
        if(gnd.length > 0) {
720
            gnd.each(function() {
721
                setGndAutocomplete($(this).data("field"),  $(this).data("groupindex"));
722
            });
723
        }
724
725
        inputWithOptions();
726
727
    });
728
});
729
730