/*
 *   Copyright (c) 2023
 *   All rights reserved.
 */
var num_decimals = 4;

/*
$(binder)
//.dataBind({modelAttribute:'firstName', selector:'#firstName', eventToBind:'keyup change'})
//.dataBind({modelAttribute:'firstName', selector:'#nameEcho'})
;
$(binder).on('change.firstName', function(event){
    if(event.newValue!==event.oldValue){
    }
    $(binder).attr('entity_name', binder.firstName);
});*/
function getValue(o, path, fb, fbFalsy) {
    if (!o || !path) return fb;
    return path.split('.').reduce((o, p) => o && typeof o !== 'string' && o.hasOwnProperty(p) ? !o[p] && fbFalsy ? fb : o[p] : fb, o);
}

function register_doc_currency(base, target, value) {
    var found_base_rate = doc_rates.hasOwnProperty([base]); //getValue(doc_rates, [post_data.base_currency], false);
    var found_target_rate = doc_rates.hasOwnProperty([target]);

    if (found_base_rate) {
        doc_rates[base][target] = value;
    } else {
        doc_rates[base] = {
            [target]: value
        };
    }

    if (found_target_rate) {
        doc_rates[target][base] = roundToX(1 / value, 4);
    } else {
        doc_rates[target] = {
            [target]: roundToX(1 / value, 4)
        };
    }

}

function roundToX(num, X = num_decimals) {
    //return +(Math.round(num + "e+"+X)  + "e-"+X);
    return parseFloat(num.toFixed(num_decimals));
}

function format_money(total, excludeSymbol) {

    if (typeof (excludeSymbol) != 'undefined' && excludeSymbol) {
        return accounting.formatMoney(total, {
            symbol: ''
        });
    }

    return accounting.formatMoney(total);
}


var convert_rates = [];

(function ($) {
    // Empty object, we are going to use this as our Queue
    var ajaxQueue = $({});

    $.ajaxQueue = function (ajaxOpts) {
        // hold the original complete function
        var oldComplete = ajaxOpts.complete;

        // queue our ajax request
        ajaxQueue.queue(function (next) {

            // create a complete callback to fire the next event in the queue
            ajaxOpts.complete = function () {
                // fire the original complete if it was there
                if (oldComplete) oldComplete.apply(this, arguments);
                next(); // run the next query in the queue
            };

            // run the query
            $.ajax(ajaxOpts);
        });
    };

})(jQuery);


function process_doc_currency() {
    ////console.log(' change invoice curency');
    displayCurrentCurrencyName();
    var rows = $('.list_items div.item');
    var $doc_currency = $('#currency').val();
    var $doc_currency_name = $('#currency option:selected').text();

    var $line_currency = $('#invoice_item_currency').val();
    var $unitary_price = $('.main [name="rate"]').val();
    var $converted_price = $('.main .invoice_item_price_converted').val();
    var $invoice_item_currency_rate = $('.main .invoice_item_currency_rate').val();
    var iteration = 0;
    var notInCondition = 0;
    var conditionUpdate = 0;

    $.each(rows, function (row_key) {
        select_elem_cur = $(rows[row_key]).find('select.dropdown_currency');
        cur_id = $('option:selected', select_elem_cur).val();
        item_currency = cur_id;
        if (item_currency === $doc_currency) {

        } else {
            notInCondition++;
        }
    })

    ////console.log("Total rows in else condition: " + notInCondition);
    $.each(rows, function (row_key) {
        iteration++;

        select_elem_cur = $(rows[row_key]).find('select.dropdown_currency');
        cur_id = $('option:selected', select_elem_cur).val();

        item_currency = cur_id; //$(this).find('.dropdown_currency').selectpicker('val');
        item_rate = $(rows[row_key]).find('.invoice_item_currency_rate').val();
        item_price = $(rows[row_key]).find('.item_rate').val();
        item_price_converted = $(rows[row_key]).find('.invoice_item_price_converted').val();


        /**
         * Quantity
         */
        quantity = $(rows[row_key]).find('[data-quantity]').val();
        if (quantity === '') {
            quantity = 1;
            $(rows[row_key]).find('[data-quantity]').val(1);
        }


        if ($(rows[row_key]).find('.rate input').val() === undefined) {
            ////console.log('No rate at line '+iteration);
        }

        /**
         * Cases when selected currency is the same as document currency
         */
        if (item_currency === $doc_currency) {
            // CUrrent value
            $unitary_item_price = $(rows[row_key]).find('.item_rate').val();

            /*
            _amount = accounting.toFixed($(this).find('.rate input').val() * quantity, app.options.decimal_places);
            $(this).find('.invoice_item_currency_rate').hide();
            $(this).find('.invoice_item_price_converted').hide();
            $(this).find('.on_rate_convert').hide();
            */

            //$(rows[row_key]).find('.invoice_item_currency_rate').hide();
            //$(rows[row_key]).find('.invoice_item_price_converted').hide();
            $(rows[row_key]).find('.on_rate_convert').hide();

            $(rows[row_key]).find('.invoice_item_currency_rate').val(1);
            //  $(this).find('.list_items .item_rate').val(item_price_converted);
            $(rows[row_key]).find('.invoice_item_price_converted').val($unitary_item_price);

            // Calculate
            crm_calculate_total();

        } else {
            invoiceDisableSave(true); // enable save

            var unitary_item_price = $(rows[row_key]).find('.item_rate').val();
            var is_triggered = true;
            //get rate
            data = {
                base_currency: $doc_currency,
                target_currency: item_currency,
                invoice_date: $('#date').val()
            },

                $.ajaxQueue({
                    url: admin_url + "core/bnr/get_daily_bnr",
                    dataType: "json",
                    async: true,
                    type: "post",
                    data: data,
                    success: function (response) {
                        //#curselect
                        conditionUpdate++;
                        $(rows[row_key]).find('.invoice_item_currency_rate').val(response.rate); //#3rd

                        $(rows[row_key]).find('.rateRowInput').addClass('block').removeClass('hidden');
                        $(rows[row_key]).find('.priceRowInput').addClass('block').removeClass('hidden');

                        if ((response.rate) == 1) {
                            $(rows[row_key]).find('.rateRowInput').addClass('hidden').removeClass('block');
                            $(rows[row_key]).find('.priceRowInput').addClass('hidden').removeClass('block');
                        } else {
                            $(rows[row_key]).find('.rateRowInput').addClass('block').removeClass('hidden');
                            $(rows[row_key]).find('.priceRowInput').addClass('block').removeClass('hidden');
                        }
                        $new_conv_from = calculateConvertCases(unitary_item_price, response);

                        $(rows[row_key]).find('.invoice_item_price_converted').val($new_conv_from);

                        /**
                         * OLD

                         if (item_currency == 3 && $doc_currency != 3) {
                         $new_conv_from = roundToX($unitary_item_price / response.rate);
                         } else if ($doc_currency == 3 && item_currency != 3) {
                         $new_conv_from = roundToX($unitary_item_price / response.rate);

                         } else {
                         $new_conv_from = roundToX($unitary_item_price * response.rate);
                         }
                         */

                        convert_rates[item_currency + "_" + $doc_currency] = response.rate;
                        $(rows[row_key]).find('.item_rate').val(unitary_item_price);

                        // Calculate
                        crm_calculate_total();
                        is_triggered = false;
                        if (notInCondition === conditionUpdate) {
                            invoiceDisableSave(false); // enable save
                        }
                    }
                });


            //$(rows[row_key]).find('.invoice_item_currency_rate').show();

            $(rows[row_key]).find('.invoice_item_price_converted').show();
            //$(rows[row_key]).find('.on_rate_convert').show();
            //////console.log('Convert from '+$doc_currency+' to '+$line_currency);


        }

        ////console.log('ready each row');
        row = $(rows[row_key]);

    });


}


function crm_calculate_total() {

    console.warn('crm_calculate_totala 2');


    if ($('body').hasClass('no-calculate-total')) {
        return false;
    }

    var $doc_currency = $('#currency').val();
    var $doc_currency_name = $('#currency option:selected').text();

    var
        item_currency,
        calculated_tax,
        taxrate,
        item_taxes,
        alltaxes = {},
        row,
        _amount,
        _tax_name,
        taxes = {},
        invoice_currencies = {},
        currency_display = '',
        taxes_rows = [],
        subtotal = 0,
        total = 0,
        quantity = 1,
        total_discount_calculated = 0,
        rows = $('.list_items div.item'),
        discount_area = $('#discount_area'),
        adjustment = $('input[name="adjustment"]').val(),
        discount_percent = $('input[name="discount_percent"]').val(),
        discount_fixed = $('input[name="discount_total"]').val(),
        discount_total_type = $('.discount-total-type.selected'),
        discount_type = $('select[name="discount_type"]').val();


    $('.tax-area').remove();

    var iteration = 0;
    $.each(rows, function () {

        iteration++;
        var select_elem_cur = $(this).find('select.dropdown_currency');
        var cur_id = $('option:selected', select_elem_cur).attr("data-cur-id");
        cur_id = $('option:selected', select_elem_cur).val();

        if (cur_id === undefined) {
            ////console.log('No currency at line '+iteration);
        }

        item_currency = cur_id; //$(this).find('.dropdown_currency').selectpicker('val');
        var item_rate = $(this).find('.invoice_item_currency_rate').val();
        ////console.log('item rate '+ item_rate);
        invoice_currencies[cur_id + slugify(item_rate)] = {
            name: $('option:selected', select_elem_cur).text(),
            rate: item_rate
        };


        quantity = $(this).find('[data-quantity]').val();

        if (quantity === '') {
            quantity = 1;
            $(this).find('[data-quantity]').val(1);
        }

        if ($(this).find('.rate input').val() === undefined) {
            //  ////console.log('No rate at line '+iteration);
        }


        if (item_currency === $doc_currency) {
            _amount = accounting.toFixed($(this).find('.priceRowInput input').val() * quantity, app.options.decimal_places);
            /*$(this).find('.invoice_item_currency_rate').hide();
            $(this).find('.invoice_item_price_converted').hide();
            $(this).find('.on_rate_convert').hide();*/
        } else {
            _amount = accounting.toFixed($(this).find('.priceRowInput input').val() * quantity, app.options.decimal_places);
            /*$(this).find('.invoice_item_currency_rate').show();
            $(this).find('.invoice_item_price_converted').show();
            $(this).find('.on_rate_convert').show();*/

            //#cezar$(this).find('.invoice_item_currency_rate').hide();
            //#$(this).find('.item_rate').hide();
        }

        ////console.log('amount' + _amount);
        _amount = parseFloat(_amount);
        //      $(this).find('.amount').html(format_money(_amount, true));
        subtotal += _amount;
        row = $(this);

        console.log({
            'currency': cur_id, // 284
            'rate': item_rate,
            'invoice_currencies': invoice_currencies,
            'quantity': quantity,
            '_amount': _amount,
            'subtotal': subtotal,
            'calculated_tax': calculated_tax,
            'item_taxes': 'item_taxes ' + item_taxes
        });

        if (settings.vat_payer == 1 || settings.vat_payer == '1') {
            item_taxes = $(this).find('select.tax').selectpicker('val');


            /*if (item_taxes) {
                $.each(item_taxes, function (i, taxname) {
                    taxrate = row.find('select.tax [value="' + taxname + '"]').data('taxrate');
                    calculated_tax = (_amount / 100 * taxrate);
                    if (!taxes.hasOwnProperty(taxname)) {
                        if (taxrate != 0) {
                            _tax_name = taxname.split('|');
                            tax_row = '<tr class="tax-area"><td>' + _tax_name[0] + '(' + taxrate + '%)</td><td id="tax_id_' + slugify(taxname) + '"></td></tr>';
                            $(discount_area).after(tax_row);
                            taxes[taxname] = calculated_tax;
                        }
                    } else {
                        // Increment total from this tax
                        taxes[taxname] = taxes[taxname] += calculated_tax;
                    }
                });
            }*/

            if (item_taxes) {
                var taxname = item_taxes;
                taxrate = row.find('select.tax [value="' + taxname + '"]').data('taxrate');
                calculated_tax = (_amount / 100 * taxrate);
                if (!taxes.hasOwnProperty(taxname)) {
                    if (taxrate != 0) {
                        _tax_name = taxname.split('|');
                        var tax_row = '<tr class="tax-area"><td>' + _tax_name[0] + '(' + taxrate + '%)</td><td id="tax_id_' + slugify(taxname) + '"></td></tr>';
                        $(discount_area).after(tax_row);
                        taxes[taxname] = calculated_tax;
                    }
                } else {
                    // Increment total from this tax
                    taxes[taxname] = taxes[taxname] += calculated_tax;
                }

                alltaxes[taxname] = true;

            }

        } //if vat payer

    });


    ////console.log('subtotal =' + subtotal);
    // Discount by percent
    if ((discount_percent !== '' && discount_percent != 0) && discount_type == 'before_tax' && discount_total_type.hasClass('discount-type-percent')) {
        total_discount_calculated = (subtotal * discount_percent) / 100;
    } else if ((discount_fixed !== '' && discount_fixed != 0) && discount_type == 'before_tax' && discount_total_type.hasClass('discount-type-fixed')) {
        total_discount_calculated = discount_fixed;
    }

    if (typeof (settings) != "undefined" && settings !== null) {
        if (settings.vat_payer == 1 || settings.vat_payer == '1') {
            $.each(taxes, function (taxname, total_tax) {
                if ((discount_percent !== '' && discount_percent != 0) && discount_type == 'before_tax' && discount_total_type.hasClass('discount-type-percent')) {
                    total_tax_calculated = (total_tax * discount_percent) / 100;
                    total_tax = (total_tax - total_tax_calculated);
                } else if ((discount_fixed !== '' && discount_fixed != 0) && discount_type == 'before_tax' && discount_total_type.hasClass('discount-type-fixed')) {
                    var t = (discount_fixed / subtotal) * 100;
                    total_tax = (total_tax - (total_tax * t) / 100);
                }

                total += total_tax;
                total_tax = valueWCurrency(accounting.toFixed(total_tax, app.options.decimal_places), $doc_currency, $doc_currency_name);
                $('#tax_id_' + slugify(taxname)).html(total_tax);
            });


            if (Object.keys(alltaxes).length > 1) {
                discount_fixed = 0;
                discount_percent = 0;
                $('.input-discount-fixed').val(0);
                $('.input-discount-percent').val(0);

                $('#discount-total-type-dropdown').find('.discount-total-type.selected').addClass('last-selected').removeClass('selected');
                $('#discount_area').hide();
                //$('.discount-total-type-selected').html($(this).text());

                /*
                $('.input-discount-fixed').addClass('hide').val(0);
                $('.input-discount-fixed').addClass('disabled');
                if ($(this).hasClass('discount-type-percent')) {
                    //$('.input-discount-fixed').addClass('hide').val(0);
                    //$('.input-discount-percent').removeClass('hide');
                } else {
                    $('.discount-total-type-selected').html('%');
                    $('.input-discount-percent').removeClass('hide');
                    $('.input-discount-fixed').addClass('hide').val(0);
                    $('#discount_percent-error').remove();
                }*/

            } else {
                //$('.input-discount-fixed').removeClass('disabled');
                $('#discount_area').show();
                $('#discount-total-type-dropdown').find('.discount-total-type.last-selected').addClass('selected').removeClass('last-selected');
            }


        } //if vat_payer
    }


    $.each(invoice_currencies, function (id, cur) {
        ////console.log(cur);
        if (cur.name != $doc_currency_name) {
            currency_display += '1 ' + cur.name + ' = ' + cur.rate + " " + $doc_currency_name + '<br />';
        }

        $('#currency_display').html(currency_display);
    });


    total = (total + subtotal);

    var test = {
        discount_percent: discount_percent,
        discount_type: discount_type,
        discount_total_type: discount_total_type.hasClass('discount-type-percent'),
        total: total,
        discount_fixed: discount_fixed,
        secondclass: discount_total_type.hasClass('discount-type-fixed'),
        discount_total_type_selected: $('.discount-total-type.selected')
    };

    ////console.log(test);

    // Discount by percent
    if ((discount_percent !== '' && discount_percent != 0) && discount_type == 'after_tax' && discount_total_type.hasClass('discount-type-percent')) {
        total_discount_calculated = (total * discount_percent) / 100;
        ////console.log(total_discount_calculated + ' first condition');
    } else if ((discount_fixed !== '' && discount_fixed != 0) && discount_type == 'after_tax' && discount_total_type.hasClass('discount-type-fixed')) {
        ////console.log(total_discount_calculated + ' 2nd condition');
        total_discount_calculated = discount_fixed;
    }

    total = total - total_discount_calculated;
    adjustment = parseFloat(adjustment);

    // Check if adjustment not empty
    if (!isNaN(adjustment)) {
        total = total + adjustment;
    }

    var discount_html = '-' + valueWCurrency(accounting.toFixed(total_discount_calculated, app.options.decimal_places), $doc_currency, $doc_currency_name);
    $('input[name="discount_total"]').val(accounting.toFixed(total_discount_calculated, app.options.decimal_places));

    // Append, format to html and display
    var obj = {
        'subtotal': subtotal,
        'doc_currency': $doc_currency

    }
    $('.discount-total').html(discount_html);
    $('.adjustment').html(valueWCurrency(adjustment, $doc_currency, $doc_currency_name));
    $('.subtotal').html(valueWCurrency(accounting.toFixed(subtotal, app.options.decimal_places), $doc_currency, $doc_currency_name) + hidden_input('subtotal', accounting.toFixed(subtotal, app.options.decimal_places)));
    $('.total').html(valueWCurrency(accounting.toFixed(total, app.options.decimal_places), $doc_currency, $doc_currency_name) + hidden_input('total', accounting.toFixed(total, app.options.decimal_places)));

    $(document).trigger('sales-total-calculated');

    $('.invoice_item_currency_rate').each(function () {
        var item_rate = $(this).val();

        if (item_rate == 1 || !item_rate.length) {
            $(this).closest('.rateRowInput').addClass('hidden').removeClass('block');
            $(this).closest('.item').find('.priceRowInput').addClass('hidden').removeClass('block');
        } else {
            $(this).closest('.rateRowInput').addClass('block').removeClass('hidden');
            $(this).closest('.item').find('.priceRowInput').addClass('block').removeClass('hidden');
        }

    });

    // var item_rate = $('.invoice_item_currency_rate').val();
    // if(item_rate == 1){
    //
    // }


}


function invoiceDisableSave(disabled = true) {
    /**
     * We select all buttons for saving invoice and disable them as long we make calculations
     */
    const saveButtons = document.querySelectorAll(".invoiceSave");

    if (saveButtons.length > 0) {
        // Disable all elements with class "invoiceSave"
        saveButtons.forEach(button => button.disabled = disabled);
    }
}


function reset_add_line_price(post_data) {
    $('#invoice_item_currency_rate').val('');
    rate = $('#rate').val();
    invoice_item_price_converted = $('#invoice_item_price_converted').val();
    $('#rate').prop('readonly', false);
    //$('#rate').val(invoice_item_price_converted);
    $('#invoice_item_price_converted').val('');
    $('#invoice_item_currency_rate').hide();
    $('#invoice_item_price_converted').hide();
    $('#rate').show();
    $('.on_rate_convert').hide();
}

/**
 * To be changed
 * @param {*} value
 * @param {*} $doc_currency_name
 */
function valueWCurrency(value, $doc_currency, $doc_currency_name) {
    switch ($doc_currency) {
        case '3':
            return value + ' lei';
            break;
        case '1':
            return '$' + value;
            break;
        case '2':
            return '€' + value;
            break;
        default:
            break;
    }
}

function update_add_line_price(post_data, mode = 'base2target') {
    post_data.invoice_date = $('#date').val()
    var $doc_currency = $('#currency').val();
    var $line_currency = $('#invoice_item_currency').val();

    if (mode == 'base2target') {

        var found_currency_rate = getValue(doc_rates, [post_data.base_currency] + '.' + [post_data.target_currency], false);
        if (found_currency_rate) {

            $('#invoice_item_currency_rate').val(found_currency_rate);
            $('#rate').prop('readonly', true);
            converted = roundToX(post_data.unitary_price / found_currency_rate);
            $('#invoice_item_price_converted').val(converted);
            $('#rate').val(post_data.unitary_price);

        } else {
            invoiceDisableSave(true); // disable save
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: post_data,
                success: function (response) {
                    ////console.log(response);
                    $('#invoice_item_currency_rate').val(response.rate);
                    $('#rate').prop('readonly', true);
                    converted = roundToX(post_data.unitary_price / response.rate);
                    $('#invoice_item_price_converted').val(converted);
                    $('#rate').val(post_data.unitary_price);
                    invoiceDisableSave(false); // enable save
                }
            });

            register_doc_currency(post_data.base_currency, post_data.target_currency, response.rate);

        }


        //$('#invoice_item_currency_rate').show();
        $('#invoice_item_price_converted').show();
        //$('.on_rate_convert').show();
        //////console.log('Convert from '+post_data.base_currency+' to '+post_data.target_currency);

    } else if (mode == 'manual_rate') {
        cur_rate = $('#invoice_item_currency_rate').val();
        converted_from = $('#invoice_item_price_converted').val();
        //converted = roundToX(post_data.unitary_price * cur_rate );
        //$('#invoice_item_price_converted').val(converted);
        unitary = roundToX(converted_from * cur_rate);
        $('#rate').val(unitary);
    } else if (mode == 'change_price') {
        cur_rate = $('#invoice_item_currency_rate').val();
        converted = roundToX(post_data.unitary_price * cur_rate);
        $('#invoice_item_price_converted').val(converted);
    } else if (mode == 'revert_rate') {
        /*$.ajax({
            url: admin_url+"core/bnr/get_daily_bnr",
            dataType: "json",
            type: "post",
            data: post_data,
            success: function(response) {
                ////console.log(response);
                $('#invoice_item_currency_rate').val(response.rate);
                $('#rate').prop('readonly',true);
                converted = roundToX(post_data.unitary_price / response.rate );
                $('#invoice_item_price_converted').val(converted);
                $('#rate').val(post_data.unitary_price);

            }
          });

        $('#invoice_item_currency_rate').show();
        $('#invoice_item_price_converted').show();
        $('.on_rate_convert').show();*/
    } else if (mode == 'new_currency_price') {
        var found_currency_rate = getValue(doc_rates, [post_data.base_currency] + '.' + [post_data.target_currency], false);
        ////console.log(found_currency_rate);
        if (found_currency_rate) {
            var form = $('.itemAddForm');
            converted = roundToX(post_data.unitary_price * found_currency_rate);
            form.find('.invoice_item_currency_rate').val(found_currency_rate);
            form.find('#rate').val(post_data.unitary_price);
            form.find('.invoice_item_price_converted').val(converted);

            if (found_currency_rate == 1) {
                form.find('.rateRowInput').addClass('hidden').removeClass('block');
                form.find('.priceRowInput').addClass('hidden').removeClass('block');
            } else {
                form.find('.rateRowInput').addClass('block').removeClass('hidden');
                form.find('.priceRowInput').addClass('block').removeClass('hidden');
            }
        } else {
            invoiceDisableSave(true); // disable save
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: post_data,
                success: function (response) {
                    ////console.log(response);
                    var converted_reverse = calculateConvertCases(post_data.unitary_price, response);

                    var form = $('.itemAddForm');
                    form.find('.invoice_item_currency_rate').val(response.rate);
                    form.find('#rate').val(post_data.unitary_price);
                    form.find('.invoice_item_price_converted').val(converted_reverse);

                    register_doc_currency(post_data.base_currency, post_data.target_currency, response.rate);

                    invoiceDisableSave(false); // enable save

                    if (response.rate == 1) {
                        form.find('.rateRowInput').addClass('hidden').removeClass('block');
                        form.find('.priceRowInput').addClass('hidden').removeClass('block');
                    } else {
                        form.find('.rateRowInput').addClass('block').removeClass('hidden');
                        form.find('.priceRowInput').addClass('block').removeClass('hidden');
                    }
                }
            });
        }
        //$('#invoice_item_currency_rate').show();
        //$('#rate').hide();
        //$('#rate').hide();
        //$('.on_rate_convert').show();

        /** #cezar on add product rate input dissapear
         if ($doc_currency == $line_currency) {
         $('#invoice_item_currency_rate').hide();
         $('#rate').show();
         $('#rate').prop('readonly', false);
         }else{
         $('#invoice_item_price_converted').show();
         $('#rate').hide();
         $('#invoice_item_price_converted').prop('readonly', false);
         }
         */
    }
}


var readyStateCheckInterval = setInterval(function () {
    if (document.readyState === "complete") {
        //RaiseEvent("DOCUMENT_READY");
        //Init();
        displayCurrentCurrencyName();
        ////console.log('1st');
        crm_calculate_total();

        //////console.log('ready state');
        clearInterval(readyStateCheckInterval);
    }
}, 1000);


/**
 * Display selected currency where asked
 */
function displayCurrentCurrencyName() {

    var $doc_currency = $('#currency').val();
    var $doc_currency_name = $('#currency option:selected').text();

    var spanElements = document.querySelectorAll('.needSelectedCurrency');


    spanElements.forEach(function (spanElement) {
        spanElement.textContent = $doc_currency_name;
    });
}


$(document).ready(function () {


    //<editor-fold TEST>

    //</editor-fold>


    //add new
    $('body').on('changed.bs.select', '#invoice_item_currency', function (e, clickedIndex, newValue, oldValue) {

        if (is_item_added) {
            is_item_added = false;
            return false;
        }

        // Get element ref
        $elem_line = $(this).closest('div.item');

        var $doc_currency = $('#currency').val();
        var $line_currency = $('#invoice_item_currency').val();
        var $unitary_price = $elem_line.find('[name="rate"]').val();

        if ($unitary_price == 0 || $unitary_price === undefined) {
            //return false;
        }

        post_data = {
            base_currency: $doc_currency,
            target_currency: $line_currency,
            unitary_price: $unitary_price,
            invoice_date: $('#date').val()
        };

        if ($doc_currency == $line_currency) {
            $($elem_line).find('.invoice_item_currency_rate').val(1);
            $($elem_line).find('.invoice_item_price_converted').val(post_data.unitary_price);
            reset_add_line_price(post_data);

            $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
            $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');

        } else {
            //get rate
            //update_add_line_price(post_data,'base2target');
            post_data = {
                base_currency: $doc_currency,
                target_currency: $line_currency,
                unitary_price: $unitary_price,
                invoice_date: $('#date').val()
            };

            var found_currency_rate = getValue(doc_rates, [post_data.base_currency] + '.' + [post_data.target_currency], false);

            invoiceDisableSave(true); // disable save
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: post_data,
                success: function (response) {
                    ////console.log(response);
                    var converted_reverse = calculateConvertCases(post_data.unitary_price, response);
                    $($elem_line).find('.invoice_item_price_converted').val(converted_reverse);
                    $($elem_line).find('.invoice_item_currency_rate').val(response.rate);

                    register_doc_currency(post_data.base_currency, post_data.target_currency, response.rate);
                    invoiceDisableSave(false); // enable save

                    if ((response.rate) == 1) {
                        $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
                        $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');
                    } else {
                        $($elem_line).find('.rateRowInput').addClass('block').removeClass('hidden');
                        $($elem_line).find('.priceRowInput').addClass('block').removeClass('hidden');
                    }
                }
            });


            //$('#invoice_item_currency_rate').show();
            //$('#invoice_item_price_converted').show();
            //$('#rate').hide();
            //$('.on_rate_convert').show();
        }

    });


    $('body').on('change', '#rate', function (e, clickedIndex, newValue, oldValue) {


        if (is_item_added) {
            is_item_added = false;
            return false;
        }

        // Get element ref
        $elem_line = $(this).closest('div.item');

        var $doc_currency = $('#currency').val();
        var $line_currency = $('#invoice_item_currency').val();
        var $unitary_price = $elem_line.find('[name="rate"]').val();

        if ($unitary_price == 0 || $unitary_price === undefined) {
            //return false;
        }

        post_data = {
            base_currency: $doc_currency,
            target_currency: $line_currency,
            unitary_price: $unitary_price,
            invoice_date: $('#date').val()
        };

        if ($doc_currency == $line_currency) {
            $($elem_line).find('.invoice_item_currency_rate').val(1);
            $($elem_line).find('.invoice_item_price_converted').val(post_data.unitary_price);
            reset_add_line_price(post_data);

            $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
            $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');

        } else {
            //get rate
            //update_add_line_price(post_data,'base2target');
            post_data = {
                base_currency: $doc_currency,
                target_currency: $line_currency,
                unitary_price: $unitary_price,
                invoice_date: $('#date').val()
            };

            var found_currency_rate = getValue(doc_rates, [post_data.base_currency] + '.' + [post_data.target_currency], false);

            invoiceDisableSave(true); // disable save
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: post_data,
                success: function (response) {
                    ////console.log(response);
                    var converted_reverse = calculateConvertCases(post_data.unitary_price, response);
                    $($elem_line).find('.invoice_item_price_converted').val(converted_reverse);
                    $($elem_line).find('.invoice_item_currency_rate').val(response.rate);

                    register_doc_currency(post_data.base_currency, post_data.target_currency, response.rate);
                    invoiceDisableSave(false); // enable save

                    if ((response.rate) == 1) {
                        $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
                        $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');
                    } else {
                        $($elem_line).find('.rateRowInput').addClass('block').removeClass('hidden');
                        $($elem_line).find('.priceRowInput').addClass('block').removeClass('hidden');
                    }
                }
            });


            //$('#invoice_item_currency_rate').show();
            //$('#invoice_item_price_converted').show();
            //$('#rate').hide();
            //$('.on_rate_convert').show();
        }

        e.stopImmediatePropagation();
    });

    $('body').on('change', '#invoice_item_currency_rate,#invoice_item_price_converted', function (e, clickedIndex, newValue, oldValue) {
        var $doc_currency = $('#currency').val();
        var $line_currency = $('#invoice_item_currency').val();
        var $unitary_price = $('.main [name="rate"]').val();

        post_data = {
            base_currency: $doc_currency,
            target_currency: $line_currency,
            unitary_price: $unitary_price
        };


        if ($doc_currency == $line_currency) {
            reset_add_line_price(post_data);
        } else {
            update_add_line_price(post_data, 'manual_rate');
        }
        e.stopImmediatePropagation();
    });

    //edit
    $('body').on('changed.bs.select', '.dropdown_currency', function (e, clickedIndex, hasNewValue, oldValue) {

        /*if(is_triggered !== undefined){
            if(is_triggered){
                return false;
            }
        }*/

        var $doc_currency = $('#currency').val();
        var $doc_currency_name = $('#currency option:selected').text();
        var $line_currency = $(this).val();
        //////console.log($line_currency);
        var item_line = $(this).closest('div.item').attr('item');
        $elem_line = $(this).closest('div.item');

        var $unitary_price = $($elem_line).find('.item_rate').val();
        var $converted_from = $($elem_line).find('.invoice_item_price_converted').val();

        if ($doc_currency === $line_currency) {
            //////console.log('line currency changed back to doc currency');
            if (hasNewValue) {
                var $current_converted_price = $($elem_line).find('.invoice_item_price_converted').val();
                var $item_rate = $($elem_line).find('.item_rate').val();

                // -----------------------------------------------------------------
                /**
                 * Set Curs and Pret when currency is selected back to invoice currency
                 */
                $($elem_line).find('.invoice_item_currency_rate').val(1);
                $($elem_line).find('.invoice_item_price_converted').val($item_rate);

                $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
                $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block'); //#2nd


                //$($elem_line).find('.item_rate').val($current_converted_price);
                //$($elem_line).find('.item_rate').prop('readonly', false);
                //$($elem_line).find('.invoice_item_currency_rate').hide();
                //$($elem_line).find('.invoice_item_price_converted').hide();
                $($elem_line).find('.on_rate_convert').hide();

                //$($elem_line).find('.item_rate').show();
                crm_calculate_total();
            }

        } else {
            var is_triggered = true;
            invoiceDisableSave(true); // disable save
            data = {
                base_currency: $doc_currency,
                target_currency: $line_currency,
                invoice_date: $('#date').val()
            }

            //get rate
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: data,
                success: function (response) {
                    //#itemselect
                    $($elem_line).find('.rateRowInput').addClass('block').removeClass('hidden');
                    $($elem_line).find('.priceRowInput').addClass('block').removeClass('hidden');


                    var converted_reverse = calculateConvertCases($unitary_price, response);
                    $($elem_line).find('.invoice_item_price_converted').val(converted_reverse);

                    //////console.log('Changed new line currency',response);

                    $($elem_line).find('.invoice_item_currency_rate').val(response.rate);

                    if ((response.rate) == 1) {
                        $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
                        $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');
                    }
                    //converted = roundToX($unitary_price / response.rate );
                    //converted_reverse = roundToX($unitary_price * response.rate);
                    //////console.log('Test');

                    /**OLD
                     if ($line_currency == 3 && $doc_currency != 3) {
                     $new_conv_from = roundToX($unitary_price / response.rate);
                     } else if ($doc_currency == 3 && $line_currency != 3) {
                     $new_conv_from = roundToX($unitary_price / response.rate);
                     } else {
                     $new_conv_from = roundToX($unitary_price * response.rate);
                     }
                     */


                    //////console.log('element price converted',$($elem_line).find('.invoice_item_price_converted'),'has value',$unitary_price);
                    //$($elem_line).find('.invoice_item_price_converted').val($unitary_price);
                    //$($elem_line).find('.item_rate').val(converted_reverse);

                    //$($elem_line).find('.item_rate').prop('readonly', true);
                    crm_calculate_total();
                    is_triggered = false;


                    invoiceDisableSave(false); // enable save
                }
            });


            //$($elem_line).find('.invoice_item_currency_rate').show();
            //$($elem_line).find('.invoice_item_currency_rate').hide();
            //$($elem_line).find('.invoice_item_price_converted').show();
            //$($elem_line).find('.item_rate').hide();
            //$($elem_line).find('.on_rate_convert').show();
            //  ////console.log('Convert from '+$doc_currency+' to '+$line_currency);
        }

        e.stopImmediatePropagation();
    });

    $('body').on('change', '.item_rate', function (e, clickedIndex, newValue, oldValue) {
        if (is_triggered !== undefined) {
            if (is_triggered) {
                return false;
            }
        }

        var $doc_currency = $('#currency').val();
        var $line_currency = $(this).val();
        //var item_line = $(this).closest('div.item').attr('item');
        var item_line = $(this).closest('div.item');

        $elem_line = $(this).closest('div.item');


        var $unitary_price = $($elem_line).find('.item_rate').val();
        var cur_rate = $($elem_line).find('.invoice_item_currency_rate').val();

        converted = roundToX($unitary_price * cur_rate);

        if ($doc_currency == $line_currency) {

        } else {
            var is_triggered = true;
            // $($elem_line).find('.invoice_item_currency_rate').val(response.rate);
            //converted = roundToX($unitary_price / response.rate );
            //converted_reverse = roundToX($unitary_price * response.rate );
            $($elem_line).find('.invoice_item_price_converted').val(converted);
            // $($elem_line).find('.item_rate').val(converted_reverse);
            is_triggered = false;


        }
        ////console.log('2nd');
        crm_calculate_total();
        e.stopImmediatePropagation();
    });
    $('body').on('change', '.invoice_item_currency_rate,.invoice_item_price_converted', function (e, clickedIndex, newValue, oldValue) {
        if (is_triggered !== undefined) {
            if (is_triggered) {
                return false;
            }
        }

        var $doc_currency = $('#currency').val();
        var $line_currency = $(this).val();
        var item_line = $(this).closest('div.item').attr('item');


        $elem_line = $(this).closest('div.item');


        var $unitary_price = $($elem_line).find('.item_rate').val();
        var cur_rate = $($elem_line).find('.invoice_item_currency_rate').val();
        //converted = roundToX($unitary_price * cur_rate );
        //converted_reverse = roundToX($unitary_price * cur_rate );

        if ($doc_currency == $line_currency) {

        } else {
            var is_triggered = true;
            //$($elem_line).find('.invoice_item_price_converted').val(converted_reverse);
            converted_from = $($elem_line).find('.invoice_item_price_converted').val();
            unit_price = roundToX(converted_from * cur_rate);
            $($elem_line).find('.item_rate').val(unit_price);
            is_triggered = false;


        }
        ////console.log('3rd');
        crm_calculate_total();
        e.stopImmediatePropagation();
    });


    //doc
    //show.bs.select
    $('body').on('changed.bs.select', '#currency', function (e, clickedIndex, hasNewValue, oldValue) {

        if (!hasNewValue) {
            return;
        }


        select = $(this);

        ////console.log('4rth');
        process_doc_currency();
        // Make calculation for add item form if we have something selected
        item_addForm_cal();

        crm_calculate_total();
        e.stopImmediatePropagation();
    });
});

function item_addForm_cal() {
    var form = $('.itemAddForm');

    var $doc_currency = $('#currency').val();
    var $line_currency = $('#invoice_item_currency').val();
    var $unitary_price = form.find('[name="rate"]').val();

    // Get element ref
    $elem_line = form.closest('div.item');

    if (typeof $unitary_price !== 'undefined' && $unitary_price.trim() !== '' && !isNaN($unitary_price)) {

        if ($unitary_price == 0 || $unitary_price === undefined) {
            //return false;
        }

        post_data = {
            base_currency: $doc_currency,
            target_currency: $line_currency,
            unitary_price: $unitary_price,
            invoice_date: $('#date').val()
        };

        ////console.log('aikci');
        ////console.log(post_data);

        if ($doc_currency == $line_currency) {
            ////console.log('egal');
            ////console.log($elem_line);

            form.find('.invoice_item_currency_rate').val(1);
            form.find('.invoice_item_price_converted').val(post_data.unitary_price);
            reset_add_line_price(post_data);

        } else {
            ////console.log('nu egal');
            //get rate
            //update_add_line_price(post_data,'base2target');

            invoiceDisableSave(true); // disable save
            $.ajax({
                url: admin_url + "core/bnr/get_daily_bnr",
                dataType: "json",
                type: "post",
                data: post_data,
                success: function (response) {
                    ////console.log(response);
                    var converted_reverse = calculateConvertCases(post_data.unitary_price, response);
                    form.find('.invoice_item_price_converted').val(converted_reverse);
                    form.find('.invoice_item_currency_rate').val(response.rate);

                    register_doc_currency(post_data.base_currency, post_data.target_currency, response.rate);
                    invoiceDisableSave(false); // enable save

                    if ((response.rate) == 1) {
                        $($elem_line).find('.rateRowInput').addClass('hidden').removeClass('block');
                        $($elem_line).find('.priceRowInput').addClass('hidden').removeClass('block');
                    } else {
                        $($elem_line).find('.rateRowInput').addClass('block').removeClass('hidden');
                        $($elem_line).find('.priceRowInput').addClass('block').removeClass('hidden');
                    }
                }
            });


            //$('#invoice_item_currency_rate').show();
            //$('#invoice_item_price_converted').show();
            //$('#rate').hide();
            //$('.on_rate_convert').show();
        }
    }
}


function findObjectByKey(array, key, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i][key] === value) {
            return array[i];
        }
    }
    return null;
}

// Append the added items to the preview to the table as items
function crm_add_invoice_item(data, itemid, merge_invoice, bill_expense) {

    // If not custom data passed get from the preview
    data = typeof (data) == 'undefined' || data == 'undefined' ? crm_get_item_preview_values() : data;
    if (data.description === "" && data.long_description === "" && data.rate === "") {
        return;
    }
    //////console.log('crm_add_invoice_item',data);
    if (data.currency == null || data.currency == '') {
        alert_float('warning', app.lang.invoice_item_currency_not_set);
        return;
    }
    if (data.unit == null || data.unit == '') {
        alert_float('warning', app.lang.invoice_item_um_not_set);
        return;
    }
    var table_row = '';
    var item_key = $("body").find('.table.items .list_items .item').length + 1;
    var $doc_currency = $('#currency').val();


    table_row += '<div class="sortable item item-row" data-merge-invoice="' + merge_invoice + '" data-bill-expense="' + bill_expense + '">';

    //<editor-fold dragger>
    table_row += '<div class="dragger-container">';
    table_row += '<div class="dragger dragger-spacer">';

    // Check if quantity is number
    if (isNaN(data.qty)) {
        data.qty = 1;
    }

    // Check if rate is number
    if (data.rate === '' || isNaN(data.rate)) {
        data.rate = 0;
    }

    var amount = data.rate * data.qty;


    cur_name = findObjectByKey(currencies, 'id', data.currency).name;
    cur_dropdown =
        `
        <input type="text" name="newitems[` + item_key + `][currency]" value="` + cur_name + `" classs="form-control" readonly>
        `;


    var tax_name = 'newitems[' + item_key + '][taxname][]';
    $("body").append('<div class="dt-loader"></div>');
    var regex = /<br[^>]*>/gi;
    get_taxes_dropdown_template(tax_name, data.taxname).done(function (tax_dropdown) {
        get_cur_dropdown_template(data.currency, "newitems[" + item_key + "][currency]").done(function (cur_dropdown) {
            // order input
            table_row += '<input type="hidden" class="order" name="newitems[' + item_key + '][order]">';

            table_row += '</div>'; //dragger
            table_row += '</div>'; //dragger contianer
            //</editor-fold>
            table_row += '<div class="item-row-container">';

            table_row += '<div class="col-item column__description">';
            table_row += '<input type="text" name="newitems[' + item_key + '][description]" required class="form-control" value="' + data.description + '">';
            table_row += '</div>';

            table_row += '<div class="col-item column__long_description column__cf">';
            var cl = '';
            var ld_val = '';
            if (invoice_settings.use_description == 1) {
                ld_val = data.long_description.replace(regex, "\n");
            } else {
                cl = 'd-none';
            }
            table_row += '<textarea name="newitems[' + item_key + '][long_description]" rows="1" class="form-control ' + cl + '">' + ld_val + '</textarea>';

            var custom_fields = $('.custom_field');
            var cf_has_required = false;

            if (custom_fields.length > 0) {

                $.each(custom_fields, function () {

                    var cf = $(this).clone();
                    var cf_html = '';
                    var cf_field = $(this).find('[data-fieldid]');
                    var cf_name = 'newitems[' + item_key + '][custom_fields][items][' + cf_field.attr('data-fieldid') + ']';

                    if (cf_field.is(':checkbox')) {

                        var checked = $(this).find('input[type="checkbox"]:checked');
                        var checkboxes = cf.find('input[type="checkbox"]');

                        $.each(checkboxes, function (i, e) {
                            var random_key = Math.random().toString(20).slice(2);
                            $(this).attr('id', random_key)
                                .attr('name', cf_name)
                                .next('label').attr('for', random_key);
                            if ($(this).attr('data-custom-field-required') == '1') {
                                cf_has_required = true;
                            }
                        });

                        $.each(checked, function (i, e) {
                            cf.find('input[value="' + $(e).val() + '"]')
                                .attr('checked', true);
                        });

                        cf_html = cf.html();

                    } else if (cf_field.is('input') || cf_field.is('textarea')) {
                        if (cf_field.is('input')) {
                            cf.find('[data-fieldid]').attr('value', cf_field.val());
                        } else {
                            cf.find('[data-fieldid]').html(cf_field.val());
                        }
                        cf.find('[data-fieldid]').attr('name', cf_name);
                        if (cf.find('[data-fieldid]').attr('data-custom-field-required') == '1') {
                            cf_has_required = true;
                        }
                        cf_html = cf.html();
                    } else if (cf_field.is('select')) {

                        if ($(this).attr('data-custom-field-required') == '1') {
                            cf_has_required = true;
                        }

                        var selected = $(this).find('select[data-fieldid]').selectpicker('val');
                        selected = typeof (selected != 'array') ? new Array(selected) : selected;

                        // Check if is multidimensional by multi-select customfield
                        selected = selected[0].constructor === Array ? selected[0] : selected;

                        var selectNow = cf.find('select');
                        var $wrapper = $('<div/>');
                        selectNow.attr('name', cf_name);

                        var $select = selectNow.clone();
                        $wrapper.append($select);
                        $.each(selected, function (i, e) {
                            $wrapper.find('select option[value="' + e + '"]').attr('selected', true);
                        });

                        cf_html = $wrapper.html();
                    }
                    table_row += '<div class="custom_field">' + cf_html + '</div>';
                });
            }
            table_row += '</div>';

            table_row += `<div class="col-item column__sku">`;
            table_row += '<input type="text" name="newitems[' + item_key + '][sku]" class="form-control input-transparent" value="' + data.sku + '">';
            table_row += ` </div>`;

            table_row += `<div class="col-item column__unit">`;
            if (!data.unit || typeof (data.unit) == 'undefined') {
                data.unit = '';
            }
            table_row += '<input type="text" placeholder="' + app.lang.unit + '" name="newitems[' + item_key + '][unit]" required class="form-control input-transparent text-right" value="' + data.unit + '">';
            table_row += ` </div>`;

            table_row += `<div class="col-item column__quantity">`;
            table_row += '<input type="number" onblur="crm_calculate_total();" onchange="crm_calculate_total();" required data-quantity name="newitems[' + item_key + '][qty]" value="' + data.qty + '" class="form-control">';
            table_row += `</div>`;

            if (settings.vat_payer == 1 || settings.vat_payer == '1') {
                table_row += '<div class="col-item column__taxes">';

                table_row += '<div class="taxrate">' + tax_dropdown + '</div>';

                table_row += '</div>';
            }

            table_row += `<div class="col-item column__currency"><div>`;
            table_row += '<div class="currency_data">' + cur_dropdown + '</div>';
            if (parseInt(data.currency) != parseInt($doc_currency)) {
                table_row += '<input type="number" name="newitems[' + item_key + '][currency_rate]" class="form-control invoice_item_currency_rate" value="' + data.currency_rate + '">';
            } else {
                table_row += '<input type="number" name="newitems[' + item_key + '][currency_rate]" class="form-control invoice_item_currency_rate" value="' + data.currency_rate + '" style="display:none;">';

            }
            table_row += `</div></div>`;

            table_row += `<div class="col-item column__price"><div>`;
            if (parseInt(data.currency) != parseInt($doc_currency)) {
                table_row += '<input type="number" name="newitems[' + item_key + '][price_converted]" class="form-control invoice_item_price_converted" value="' + data.price_converted + '">';
            } else {
                table_row += '<input type="number" name="newitems[' + item_key + '][price_converted]" class="form-control invoice_item_price_converted" value="' + data.price_converted + '" style="display:none;">';
            }

            if (parseInt(data.currency) != parseInt($doc_currency)) {
                //rate
                table_row += '<div class="rate"><input readonly type="number" data-toggle="tooltip" title="' + app.lang.item_field_not_formatted + '" onblur="crm_calculate_total();" onchange="crm_calculate_total();" name="newitems[' + item_key + '][rate]" value="' + data.rate + '" class="form-control item_rate"></div>';
            } else {
                table_row += '<div class="rate"><input type="number" data-toggle="tooltip" title="' + app.lang.item_field_not_formatted + '" onblur="crm_calculate_total();" onchange="crm_calculate_total();" name="newitems[' + item_key + '][rate]" value="' + data.rate + '" class="form-control item_rate"></div>';
            }
            table_row += `</div></div>`;

            //  table_row += '<span class="amount" align="right">Line total: ' + format_money(amount, true) + '</span>';
            table_row += `<div class="col-item column__actions">`;
            table_row += '<div><button href="#" class="btn btn-danger invoice-del pull-left invoiceSave" onclick="crm_delete_item(this,' + itemid + '); return false;"><i class="fal fa-times"></i></button></div>';
            table_row += `</div>`;


            table_row += '</div>'; //item-row-container


            table_row += '</div>';

            $('.table.items .list_items').append(table_row);


            $(document).trigger({
                type: "item-added-to-table",
                data: data,
                row: table_row
            });

            setTimeout(function () {
                crm_calculate_total();
            }, 15);

            var billed_task = $('input[name="task_id"]').val();
            var billed_expense = $('input[name="expense_id"]').val();

            if (billed_task !== '' && typeof (billed_task) != 'undefined') {
                billed_tasks = billed_task.split(',');
                $.each(billed_tasks, function (i, obj) {
                    $('#billed-tasks').append(hidden_input('billed_tasks[' + item_key + '][]', obj));
                });
            }

            if (billed_expense !== '' && typeof (billed_expense) != 'undefined') {
                billed_expenses = billed_expense.split(',');
                $.each(billed_expenses, function (i, obj) {
                    $('#billed-expenses').append(hidden_input('billed_expenses[' + item_key + '][]', obj));
                });
            }

            if ($('#item_select').hasClass('ajax-search') && $('#item_select').selectpicker('val') !== '') {
                $('#item_select').prepend('<option></option>');
            }

            init_selectpicker();
            init_datepicker();
            init_color_pickers();
            crm_clear_item_preview_values();
            reorder_items();

            $('body').find('#items-warning').remove();
            $("body").find('.dt-loader').remove();
            $('#item_select').selectpicker('val', '');


            $('#invoice_item_currency_rate').hide();
            $('#invoice_item_price_converted').hide();
            $('.on_rate_convert').hide();

            $('#invoice_item_currency_rate').val('');
            $('#invoice_item_sku').val('');

            $('#invoice_item_price_converted').val('');
            $('#invoice_item_currency').selectpicker('val', $doc_currency);

            if (cf_has_required && $('.invoice-form').length) {
                ////console.log('validate inv');
                crm_validate_invoice_form();
            } else if (cf_has_required && $('.estimate-form').length) {
                ////console.log('validate est');
                validate_estimate_form();
            } else if (cf_has_required && $('.proposal-form').length) {
                ////console.log('validate prop');
                validate_proposal_form();
            } else if (cf_has_required && $('.credit-note-form').length) {
                ////console.log('validate crn');
                validate_credit_note_form();
            }

            return true;
        });
    });


    $('#rate').show();

    return false;
}

// Append the added items to the preview to the table as items
function crm_add_invoice_item_2(data, itemid, merge_invoice, bill_expense) {

    // We need to trigger rate change to avoid unwanted values after price change
    $('#rate').trigger('change');

    // If not custom data passed get from the preview
    data = typeof (data) == 'undefined' || data == 'undefined' ? crm_get_item_preview_values() : data;
    if (data.description === "" && data.long_description === "" && data.rate === "") {
        return;
    }
    //////console.log('crm_add_invoice_item',data);
    if (data.currency == null || data.currency == '') {
        alert_float('warning', app.lang.invoice_item_currency_not_set);
        return;
    }
    if (data.unit == null || data.unit == '') {
        alert_float('warning', app.lang.invoice_item_um_not_set);
        return;
    }
    var table_row = '';
    var item_key = $("body").find('.table.items .list_items .item').length + 1;
    var $doc_currency = $('#currency').val();


    table_row += '<div class="sortable item flex flex-row mb-5 border-solid border-b-2 border-gray-200" data-merge-invoice="' + merge_invoice + '" data-bill-expense="' + bill_expense + '">';

    //<editor-fold dragger>
    table_row += '<div class="dragger-container">';
    table_row += '<div class="dragger dragger-spacer">';

    // Check if quantity is number
    if (isNaN(data.qty)) {
        data.qty = 1;
    }

    // Check if rate is number
    if (data.rate === '' || isNaN(data.rate)) {
        data.rate = 0;
    }

    var amount = data.rate * data.qty;


    cur_name = findObjectByKey(currencies, 'id', data.currency).name;
    cur_dropdown =
        `
        <input type="text" name="newitems[` + item_key + `][currency]" value="` + cur_name + `" classs="form-control" readonly>
        `;


    var tax_name = 'newitems[' + item_key + '][taxname][]';
    $("body").append('<div class="dt-loader"></div>');
    var regex = /<br[^>]*>/gi;
    get_taxes_dropdown_template(tax_name, data.taxname).done(function (tax_dropdown) {
        get_cur_dropdown_template(data.currency, "newitems[" + item_key + "][currency]").done(function (cur_dropdown) {
            // order input
            table_row += '<input type="hidden" class="order" name="newitems[' + item_key + '][order]">';

            table_row += '</div>'; //dragger
            table_row += '</div>'; //dragger contianer
            //</editor-fold>
            table_row += '<div class="flex flex-row w-full">';

            table_row += '<div class="col-item column__description">';
            table_row += '<input type="text" name="newitems[' + item_key + '][description]" required class="form-control" value="' + data.description + '">';
            table_row += '</div>';


            var cl = '';
            var ld_val = '';

            if (invoice_settings.use_description == 1) {
                ld_val = data.long_description.replace(regex, "\n");
                table_row += '<div class="col-item column__long_description column__cf">';
                table_row += '<textarea name="newitems[' + item_key + '][long_description]" rows="1" class="form-control ' + cl + '">' + ld_val + '</textarea>';
            } else {
                cl = 'd-none';
            }


            var custom_fields = $('.custom_field');
            var cf_has_required = false;

            if (custom_fields.length > 0) {

                $.each(custom_fields, function () {

                    var cf = $(this).clone();
                    var cf_html = '';
                    var cf_field = $(this).find('[data-fieldid]');
                    var cf_name = 'newitems[' + item_key + '][custom_fields][items][' + cf_field.attr('data-fieldid') + ']';

                    if (cf_field.is(':checkbox')) {

                        var checked = $(this).find('input[type="checkbox"]:checked');
                        var checkboxes = cf.find('input[type="checkbox"]');

                        $.each(checkboxes, function (i, e) {
                            var random_key = Math.random().toString(20).slice(2);
                            $(this).attr('id', random_key)
                                .attr('name', cf_name)
                                .next('label').attr('for', random_key);
                            if ($(this).attr('data-custom-field-required') == '1') {
                                cf_has_required = true;
                            }
                        });

                        $.each(checked, function (i, e) {
                            cf.find('input[value="' + $(e).val() + '"]')
                                .attr('checked', true);
                        });

                        cf_html = cf.html();

                    } else if (cf_field.is('input') || cf_field.is('textarea')) {
                        if (cf_field.is('input')) {
                            cf.find('[data-fieldid]').attr('value', cf_field.val());
                        } else {
                            cf.find('[data-fieldid]').html(cf_field.val());
                        }
                        cf.find('[data-fieldid]').attr('name', cf_name);
                        if (cf.find('[data-fieldid]').attr('data-custom-field-required') == '1') {
                            cf_has_required = true;
                        }
                        cf_html = cf.html();
                    } else if (cf_field.is('select')) {

                        if ($(this).attr('data-custom-field-required') == '1') {
                            cf_has_required = true;
                        }

                        var selected = $(this).find('select[data-fieldid]').selectpicker('val');
                        selected = typeof (selected != 'array') ? new Array(selected) : selected;

                        // Check if is multidimensional by multi-select customfield
                        selected = selected[0].constructor === Array ? selected[0] : selected;

                        var selectNow = cf.find('select');
                        var $wrapper = $('<div/>');
                        selectNow.attr('name', cf_name);

                        var $select = selectNow.clone();
                        $wrapper.append($select);
                        $.each(selected, function (i, e) {
                            $wrapper.find('select option[value="' + e + '"]').attr('selected', true);
                        });

                        cf_html = $wrapper.html();
                    }
                    table_row += '<div class="custom_field">' + cf_html + '</div>';
                });
            }
            table_row += '</div>';

            if (invoice_settings.use_product_code == 1) {
                table_row += `<div class="col-item column__sku">`;
                table_row += '<input type="text" name="newitems[' + item_key + '][sku]" class="form-control input-transparent" value="' + data.sku + '">';
                table_row += ` </div>`;
            }

            table_row += `<div class="col-item column__unit">`;
            if (!data.unit || typeof (data.unit) == 'undefined') {
                data.unit = '';
            }
            table_row += '<input type="text" placeholder="' + app.lang.unit + '" name="newitems[' + item_key + '][unit]" required class="form-control input-transparent text-right" value="' + data.unit + '">';
            table_row += ` </div>`;

            table_row += `<div class="col-item column__quantity">`;
            table_row += '<input type="number" onblur="crm_calculate_total();" onchange="crm_calculate_total();" required data-quantity name="newitems[' + item_key + '][qty]" value="' + data.qty + '" class="form-control">';
            table_row += `</div>`;

            if (settings.vat_payer == 1 || settings.vat_payer == '1') {
                table_row += '<div class="col-item column__taxes">';

                table_row += '<div class="taxrate">' + tax_dropdown + '</div>';

                table_row += '</div>';
            }

            // Currency
            table_row += `<div class="col-item column__currency">`;
            table_row += `<div>`;
            table_row += '<div class="currency_data">' + cur_dropdown + '</div>';
            table_row += `</div>`;
            data.currency_rate === '' ? data.currency_rate = 1 : data.currency_rate = data.currency_rate;
            if (data.currency_rate == 1) {
                var rate_class = 'hidden';
            } else {
                var rate_class = 'block';
            }
            // curs
            table_row += '<div class="rateRowInput ' + rate_class + ' ">';
            table_row += `<span class="xnbr text-sm font-semibold">Curs</span>`;
            ////console.log(data);

            table_row += '<input readonly type="number" step="0.0001" name="newitems[' + item_key + '][currency_rate]" class="form-control invoice_item_currency_rate" value="' + data.currency_rate + '">';
            table_row += `</div>`;
            // curs END
            table_row += `</div>`; // Currency END

            table_row += `<div class="col-item column__price">`;
            table_row += `<div>`;
            table_row += '<div class="rate"><input data-toggle="tooltip" title="' + app.lang.item_field_not_formatted + '" onblur="crm_calculate_total();" onchange="crm_calculate_total();" name="newitems[' + item_key + '][rate]" value="' + data.rate + '" class="form-control item_rate"></div>';
            table_row += `</div>`;
            // pret down
            table_row += '<div class="priceRowInput ' + rate_class + '">';
            table_row += `<span class="xnbr text-sm font-semibold">Pret<span class="needSelectedCurrency font-semibold"></span></span>`;
            table_row += '<input readonly type="number" name="newitems[' + item_key + '][price_converted]" class="form-control invoice_item_price_converted" value="' + data.price_converted + '">';
            table_row += `</div>`;
            table_row += `</div>`;

            //  table_row += '<span class="amount" align="right">Line total: ' + format_money(amount, true) + '</span>';
            table_row += `<div class="col-item column__actions">`;
            table_row += '<div><button class="btn btn-danger invoice-del pull-left invoiceSave" onclick="crm_delete_item(this,' + itemid + '); return false;"><i class="fal fa-times"></i></button></div>';
            table_row += `</div>`;


            table_row += '</div>'; //item-row-container


            table_row += '</div>';

            $('.table.items .list_items').append(table_row);


            $(document).trigger({
                type: "item-added-to-table",
                data: data,
                row: table_row
            });

            setTimeout(function () {
                crm_calculate_total();
            }, 15);

            var billed_task = $('input[name="task_id"]').val();
            var billed_expense = $('input[name="expense_id"]').val();

            if (billed_task !== '' && typeof (billed_task) != 'undefined') {
                billed_tasks = billed_task.split(',');
                $.each(billed_tasks, function (i, obj) {
                    $('#billed-tasks').append(hidden_input('billed_tasks[' + item_key + '][]', obj));
                });
            }

            if (billed_expense !== '' && typeof (billed_expense) != 'undefined') {
                billed_expenses = billed_expense.split(',');
                $.each(billed_expenses, function (i, obj) {
                    $('#billed-expenses').append(hidden_input('billed_expenses[' + item_key + '][]', obj));
                });
            }

            if ($('#item_select').hasClass('ajax-search') && $('#item_select').selectpicker('val') !== '') {
                $('#item_select').prepend('<option></option>');
            }

            init_selectpicker();
            init_datepicker();
            init_color_pickers();
            crm_clear_item_preview_values();
            reorder_items();

            $('body').find('#items-warning').remove();
            $("body").find('.dt-loader').remove();
            $('#item_select').selectpicker('val', '');


            $('#invoice_item_currency_rate').hide();
            $('#invoice_item_price_converted').hide();
            $('.on_rate_convert').hide();

            $('#invoice_item_currency_rate').val('');
            $('#invoice_item_sku').val('');

            $('#invoice_item_price_converted').val('');
            $('#invoice_item_currency').selectpicker('val', $doc_currency);

            if (cf_has_required && $('.invoice-form').length) {
                ////console.log('validate inv');
                crm_validate_invoice_form();
            } else if (cf_has_required && $('.estimate-form').length) {
                ////console.log('validate est');
                validate_estimate_form();
            } else if (cf_has_required && $('.proposal-form').length) {
                ////console.log('validate prop');
                validate_proposal_form();
            } else if (cf_has_required && $('.credit-note-form').length) {
                ////console.log('validate crn');
                validate_credit_note_form();
            }

            return true;
        });
    });


    $('#rate').show();

    return false;
}


var fdates = {
    convert: function (d) {
        // Converts the date in d to a date-object. The input can be:
        //   a date object: returned without modification
        //  an array      : Interpreted as [year,month,day]. NOTE: month is 0-11.
        //   a number     : Interpreted as number of milliseconds
        //                  since 1 Jan 1970 (a timestamp)
        //   a string     : Any format supported by the javascript engine, like
        //                  "YYYY/MM/DD", "MM/DD/YYYY", "Jan 31 2009" etc.
        //  an object     : Interpreted as an object with year, month and date
        //                  attributes.  **NOTE** month is 0-11.
        return (
            d.constructor === Date ? d :
                d.constructor === Array ? new Date(d[0], d[1], d[2]) :
                    d.constructor === Number ? new Date(d) :
                        d.constructor === String ? new Date(d) :
                            typeof d === "object" ? new Date(d.year, d.month, d.date) :
                                NaN
        );
    },
    compare: function (a, b) {
        // Compare two dates (could be of any type supported by the convert
        // function above) and returns:
        //  -1 : if a < b
        //   0 : if a = b
        //   1 : if a > b
        // NaN : if a or b is an illegal date
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(a = this.convert(a).valueOf()) &&
            isFinite(b = this.convert(b).valueOf()) ?
                (a > b) - (a < b) :
                NaN
        );
    },
    inRange: function (d, start, end) {
        // Checks if date in d is between dates in start and end.
        // Returns a boolean or NaN:
        //    true  : if d is between start and end (inclusive)
        //    false : if d is before start or after end
        //    NaN   : if one or more of the dates is illegal.
        // NOTE: The code inside isFinite does an assignment (=).
        return (
            isFinite(d = this.convert(d).valueOf()) &&
            isFinite(start = this.convert(start).valueOf()) &&
            isFinite(end = this.convert(end).valueOf()) ?
                start <= d && d <= end :
                NaN
        );
    }
};

/*
$.validator.addMethod(
       "valid_due",
       function(value, element) {
         var $due_date = $('#duedate').val();
         if($due_date == ''){return false;}
         var $date = $('#date').val();
         var res = fdates.compare($due_date,$date);
         if(res === -1){
           return false;
         }else{
           return true;
         }

       },
       "Due date not allowed."
   );
*/

function crm_validate_invoice_form(selector) {
    selector = typeof (selector) == 'undefined' ? '#invoice-form' : selector;

    appValidateForm($(selector), {
        clientid: {
            required: {
                depends: function () {
                    var customerRemoved = $('select#clientid').hasClass('customer-removed');
                    return !customerRemoved;
                }
            }
        },
        //date: 'required',
        date: {
            required: true,
        },
        duedate: {
            required: true,
        },
        currency: 'required',
        repeat_every_custom: {
            min: 1
        },
        number: {
            required: true,
        }
    });
    $("body").find('input[name="number"]').rules('add', {
        remote: {
            url: admin_url + "invoices/validate_invoice_number_seria",
            type: 'post',
            data: {
                number: function () {
                    return $('input[name="number"]').val();
                },
                seria: function () {
                    return $('[name="s_prefix"]').val();
                },
                isedit: function () {
                    return $('input[name="number"]').data('isedit');
                },
                original_number: function () {
                    return $('input[name="number"]').data('original-number');
                },
                date: function () {
                    return $('input[name="date"]').val();
                },
            }
        },
        messages: {
            remote: app.lang.invoice_number_exists,
        }
    });

    $("body").find('#duedate').rules('add', {
        valid_due: function (value, element) {
            var $due_date = $('#duedate').val();
            if ($due_date == '') {
                return false;
            }
            var $date = $('#date').val();
            var res = fdates.compare($due_date, $date);
            if (res === -1) {
                return false;
            } else {
                return true;
            }

        },
        messages: {
            valid_due: 'Invalud due date',
        }
    });


}

function crm_get_item_preview_values() {
    var response = {};
    response.description = $('.main [name="description"]').val();
    response.long_description = $('.main [name="long_description"]').val();
    response.qty = $('.main input[name="quantity"]').val();
    //response.taxname = $('.main select.tax').selectpicker('val');
    response.taxname = $('.main select.tax').val();
    response.rate = $('.main input[name="rate"]').val();
    response.unit = $('.main input[name="unit"]').val();
    response.sku = $('.main input[name="sku"]').val();


    response.currency_rate = $('.main input[name="invoice_item_currency_rate"]').val();
    response.price_converted = $('.main input[name="invoice_item_price_converted"]').val();
    response.currency = $('.main [name="invoice_item_currency"]').val();


    return response;
}


// Clear the items added to preview
function crm_clear_item_preview_values(default_taxes) {

    // Get the last taxes applied to be available for the next item
    var last_taxes_applied = $('.table.items .list_items').find('div').find('select').selectpicker('val');
    var previewArea = $('.main');

    previewArea.find('textarea').val(''); // includes cf
    previewArea.find('input[name="description"]').val('');
    previewArea.find('td.custom_field input[type="checkbox"]').prop('checked', false); // cf
    previewArea.find('td.custom_field input:not(:checkbox):not(:hidden)').val(''); // cf // not hidden for chkbox hidden helpers
    previewArea.find('td.custom_field select').selectpicker('val', ''); // cf
    previewArea.find('input[name="quantity"]').val(1);
    previewArea.find('select.tax').selectpicker('val', last_taxes_applied);
    previewArea.find('input[name="rate"]').val('');
    previewArea.find('input[name="unit"]').val('');

    $('input[name="task_id"]').val('');
    $('input[name="expense_id"]').val('');
}


/*init_invoices_total();
init_expenses_total();
init_estimates_total();*/
init_crm_items_sortable();

// Make items sortable with jquery sort plugin
function init_crm_items_sortable(preview_table) {
    var _items_sortable = $("#wrapper").find('.items.invoice-items-table');

    if (_items_sortable.length === 0) {
        return;
    }
    _items_sortable.sortable({
        helper: fixHelperTableHelperSortable,
        handle: '.dragger',
        placeholder: 'ui-placeholder',
        itemPath: '> .list_items',
        itemSelector: 'div.sortable',
        items: "div.sortable",
        update: function () {
            if (typeof (preview_table) == 'undefined') {
                reorder_items();
            } else {
                // If passed from the admin preview there is other function for re-ordering
                save_ei_items_order();
            }
        },
        sort: function (event, ui) {
            // Firefox fixer when dragging
            var $target = $(event.target);
            if (!/html|body/i.test($target.offsetParent()[0].tagName)) {
                var top = event.pageY - $target.offsetParent().offset().top - (ui.helper.outerHeight(true) / 2);
                ui.helper.css({
                    'top': top + 'px'
                });
            }
        }
    });
}


function crm_delete_item(row, itemid) {
    $(row).parents('div.item').addClass('animated fadeOut', function () {
        setTimeout(function () {
            $(row).parents('div.item').remove();
            crm_calculate_total();
        }, 50);
    });
    // If is edit we need to add to input removed_items to track activity
    if ($('input[name="isedit"]').length > 0) {
        $('#removed-items').append(hidden_input('removed_items[]', itemid));
    }
}


function get_cur_dropdown_template(id, name) {

    jQuery.ajaxSetup({
        async: false
    });
    var d = $.post(admin_url + 'misc/get_currency_dropdown_template/', {
        id: id,
        name: name
    });
    jQuery.ajaxSetup({
        async: true
    });

    return d;
}

if (typeof (accounting) != 'undefined') {

    // For currency
    accounting.settings.currency.precision = app.options.decimal_places;

    // Used for numbers
    accounting.settings.number.thousand = app.options.thousand_separator;
    accounting.settings.number.decimal = app.options.decimal_separator;
    accounting.settings.number.precision = app.options.decimal_places;

    ////console.log('1st111');
    crm_calculate_total();
}


$('body').on('change', '#select_seria', function (e, clickedIndex, newValue, oldValue) {
    var $seria = $(this).val();
    var date = $('[name=date]').val();

    $.ajax({
        url: admin_url + "invoices/get_seria",
        dataType: "json",
        type: "post",
        data: {
            seria: $seria,
            date: date
        },
        success: function (response) {

            $('[name=number]').val(response.next_number);
            if (response.last_date !== undefined) {
                if (response.last_date) {
                    $('[name=date]').val(response.last_date);
                    alert_float('warning', app.lang.invoice_min_date + ' ' + response.last_date);

                    $('#date').prop('data-date-start-date', '20-04-2023');
                    $('[name=date]').attr('data-date-start-date', '20-04-2023');


                }
            }

        }
    });

});


$("body").on('submit', '._transaction_form', function () {

    // On submit re-calculate total and reorder the items for all cases.
    crm_calculate_total();
});

function calculateConvertCases(price, rate) {

    var result;

    switch (rate.base_currency) {
        case "RON":
            if (rate.target_currency === "USD" || rate.target_currency === "EUR") {
                result = roundToX(price * rate.rate);
            }
            break;

        case "USD":
            if (rate.target_currency === "EUR") {
                result = roundToX(price / rate.rate);
            }

            if (rate.target_currency === "RON") {
                result = roundToX(price * rate.rate);
            }

        case "EUR":
            if (rate.target_currency === "RON") {
                result = roundToX(price * rate.rate);
            }

            if (rate.target_currency === "USD") {
                result = roundToX(price / rate.rate);
            }
            break;

        default:
            break;
    }

    return accounting.toFixed(result, app.options.decimal_places);
}

function crm_set_invoice_number(e) {
    var data = {};
    data.prefix = $("body").find('input[name="s_prefix"]').val();
    $.post($(e).data('url'), data).done(function (response) {
        response = JSON.parse(response);
        if (response.success && response.message) {
            alert_float('success', response.message);
            $('#prefix').html(data.prefix);
        }
    });
}


$("body").on('change', 'input[name="invoices_to_merge[]"]', function () {
    var checked = $(this).prop('checked');
    var _id = $(this).val();
    if (checked === true) {
        requestGetJSON('invoices/get_merge_data/' + _id).done(function (response) {
            $.each(response.items, function (i, obj) {
                if (obj.rel_type !== '') {
                    if (obj.rel_type == 'task') {
                        $('input[name="task_id"]').val(obj.item_related_formatted_for_input);
                    } else if (obj.rel_type == 'expense') {
                        $('input[name="expense_id"]').val(obj.item_related_formatted_for_input);
                    }
                }
                _set_item_preview_custom_fields_array(obj.custom_fields);
                crm_add_invoice_item(obj, 'undefined', _id); //old add_item_to_table
            });
        });
    } else {
        // Remove the appended invoice to merge
        $("body").find('[data-merge-invoice="' + _id + '"]').remove();
    }
});


$('body').on('change', '#date', function (e) {
    var newValue = $(this).val();
    ////console.log('4rth');
    process_doc_currency();
    // Make calculation for add item form if we have something selected
    item_addForm_cal();

    crm_calculate_total();
    e.stopImmediatePropagation();
});