Passed
Pull Request — master (#126)
by Kiran
03:46
created

admin.js ➔ ... ➔ $.post   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
nc 8
nop 1
dl 0
loc 33
rs 5.3846
c 0
b 0
f 0
1
jQuery(function($) {
2
    //'use strict';
3
4
    // Tooltips
5
    $('.wpi-help-tip').tooltip({
6
        content: function() {
7
            return $(this).prop('title');
8
        },
9
        tooltipClass: 'wpi-ui-tooltip',
10
        position: {
11
            my: 'center top',
12
            at: 'center bottom+10',
13
            collision: 'flipfit'
14
        },
15
        hide: {
16
            duration: 200
17
        },
18
        show: {
19
            duration: 200
20
        }
21
    });
22
23
    var wpiGlobalTax = WPInv_Admin.tax != 0 ? WPInv_Admin.tax : 0;
0 ignored issues
show
Unused Code introduced by
The variable wpiGlobalTax seems to be never used. Consider removing it.
Loading history...
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
24
    var wpiGlobalDiscount = WPInv_Admin.discount != 0 ? WPInv_Admin.discount : 0;
0 ignored issues
show
Unused Code introduced by
The variable wpiGlobalDiscount seems to be never used. Consider removing it.
Loading history...
25
    var wpiSymbol = WPInv_Admin.currency_symbol;
26
    var wpiPosition = WPInv_Admin.currency_pos;
27
    var wpiThousandSep = WPInv_Admin.thousand_sep;
28
    var wpiDecimalSep = WPInv_Admin.decimal_sep;
29
    var wpiDecimals = WPInv_Admin.decimals;
30
    var $postForm = $('.post-type-wpi_invoice form#post');
31
    if ($('[name="wpinv_status"]', $postForm).length) {
32
        var origStatus = $('[name="wpinv_status"]', $postForm).val();
33
        $('[name="original_post_status"]', $postForm).val(origStatus);
34
        $('[name="hidden_post_status"]', $postForm).val(origStatus);
35
        $('[name="post_status"]', $postForm).replaceWith('<input type="hidden" value="' + origStatus + '" id="post_status" name="post_status">');
36
        $postForm.on('change', '[name="wpinv_status"]', function(e) {
37
            e.preventDefault();
38
            $('[name="post_status"]', $postForm).replaceWith('<input type="hidden" value="' + $(this).val() + '" id="post_status" name="post_status">');
39
        });
40
    }
41
    $('input.wpi-price').on("contextmenu", 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...
42
        return false;
43
    });
44
    $(document).on('keypress', 'input.wpi-price', function(e) {
45
        var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
46
        if ($.inArray(e.key, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ",", "."]) !== -1) {
47
            return true;
48
        } else if (e.ctrlKey || e.shiftKey) {
49
            return false;
50
        } else if ($.inArray(key, [8, 35, 36, 37, 39, 46]) !== -1) {
51
            return true;
52
        }
53
        return false;
54
    });
55
    // sorts out the number to enable calculations
56
    function wpinvRawNumber(x) {
0 ignored issues
show
introduced by
The function wpinvRawNumber does not seem to be used and can be removed.
Loading history...
57
        // removes the thousand seperator
58
        var parts = x.toString().split(wpiThousandSep);
59
        parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, '');
60
        var amount = parts.join('');
61
        // makes the decimal seperator a period
62
        var output = amount.toString().replace(/\,/g, '.');
63
        output = parseFloat(output);
64
        if (isNaN(output)) {
65
            output = 0;
66
        }
67
        if (output && output < 0) {
68
            output = output * (-1);
69
        }
70
        return output;
71
    }
72
    // formats number into users format
73
    function wpinvFormatNumber(nStr) {
74
        var num = nStr.split('.');
75
        var x1 = num[0];
76
        var x2 = num.length > 1 ? wpiDecimalSep + num[1] : '';
77
        var rgx = /(\d+)(\d{3})/;
78
        while (rgx.test(x1)) {
79
            x1 = x1.replace(rgx, '$1' + wpiThousandSep + '$2');
80
        }
81
        return x1 + x2;
82
    }
83
    // format the amounts
84
    function wpinvFormatAmount(amount) {
0 ignored issues
show
introduced by
The function wpinvFormatAmount does not seem to be used and can be removed.
Loading history...
85
        if (typeof amount !== 'number') {
86
            amount = parseFloat(amount);
87
        }
88
        // do the symbol position formatting   
89
        var formatted = 0;
90
        var amount = amount.toFixed(wpiDecimals);
91
        switch (wpiPosition) {
92
            case 'left':
93
                formatted = wpiSymbol + wpinvFormatNumber(amount);
94
                break;
95
            case 'right':
96
                formatted = wpinvFormatNumber(amount) + wpiSymbol;
97
                break;
98
            case 'left_space':
99
                formatted = wpiSymbol + ' ' + wpinvFormatNumber(amount);
100
                break;
101
            case 'right_space':
102
                formatted = wpinvFormatNumber(amount) + ' ' + wpiSymbol;
103
                break;
104
            default:
105
                formatted = wpiSymbol + wpinvFormatNumber(amount);
106
                break;
107
        }
108
        return formatted;
109
    }
110
    /**
111
     * Invoice Notes Panel
112
     */
113
    var wpinv_meta_boxes_notes = {
114
        init: function() {
115
            $('#wpinv-notes')
116
                .on('click', 'a.add_note', this.add_invoice_note)
117
                .on('click', 'a.delete_note', this.delete_invoice_note);
118
            if ($('ul.invoice_notes')[0]) {
119
                $('ul.invoice_notes')[0].scrollTop = $('ul.invoice_notes')[0].scrollHeight;
120
            }
121
        },
122
        add_invoice_note: function() {
123
            if (!$('textarea#add_invoice_note').val()) {
124
                return;
125
            }
126
            $('#wpinv-notes').block({
127
                message: null,
128
                overlayCSS: {
129
                    background: '#fff',
130
                    opacity: 0.6
131
                }
132
            });
133
            var data = {
134
                action: 'wpinv_add_note',
135
                post_id: WPInv_Admin.post_ID,
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
136
                note: $('textarea#add_invoice_note').val(),
137
                note_type: $('select#invoice_note_type').val(),
138
                _nonce: WPInv_Admin.add_invoice_note_nonce
139
            };
140
            $.post(WPInv_Admin.ajax_url, data, function(response) {
141
                $('ul.invoice_notes').append(response);
142
                $('ul.invoice_notes')[0].scrollTop = $('ul.invoice_notes')[0].scrollHeight;
143
                $('#wpinv-notes').unblock();
144
                $('#add_invoice_note').val('');
145
            });
146
            return false;
147
        },
148
        delete_invoice_note: function() {
149
            var note = $(this).closest('li.note');
150
            $(note).block({
151
                message: null,
152
                overlayCSS: {
153
                    background: '#fff',
154
                    opacity: 0.6
155
                }
156
            });
157
            var data = {
158
                action: 'wpinv_delete_note',
159
                note_id: $(note).attr('rel'),
160
                _nonce: WPInv_Admin.delete_invoice_note_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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
            };
162
            $.post(WPInv_Admin.ajax_url, data, function() {
163
                $(note).remove();
164
            });
165
            return false;
166
        }
167
    };
168
    wpinv_meta_boxes_notes.init();
169
    $('.post-type-wpi_invoice [name="post"] #submitpost [type="submit"]').on('click', 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...
170
        if (parseInt($(document.body).find('.wpinv-line-items > .item').length) < 1) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if parseInt($(document.body...s > .item").length) < 1 is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
171
            alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
172
            $('#wpinv_invoice_item').focus();
173
            return false;
174
        }
175
    });
176
    var invDetails = jQuery('#gdmbx2-metabox-wpinv_details').html();
177
    if (invDetails) {
178
        jQuery('#submitpost', jQuery('.wpinv')).detach().appendTo(jQuery('#wpinv-details'));
179
        jQuery('#submitdiv', jQuery('.wpinv')).hide();
180
        jQuery('#major-publishing-actions', '#wpinv-details').find('input[type=submit]').attr('name', 'save_invoice').val(WPInv_Admin.save_invoice);
181
    }
182
    var invBilling = jQuery('#wpinv-address.postbox').html();
183
    if (invBilling) {
184
        jQuery('#post_author_override', '#authordiv').remove(); //.addClass('gdmbx2-text-medium').detach().prependTo(jQuery('.gdmbx-customer-div'));
185
        jQuery('#authordiv', jQuery('.wpinv')).hide();
186
    }
187
    var wpinvNumber;
188
    if (!jQuery('#post input[name="post_title"]').val() && (wpinvNumber = jQuery('#wpinv-details input[name="wpinv_number"]').val())) {
189
        jQuery('#post input[name="post_title"]').val(wpinvNumber);
190
    }
191
    var wpi_stat_links = jQuery('.post-type-wpi_invoice .subsubsub');
192
    if (wpi_stat_links.is(':visible')) {
193
        var publish_count = jQuery('.publish', wpi_stat_links).find('.count').text();
194
        jQuery('.publish', wpi_stat_links).find('a').html(WPInv_Admin.status_publish + ' <span class="count">' + publish_count + '</span>');
195
        var pending_count = jQuery('.wpi-pending', wpi_stat_links).find('.count').text();
196
        jQuery('.pending', wpi_stat_links).find('a').html(WPInv_Admin.status_pending + ' <span class="count">' + pending_count + '</span>');
197
    }
198
    // Update tax rate state field based on selected rate country
199
    $(document.body).on('change', '#wpinv_tax_rates select.wpinv-tax-country', function() {
200
        var $this = $(this);
201
        data = {
0 ignored issues
show
Bug introduced by
The variable data 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.data.
Loading history...
202
            action: 'wpinv_get_states_field',
203
            country: $(this).val(),
204
            field_name: $this.attr('name').replace('country', 'state')
205
        };
206
        $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ 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...
207
            if ('nostates' == response) {
208
                var text_field = '<input type="text" name="' + data.field_name + '" value=""/>';
209
                $this.parent().next().find('select').replaceWith(text_field);
210
            } else {
211
                $this.parent().next().find('input,select').show();
212
                $this.parent().next().find('input,select').replaceWith(response);
213
            }
214
        });
215
        return false;
216
    });
217
    // Insert new tax rate row
218
    $('#wpinv_add_tax_rate').on('click', function() {
219
        var row = $('#wpinv_tax_rates tbody tr:last');
220
        var clone = row.clone();
221
        var count = row.parent().find('tr').length;
222
        clone.find('td input').not(':input[type=checkbox]').val('');
223
        clone.find('td [type="checkbox"]').attr('checked', false);
224
        clone.find('input, select').each(function() {
225
            var name = $(this).attr('name');
226
            name = name.replace(/\[(\d+)\]/, '[' + parseInt(count) + ']');
227
            $(this).attr('name', name).attr('id', name);
228
        });
229
        clone.find('label').each(function() {
230
            var name = $(this).attr('for');
231
            name = name.replace(/\[(\d+)\]/, '[' + parseInt(count) + ']');
232
            $(this).attr('for', name);
233
        });
234
        clone.insertAfter(row);
235
        return false;
236
    });
237
    // Remove tax row
238
    $(document.body).on('click', '#wpinv_tax_rates .wpinv_remove_tax_rate', function() {
239
        var tax_rates = $('#wpinv_tax_rates tbody tr:visible');
240
        var count = tax_rates.length;
241
        if (count === 1) {
242
            $('#wpinv_tax_rates select').val('');
243
            $('#wpinv_tax_rates input[type="text"]').val('');
244
            $('#wpinv_tax_rates input[type="number"]').val('');
245
            $('#wpinv_tax_rates input[type="checkbox"]').attr('checked', false);
246
        } else {
247
            $(this).closest('tr').remove();
248
        }
249
        /* re-index after deleting */
250
        $('#wpinv_tax_rates tbody tr').each(function(rowIndex) {
251
            $(this).children().find('input, select').each(function() {
252
                var name = $(this).attr('name');
253
                name = name.replace(/\[(\d+)\]/, '[' + (rowIndex) + ']');
254
                $(this).attr('name', name).attr('id', name);
255
            });
256
        });
257
        return false;
258
    });
259
    var elB = $('#wpinv-address');
260
    $('#wpinv_country', elB).change(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...
261
        var $this = $(this);
262
        data = {
0 ignored issues
show
Bug introduced by
The variable data 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.data.
Loading history...
263
            action: 'wpinv_get_states_field',
264
            country: $(this).val(),
265
            field_name: 'wpinv_state',
266
        };
267
        $this.closest('.gdmbx-row').find('.wpi-loader').show();
268
        $('#wpinv_state', elB).css({
269
            'opacity': '.5'
270
        });
271
        $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ 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...
272
            var selected = typeof $this.data('state') !== 'undefined' ? $this.data('state') : "";
273
            if ('nostates' === response) {
274
                var text_field = '<input type="text" value="' + selected + '" id="wpinv_state" name="wpinv_state" />';
275
                $('#wpinv_state', elB).replaceWith(text_field);
276
            } else {
277
                $('#wpinv_state', elB).replaceWith(response);
278
                $('#wpinv_state', elB).find('option[value="' + selected + '"]').attr('selected', 'selected');
279
                $('#wpinv_state', elB).find('option[value=""]').remove();
280
            }
281
            $('#wpinv_state', elB).addClass('gdmbx2-text-large');
282
            if (typeof $this.data('change') === '1') {
283
                $('#wpinv_state', elB).change();
284
            } else {
285
                window.wpiConfirmed = true;
286
                $('#wpinv-recalc-totals').click();
287
                window.wpiConfirmed = false;
288
            }
289
            $this.closest('.gdmbx-row').find('.wpi-loader').hide();
290
            $('#wpinv_state', elB).css({
291
                'opacity': '1'
292
            });
293
        });
294
        return false;
295
    });
296
    $('#wpinv_state', elB).on('change', 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...
297
        window.wpiConfirmed = true;
298
        $('#wpinv-recalc-totals').click();
299
        window.wpiConfirmed = false;
300
    });
301
    $('#wpinv-fill-user-details').click(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...
302
        var metaBox = $(this).closest('.inside');
303
        var user_id = $('select[name="post_author_override"]', metaBox).val();
304
        if (!user_id || $(this).attr('disabled')) {
305
            return false;
306
        }
307
        if (window.confirm(WPInv_Admin.FillBillingDetails)) {
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
Complexity Best Practice introduced by
There is no return statement if window.confirm(WPInv_Admin.FillBillingDetails) is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
308
            var data = {
309
                action: 'wpinv_get_billing_details',
310
                user_id: user_id,
311
                _nonce: WPInv_Admin.billing_details_nonce
312
            };
313
            wpinvBlock(metaBox);
314
            $.post(WPInv_Admin.ajax_url, data, function(response) {
315
                var elCountry = $('#wpinv_country', metaBox);
316
                elCountry.removeAttr('data-state').removeAttr('data-change');
317
                if (response && typeof response == 'object') {
318
                    if (response.success === true && typeof response.data.billing_details == 'object') {
319
                        var state = false;
320
                        var country = false;
321
                        $.each(response.data.billing_details, function(key, value) {
322
                            if (key == 'state') {
323
                                state = value;
324
                            } else if (key == 'country') {
325
                                country = value;
326
                            } else {
327
                                $('#wpinv_' + key, metaBox).val(value).change();
328
                            }
329
                        });
330
                        if (country !== false) {
331
                            if (state !== false) {
332
                                elCountry.data('state', state).data('change', '1');
333
                            }
334
                            elCountry.val(country).change();
335
                        }
336
                    }
337
                }
338
                wpinvUnblock(metaBox);
339
            });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
340
        }
341
    });
342
    var WPInv = {
343
        init: function() {
344
            this.preSetup();
345
            this.prices();
346
            this.remove_item();
347
            this.add_item();
348
            this.recalculateTotals();
349
            this.setup_tools();
350
        },
351
        preSetup: function() {
352
            $('.wpiDatepicker').each(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...
353
                var $this = $(this);
354
                var args = {};
355
                if ($this.attr('data-changeMonth')) {
356
                    args.changeMonth = true;
357
                }
358
                if ($this.attr('data-changeYear')) {
359
                    args.changeYear = true;
360
                }
361
                if ($this.attr('data-dateFormat')) {
362
                    args.dateFormat = $this.attr('data-dateformat');
363
                }
364
                if ($this.attr('data-minDate')) {
365
                    args.minDate = $this.attr('data-minDate');
366
                }
367
                $(this).datepicker(args);
368
            });
369
            var wpinvColorPicker = $('.wpinv-color-picker');
370
            if (wpinvColorPicker.length) {
371
                wpinvColorPicker.wpColorPicker();
372
            }
373
            var no_states = $('select.wpinv-no-states');
374
            if (no_states.length) {
375
                no_states.closest('tr').hide();
376
            }
377
            // Update base state field based on selected base country
378
            $('select[name="wpinv_settings[default_country]"]').change(function() {
379
                var $this = $(this),
380
                    $tr = $this.closest('tr');
381
                data = {
0 ignored issues
show
Bug introduced by
The variable data 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.data.
Loading history...
382
                    action: 'wpinv_get_states_field',
383
                    country: $(this).val(),
384
                    field_name: 'wpinv_settings[default_state]'
385
                };
386
                $.post(ajaxurl, data, function(response) {
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ 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...
387
                    if ('nostates' == response) {
388
                        $tr.next().hide();
389
                    } else {
390
                        $tr.next().show();
391
                        $tr.next().find('select').replaceWith(response);
392
                    }
393
                });
394
                return false;
395
            });
396
            $('#wpinv-address').on('click', '.wpinv-new-user', function(e) {
397
                e.preventDefault();
398
                var mBox = $('#wpinv-address');
399
                $(this).hide();
400
                $('#wpinv-fill-user-details', elB).attr('disabled', true);
401
                $('.wpinv-new-cancel', mBox).show();
402
                $('#wpinv_new_user', mBox).val(1);
403
                $('#wpinv_email', mBox).prop('required', 'required');
404
                $('.gdmbx-wpinv-user-id', mBox).hide();
405
                $('.gdmbx-wpinv-email', mBox).show();
406
            });
407
            $('#wpinv-address').on('click', '.wpinv-new-cancel', function(e) {
408
                e.preventDefault();
409
                var mBox = $('#wpinv-address');
410
                $(this).hide();
411
                $('#wpinv-fill-user-details', elB).attr('disabled', false);
412
                $('.wpinv-new-user', mBox).show();
413
                $('#wpinv_new_user', mBox).val(0);
414
                $('#wpinv_email', mBox).prop('required', false);
415
                $('.gdmbx-wpinv-email', mBox).hide();
416
                $('.gdmbx-wpinv-user-id', mBox).show();
417
            });
418
            $('#wpinv-address #wpinv_email').on('change', function(e) {
419
                var metaBox = $(this).closest('.inside');
420
                if (parseInt($('#wpinv_new_user', metaBox).val()) != 1) {
421
                    return false;
422
                }
423
                e.preventDefault();
424
                wpinvBlock(metaBox);
425
                var data = {
426
                    action: 'wpinv_check_email',
427
                    email: $(this).val(),
428
                    _nonce: WPInv_Admin.wpinv_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
429
                };
430
                $.post(WPInv_Admin.ajax_url, data, function(response) {
431
                    var elCountry = $('#wpinv_country', metaBox);
432
                    elCountry.removeAttr('data-state').removeAttr('data-change');
433
                    if (response && typeof response == 'object') {
434
                        if (response.success === true && typeof response.data.billing_details == 'object') {
435
                            if (!$('#post_author_override [value="' + response.data.id + '"]', metaBox).val()) {
436
                                $('#post_author_override', metaBox).prepend('<option value="' + response.data.id + '">' + response.data.name + '</option>');
437
                            }
438
                            $('#post_author_override', metaBox).val(response.data.id);
439
                            $('.wpinv-new-cancel', metaBox).click();
440
                            var state = false;
441
                            var country = false;
442
                            $.each(response.data.billing_details, function(key, value) {
443
                                if (key == 'state') {
444
                                    state = value;
445
                                } else if (key == 'country') {
446
                                    country = value;
447
                                } else {
448
                                    if (key != 'email') {
449
                                        $('#wpinv_' + key, metaBox).val(value).change();
450
                                    }
451
                                }
452
                            });
453
                            if (country !== false) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
454
                                if (state !== false) {
455
                                    elCountry.data('state', state).data('change', '1');
456
                                }
457
                                elCountry.val(country).change();
458
                            }
459
                        }
460
                    }
461
                    wpinvUnblock(metaBox);
462
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
463
            });
464
            $('#wpinv_discount_type').on('change', function(e) {
465
                e.preventDefault();
466
                var mBox = $(this).closest('.inside');
467
                if ($(this).val() == 'flat') {
468
                    $('.wpi-discount-p', mBox).hide();
469
                    $('.wpi-discount-f', mBox).show();
470
                } else {
471
                    $('.wpi-discount-p', mBox).show();
472
                    $('.wpi-discount-f', mBox).hide();
473
                }
474
            });
475
            $('#wpinv_discount_type').trigger('change');
476
            
477
            $('#wpinv-apply-code').on('click', function(e) {
478
                e.preventDefault();
479
                var $this = $(this);
480
                var $form = $(this).closest('form[name="post"]');
481
                var invoice_id = parseInt($form.find('input#post_ID').val());
482
                if (!invoice_id > 0) {
483
                    return false;
484
                }
485
                
486
                if (!parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0) {
487
                    alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
488
                    $('#wpinv_invoice_item').focus();
489
                    return false;
490
                }
491
                
492
                var discount_code = $('#wpinv_discount', $form).val();
493
                
494
                if (!discount_code) {
495
                    $('#wpinv_discount', $form).focus();
496
                    return false;
497
                }
498
                
499
                $this.attr('disabled', true);
500
                $this.after('<span class="wpi-refresh">&nbsp;&nbsp;<i class="fa fa-spin fa-refresh"></i></span>');
501
502
                var data = {
503
                    action: 'wpinv_admin_apply_discount',
504
                    invoice_id: invoice_id,
505
                    code: discount_code,
506
                    _nonce: WPInv_Admin.wpinv_nonce
507
                };
508
                
509
                $.post(WPInv_Admin.ajax_url, data, function(response) {
510
                    var msg, success;
511
                    if (response && typeof response == 'object') {
512
                        if (response.success === true) {
513
                            success = true;
514
                            
515
                            $('#wpinv_discount', $form).attr('readonly', true);
516
                            $this.removeClass('wpi-inlineb').addClass('wpi-hide');
517
                            $('#wpinv-remove-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
518
                        }
519
                        
520
                        if (response.msg) {
521
                            msg = response.msg;
522
                        }
523
                    }
524
                    
525
                    $this.attr('disabled', false);
526
                    $this.closest('div').find('.wpi-refresh').remove();
527
                    
528
                    if (success) {
529
                        console.log(success);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
530
                        window.wpiConfirmed = true;
531
                        $('#wpinv-recalc-totals').click();
532
                        window.wpiConfirmed = false;
533
                    }
534
                    
535
                    if (msg) {
536
                        alert(msg);
537
                    }
538
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
539
            });
540
            
541
            $('#wpinv-remove-code').on('click', function(e) {
542
                e.preventDefault();
543
                var $this = $(this);
544
                var $form = $(this).closest('form[name="post"]');
545
                var invoice_id = parseInt($form.find('input#post_ID').val());
546
                var discount_code = $('#wpinv_discount', $form).val();
547
                if (!invoice_id > 0) {
548
                    return false;
549
                }
550
                
551
                if (!invoice_id > 0 || !parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0 || !discount_code) {
552
                    $this.removeClass('wpi-inlineb').addClass('wpi-hide');
553
                    $('#wpinv_discount', $form).attr('readonly', false).val('');
554
                    $('#wpinv-apply-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
555
                    return false;
556
                }
557
                
558
                $this.attr('disabled', true);
559
                $this.after('<span class="wpi-refresh">&nbsp;&nbsp;<i class="fa fa-spin fa-refresh"></i></span>');
560
561
                var data = {
562
                    action: 'wpinv_admin_remove_discount',
563
                    invoice_id: invoice_id,
564
                    code: discount_code,
565
                    _nonce: WPInv_Admin.wpinv_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
566
                };
567
                
568
                $.post(WPInv_Admin.ajax_url, data, function(response) {
569
                    var msg, success;
570
                    if (response && typeof response == 'object') {
571
                        if (response.success === true) {
572
                            success = true;
573
                            
574
                            $this.removeClass('wpi-inlineb').addClass('wpi-hide');
575
                            $('#wpinv_discount', $form).attr('readonly', false).val('');
576
                            $('#wpinv-apply-code', $form).removeClass('wpi-hide').addClass('wpi-inlineb');
577
                        }
578
                        
579
                        if (response.msg) {
580
                            msg = response.msg;
581
                        }
582
                    }
583
                    
584
                    $this.attr('disabled', false);
585
                    $this.closest('div').find('.wpi-refresh').remove();
586
                    
587
                    if (success) {
588
                        window.wpiConfirmed = true;
589
                        $('#wpinv-recalc-totals').click();
590
                        window.wpiConfirmed = false;
591
                    }
592
                    
593
                    if (msg) {
594
                        alert(msg);
595
                    }
596
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
597
            });
598
        },
599
        remove_item: function() {
600
            // Remove a remove from a purchase
601
            $('#wpinv_items').on('click', '.wpinv-item-remove', function(e) {
602
                var item = $(this).closest('.item');
603
                var count = $(document.body).find('.wpinv-line-items > .item').length;
604
                var qty = parseInt($('.qty', item).data('quantity'));
605
                qty = qty > 0 ? qty : 1;
606
                if (count === 1 && qty == 1) {
607
                    alert(WPInv_Admin.OneItemMin);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
608
                    return false;
609
                }
610
                if (confirm(WPInv_Admin.DeleteInvoiceItem)) {
0 ignored issues
show
Complexity Best Practice introduced by
There is no return statement if confirm(WPInv_Admin.DeleteInvoiceItem) is false. Are you sure this is correct? If so, consider adding return; explicitly.

This check looks for functions where a return statement is found in some execution paths, but not in all.

Consider this little piece of code

function isBig(a) {
    if (a > 5000) {
        return "yes";
    }
}

console.log(isBig(5001)); //returns yes
console.log(isBig(42)); //returns undefined

The function isBig will only return a specific value when its parameter is bigger than 5000. In any other case, it will implicitly return undefined.

This behaviour may not be what you had intended. In any case, you can add a return undefined to the other execution path to make the return value explicit.

Loading history...
611
                    e.preventDefault();
612
                    var metaBox = $('#wpinv_items_wrap');
613
                    var gdTotals = $('.wpinv-totals', metaBox);
614
                    var item_id = item.data('item-id');
615
                    var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
616
                    var index = $(item).index();
617
                    if (!(item_id > 0 && invoice_id > 0)) {
618
                        return false;
619
                    }
620
                    wpinvBlock(metaBox);
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
621
                    var data = {
622
                        action: 'wpinv_remove_invoice_item',
623
                        invoice_id: invoice_id,
624
                        item_id: item_id,
625
                        index: index,
626
                        _nonce: WPInv_Admin.invoice_item_nonce
627
                    };
628
                    $.post(WPInv_Admin.ajax_url, data, function(response) {
629
                        item.remove();
630
                        wpinvUnblock(metaBox);
631
                        if (response && typeof response == 'object') {
632
                            if (response.success === true) {
633
                                WPInv.update_inline_items(response.data, metaBox, gdTotals);
634
                            } else if (response.msg) {
635
                                alert(response.msg);
636
                            }
637
                        }
638
                    });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
639
                }
640
            });
641
        },
642
        add_item: function() {
643
            // Add a New Item from the Add Items to Items Box
644
            $('.wpinv-actions').on('click', '#wpinv-add-item', function(e) {
645
                e.preventDefault();
646
                var metaBox = $('#wpinv_items_wrap');
647
                var gdTotals = $('.wpinv-totals', metaBox);
648
                var item_id = $('#wpinv_invoice_item').val();
649
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
650
                if (!(item_id > 0 && invoice_id > 0)) {
651
                    return false;
652
                }
653
                wpinvBlock(metaBox);
654
                var data = {
655
                    action: 'wpinv_add_invoice_item',
656
                    invoice_id: invoice_id,
657
                    item_id: item_id,
658
                    _nonce: WPInv_Admin.invoice_item_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
659
                };
660
                var user_id, country, state;
661
                if (user_id = $('[name="post_author_override"]').val()) {
662
                    data.user_id = user_id;
663
                }
664
                if (parseInt($('#wpinv_new_user').val()) == 1) {
665
                    data.new_user = true;
666
                }
667
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
668
                    data.country = country;
669
                }
670
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
671
                    data.state = state;
672
                }
673
                $.post(WPInv_Admin.ajax_url, data, function(response) {
674
                    wpinvUnblock(metaBox);
675
                    if (response && typeof response == 'object') {
676
                        if (response.success === true) {
677
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
678
                        } else if (response.msg) {
679
                            alert(response.msg);
680
                        }
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
681
                    }
682
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
683
            });
684
            $('.wpinv-actions').on('click', '#wpinv-new-item', function(e) {
685
                e.preventDefault();
686
                var $quickAdd = $('#wpinv-quick-add');
687
                if ($quickAdd.is(':visible')) {
688
                    $quickAdd.slideUp('fast');
689
                } else {
690
                    $quickAdd.slideDown('fast');
691
                }
692
                return false;
693
            });
694
            $('#wpinv-quick-add').on('click', '#wpinv-cancel-item', function(e) {
695
                e.preventDefault();
696
                var $quickAdd = $('#wpinv-quick-add');
697
                if ($quickAdd.is(':visible')) {
698
                    $quickAdd.slideUp('fast');
699
                } else {
700
                    $quickAdd.slideDown('fast');
701
                }
702
                $('[name="_wpinv_quick[name]"]', $quickAdd).val('');
703
                $('[name="_wpinv_quick[price]"]', $quickAdd).val('');
704
                $('[name="_wpinv_quick[qty]"]', $quickAdd).val(1);
705
                $('[name="_wpinv_quick[type]"]', $quickAdd).prop('selectedIndex',0);
706
                return false;
707
            });
708
            $('#wpinv-quick-add').on('click', '#wpinv-save-item', function(e) {
709
                e.preventDefault();
710
                var metaBox = $('#wpinv_items_wrap');
711
                var gdTotals = $('.wpinv-totals', metaBox);
712
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
713
                var item_title = $('[name="_wpinv_quick[name]"]', metaBox).val();
714
                var item_price = $('[name="_wpinv_quick[price]"]', metaBox).val();
715
                if (!(invoice_id > 0)) {
716
                    return false;
717
                }
718
                if (!item_title) {
719
                    $('[name="_wpinv_quick[name]"]', metaBox).focus();
720
                    return false;
721
                }
722
                if (item_price === '') {
723
                    $('[name="_wpinv_quick[price]"]', metaBox).focus();
724
                    return false;
725
                }
726
                wpinvBlock(metaBox);
727
                var data = {
728
                    action: 'wpinv_create_invoice_item',
729
                    invoice_id: invoice_id,
730
                    _nonce: WPInv_Admin.invoice_item_nonce
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
731
                };
732
                var fields = $('[name^="_wpinv_quick["]');
733
                for (var i in fields) {
0 ignored issues
show
Complexity introduced by
A for in loop automatically includes the property of any prototype object, consider checking the key using hasOwnProperty.

When iterating over the keys of an object, this includes not only the keys of the object, but also keys contained in the prototype of that object. It is generally a best practice to check for these keys specifically:

var someObject;
for (var key in someObject) {
    if ( ! someObject.hasOwnProperty(key)) {
        continue; // Skip keys from the prototype.
    }

    doSomethingWith(key);
}
Loading history...
734
                    data[fields[i]['name']] = fields[i]['value'];
735
                }
736
                var user_id, country, state;
737
                if (user_id = $('[name="post_author_override"]').val()) {
738
                    data.user_id = user_id;
739
                }
740
                if (parseInt($('#wpinv_new_user').val()) == 1) {
741
                    data.new_user = true;
742
                }
743
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
744
                    data.country = country;
745
                }
746
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
747
                    data.state = state;
748
                }
749
                $.post(WPInv_Admin.ajax_url, data, function(response) {
750
                    wpinvUnblock(metaBox);
751
                    if (response && typeof response == 'object') {
752
                        if (response.success === true) {
753
                            $('[name="_wpinv_quick[name]"]', metaBox).val('');
754
                            $('[name="_wpinv_quick[price]"]', metaBox).val('');
755
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
756
                        } else if (response.msg) {
757
                            alert(response.msg);
758
                        }
759
                    }
760
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
761
            });
762
        },
763
        recalculateTotals: function() {
764
            $('.wpinv-actions').on('click', '#wpinv-recalc-totals', function(e) {
765
                e.preventDefault();
766
                var metaBox = $('#wpinv_items_wrap');
767
                var gdTotals = $('.wpinv-totals', metaBox);
768
                var invoice_id = metaBox.closest('form[name="post"]').find('input#post_ID').val();
769
                if (!invoice_id > 0) {
770
                    return false;
771
                }
772
                if (!parseInt($(document.body).find('.wpinv-line-items > .item').length) > 0) {
773
                    if (!window.wpiConfirmed) {
774
                        alert(WPInv_Admin.emptyInvoice);
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
775
                        $('#wpinv_invoice_item').focus();
776
                    }
777
                    return false;
778
                }
779
                if (!window.wpiConfirmed && !window.confirm(WPInv_Admin.confirmCalcTotals)) {
780
                    return false;
781
                }
782
                wpinvBlock(metaBox);
783
                var data = {
784
                    action: 'wpinv_admin_recalculate_totals',
785
                    invoice_id: invoice_id,
786
                    _nonce: WPInv_Admin.wpinv_nonce
787
                };
788
                var user_id, country, state;
789
                if (user_id = $('[name="post_author_override"]').val()) {
790
                    data.user_id = user_id;
791
                }
792
                if (parseInt($('#wpinv_new_user').val()) == 1) {
793
                    data.new_user = true;
794
                }
795
                if (country = $('#wpinv-address [name="wpinv_country"]').val()) {
796
                    data.country = country;
797
                }
798
                if (state = $('#wpinv-address [name="wpinv_state"]').val()) {
799
                    data.state = state;
800
                }
801
                $.post(WPInv_Admin.ajax_url, data, function(response) {
802
                    wpinvUnblock(metaBox);
803
                    if (response && typeof response == 'object') {
804
                        if (response.success === true) {
805
                            WPInv.update_inline_items(response.data, metaBox, gdTotals);
806
                        }
807
                    }
808
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
809
            });
810
        },
811
        update_inline_items: function(data, metaBox, gdTotals) {
812
            if (data.discount > 0) {
813
                data.discountf = '&ndash;' + data.discountf;
814
            }
815
            $('.wpinv-line-items', metaBox).html(data.items);
816
            $('.subtotal .total', gdTotals).html(data.subtotalf);
817
            $('.tax .total', gdTotals).html(data.taxf);
818
            $('.discount .total', gdTotals).html(data.discountf);
819
            $('.total .total', gdTotals).html(data.totalf);
820
            $('#wpinv-details input[name="wpinv_discount"]').val(data.discount);
821
            $('#wpinv-details input[name="wpinv_tax"]').val(data.tax);
822
        },
823
        prices: function() {
824
            var $this = this;
825
            $this.check_recurring('#wpinv_is_recurring');
826
            $(document.body).on('change', '#wpinv_is_recurring', 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...
827
                $this.check_recurring(this);
828
            });
829
            $(document.body).on('change', '#wpinv_recurring_period', 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...
830
                $this.recurring_period($(this).val());
831
            });
832
        },
833
        check_recurring: function(el) {
834
            var $obj = $('.wpinv-row-recurring-fields');
835
            this.recurring_period($('#wpinv_recurring_period').val());
836
            if ($(el).is(':checked')) {
837
                $obj.removeClass('wpinv-recurring-n').addClass('wpinv-recurring-y');
838
                $('input', $obj).prop('disabled', false);
839
                $('select', $obj).prop('disabled', false);
840
            } else {
841
                $obj.removeClass('wpinv-recurring-y').addClass('wpinv-recurring-n');
842
                $('input', $obj).prop('disabled', true);
843
                $('select', $obj).prop('disabled', true);
844
            }
845
        },
846
        recurring_period: function(val) {
847
            var txt = '';
848
            if (typeof val != 'undefined') {
849
                txt = $('#wpinv_recurring_period').find('option[value="' + val + '"]').data('text');
850
                txt = txt !== 'undefined' ? txt : '';
851
            }
852
            $('#wpinv_interval_text').text(txt);
853
            this.recurring_interval(val);
854
        },
855
        recurring_interval: function(period) {
856
            var limit;
857
            switch (period) {
858
                case 'W':
859
                    limit = 52;
860
                    break;
861
                case 'M':
862
                    limit = 24;
863
                    break;
864
                case 'Y':
865
                    limit = 5;
866
                    break;
867
                default:
0 ignored issues
show
Coding Style Comprehensibility introduced by
The default case is not the last statement in this switch statement. For the sake of readability, you might want to move it to the end of the statement.
Loading history...
868
                case 'D':
869
                    limit = 90;
870
                    break;
871
            }
872
            var optioins = '';
873
            for (i = 1; i <= limit; i++) {
0 ignored issues
show
Bug introduced by
The variable limit seems to not be initialized for all possible execution paths.
Loading history...
Bug introduced by
The variable i 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.i.
Loading history...
874
                optioins += '<option value="' + i + '">' + i + '</option>';
875
            }
876
            var $el = $('#wpinv_interval');
877
            var val = $el.val();
878
            $el.find('option').remove();
879
            $el.append(optioins);
880
            $el.val(val);
881
            $el.find('option[value="' + val + '"]').attr('selected', 'selected');
882
        },
883
        setup_tools: function() {
884
            $('#wpinv_tools_table').on('click', '.wpinv-tool', function(e) {
885
                var $this = $(this);
886
                e.preventDefault();
887
                var mBox = $this.closest('tr');
888
                if (!confirm(WPInv_Admin.AreYouSure)) {
0 ignored issues
show
Bug introduced by
The variable WPInv_Admin seems to be never declared. If this is a global, consider adding a /** global: WPInv_Admin */ 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...
889
                    return false;
890
                }
891
                var tool = $this.data('tool');
892
                $(this).prop('disabled', true);
893
                if (!tool) {
894
                    return false;
895
                }
896
                $('.wpinv-run-' + tool).remove();
897
                if (!mBox.hasClass('wpinv-tool-' + tool)) {
898
                    mBox.addClass('wpinv-tool-' + tool);
899
                }
900
                mBox.addClass('wpinv-tool-active');
901
                mBox.after('<tr class="wpinv-tool-loader wpinv-run-' + tool + '"><td colspan="3"><span class="wpinv-i-loader"><i class="fa fa-spin fa-refresh"></i></span></td></tr>');
902
                var data = {
903
                    action: 'wpinv_run_tool',
904
                    tool: tool,
905
                    _nonce: WPInv_Admin.wpinv_nonce
906
                };
907
                $.post(WPInv_Admin.ajax_url, data, function(res) {
908
                    mBox.removeClass('wpinv-tool-active');
909
                    $this.prop('disabled', false);
910
                    var msg = prem = '';
0 ignored issues
show
Bug introduced by
The variable prem 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.prem.
Loading history...
911
                    if (res && typeof res == 'object') {
912
                        msg = res.data ? res.data.message : '';
913
                        if (res.success === false) {
914
                            prem = '<span class="wpinv-i-check wpinv-i-error"><i class="fa fa-exclamation-circle"></i></span>';
915
                        } else {
916
                            prem = '<span class="wpinv-i-check"><i class="fa fa-check-circle"></i></span>';
917
                        }
918
                    }
919
                    if (msg) {
920
                        $('.wpinv-run-' + tool).addClass('wpinv-tool-done').find('td').html(prem + msg + '<span class="wpinv-i-close"><i class="fa fa-close"></i></span>');
921
                    } else {
922
                        $('.wpinv-run-' + tool).remove();
923
                    }
924
                });
0 ignored issues
show
Best Practice introduced by
There is no return statement in this branch, but you do return something in other branches. Did you maybe miss it? If you do not want to return anything, consider adding return undefined; explicitly.
Loading history...
925
            });
926
            $('#wpinv_tools_table').on('click', '.wpinv-i-close', 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...
927
                $(this).closest('tr').fadeOut();
928
            });
929
        }
930
    };
931
    $('.post-type-wpi_invoice form#post #titlediv [name="post_title"]').attr('readonly', true);
932
    $('.post-type-wpi_item.wpi-editable-n form#post').attr('action', 'javascript:void(0)');
933
    $('.post-type-wpi_item.wpi-editable-n #submitdiv #major-publishing-actions').remove();
934
    $('.post-type-wpi_item.wpi-editable-n #submitdiv #misc-publishing-actions a.edit-post-status').remove();
935
    $('.post-type-wpi_item .posts .wpi-editable-n').each(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...
936
        $('.check-column [type="checkbox"]', $(this)).attr('disabled', true);
937
    });
938
    WPInv.init();
939
    var WPInv_Export = {
940
        init: function() {
941
            this.submit();
942
            this.clearMessage();
943
        },
944
        submit: function() {
945
            var $this = this;
946
            $('.wpi-export-form').submit(function(e) {
947
                e.preventDefault();
948
                var $form = $(this);
949
                var submitBtn = $form.find('input[type="submit"]');
950
                if (!submitBtn.attr('disabled')) {
951
                    var data = $form.serialize();
952
                    submitBtn.attr('disabled', true);
953
                    $form.find('.wpi-msg-wrap').remove();
954
                    $form.append('<div class="wpi-msg-wrap"><div class="wpi-progress"><div></div><span>0%</span></div><span class="wpi-export-loader"><i class="fa fa-spin fa-spinner"></i></span></div>');
955
                    // start the process
956
                    $this.step(1, data, $form, $this);
957
                }
958
            });
959
        },
960
        step: function(step, data, $form, $this) {
961
            var message = $form.find('.wpi-msg-wrap');
962
            var post_data = {
963
                action: 'wpinv_ajax_export',
964
                step: step,
965
                data: data,
966
            };
967
            $.ajax({
968
                url: ajaxurl,
0 ignored issues
show
Bug introduced by
The variable ajaxurl seems to be never declared. If this is a global, consider adding a /** global: ajaxurl */ 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...
969
                type: 'POST',
970
                cache: false,
971
                dataType: 'json',
972
                data: post_data,
973
                beforeSend: function(jqXHR, settings) {},
0 ignored issues
show
Unused Code introduced by
The parameter jqXHR 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...
Unused Code introduced by
The parameter settings 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...
974
                success: function(res) {
975
                    if (res && typeof res == 'object') {
976
                        if (res.success) {
977
                            if ('done' == res.data.step || res.data.done >= 100) {
978
                                $form.find('input[type="submit"]').removeAttr('disabled');
979
                                $('.wpi-progress > span').text(parseInt(res.data.done) + '%');
980
                                $('.wpi-progress div').animate({
981
                                    width: res.data.done + '%'
982
                                }, 100, function() {});
983
                                if (res.msg) {
984
                                    message.html('<div id="wpi-export-success" class="updated notice is-dismissible"><p>' + msg + '<span class="notice-dismiss"></span></p></div>');
0 ignored issues
show
Bug introduced by
The variable msg seems to be never declared. If this is a global, consider adding a /** global: 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...
985
                                }
986
                                if (res.data.file && res.data.file.u) {
987
                                    message.append('<span class="wpi-export-file"><a href="' + res.data.file.u + '" target="_blank"><i class="fa fa-download"></i> ' + res.data.file.u + '</a><span> - ' + res.data.file.s + '<span><span>');
988
                                }
989
                                message.find('.wpi-export-loader').html('<i class="fa fa-check-circle"></i>');
990
                            } else {
991
                                var next = parseInt(res.data.step) > 0 ? parseInt(res.data.step) : 1;
992
                                $('.wpi-progress > span').text(parseInt(res.data.done) + '%');
993
                                $('.wpi-progress div').animate({
994
                                    width: res.data.done + '%'
995
                                }, 100, function() {});
996
                                $this.step(parseInt(next), data, $form, $this);
997
                            }
998
                        } else {
999
                            $form.find('input[type="submit"]').removeAttr('disabled');
1000
                            if (res.msg) {
1001
                                message.html('<div class="updated error"><p>' + res.msg + '</p></div>');
1002
                            }
1003
                        }
1004
                    } else {
1005
                        $form.find('input[type="submit"]').removeAttr('disabled');
1006
                        message.html('<div class="updated error">' + res + '</div>');
1007
                    }
1008
                }
1009
            }).fail(function(res) {
1010
                if (window.console && window.console.log) {
1011
                    console.log(res);
0 ignored issues
show
Debugging Code introduced by
console.log looks like debug code. Are you sure you do not want to remove it?
Loading history...
1012
                }
1013
            });
1014
        },
1015
        clearMessage: function() {
1016
            $('body').on('click', '#wpi-export-success .notice-dismiss', function() {
1017
                $(this).closest('#wpi-export-success').parent().slideUp('fast');
1018
            });
1019
        }
1020
    };
1021
    WPInv_Export.init();
1022
1023
});
1024
1025
function wpinvBlock(el, message) {
1026
    message = typeof message != 'undefined' && message !== '' ? message : '';
1027
    el.block({
1028
        message: '<i class="fa fa-spinner fa-pulse fa-2x"></i>' + message,
1029
        overlayCSS: {
1030
            background: '#fff',
1031
            opacity: 0.6
1032
        }
1033
    });
1034
}
1035
1036
function wpinvUnblock(el) {
1037
    el.unblock();
1038
}