var subjectRabate = 0;
var selectedInvoiceItemData = { data: null };
var focusElement;
var pricesForSelect = [];
var actionRebateOnly = false;

const PriceType = {
    Pos: 'M',
    Wholesale: 'P',
    ReceivedBills: 'D',
    OrderSuppliers: 'OS',
    OrderBuyer: 'OB',
    SalePrice: '1',
    WSPrice1: '2',
    WSPrice2: '3',
    AdvancePaymentReceived: 'AR',
    AdvancePaymentIssued: 'AI',
    PartList: 'PL',
    PriceChange: 'PC',
    Inventory: 'I'
};

const DiscountType = {
    SellerDiscount: 'D',
    SupplierRebate: 'R'
};

const ItemSrchSubjCodeType = {
    DontSearchByCode: 'N',
    SearchForSpecificSubject: 'P',
    SearchForAllSubjects: 'K',
    SearchByIdentThenByCode: 'I'
};

var identSearchPopup = null;

async function initializeInvoiceIdentInputs($element, priceType, discountType, defaultDecimalPlacesPrice, $warehouse, $subject, $wayOfSale, localization, $isAdvPayFisc, $specPayment, typeaheadOptions, identSearchPopupOptions) {
    let searchIdentUrl = $element.attr('dataUrl');
    let saleType = (priceType === PriceType.Wholesale || priceType === PriceType.OrderBuyer || priceType === PriceType.Pos || priceType === PriceType.AdvancePaymentReceived) ? "P" : "N";

    $element.customTypeahead({
        value: "Ident",
        display: "Name",
        minWidth: "330px",
        minSearchLength: 0,
        focusOpen: true,
        paginate: false,
        typeaheadClass: "custom-typeahead-dropdown-invoice",
        columns: [
            { name: localization.ident, value: "Ident", width: "25%" },
            { name: localization.name, value: "Name", cellClass: "custom-typeahead-multiline custom-typeahead-hidden-sm", headerClass: "custom-typeahead-hidden-sm" },
            { name: localization.price, value: (item) => formatDisplay(defaultDecimalPlacesPrice, getPriceByPriceType(item, priceType)), width: "90px", headerClass: "text-right", cellClass: "text-right custom-typeahead-multiline" },
            { name: localization.stock, value: (item) => item.WarehouseStockInQty === true ? (item.Stock > 0 ? $("#yesLoc").val() : $("#noLoc").val()) : formatDisplay(defaultDecimalPlacesPrice, item.Stock), width: "90px", headerClass: "text-right", cellClass: "text-right  custom-typeahead-multiline" }
        ],
        rowBelow: function (rowData) {
            return "<td colspan='3' class='custom-typeahead-multiline custom-typeahead-description custom-typeahead-visible-sm'>" + rowData.Name + "</td>";
        },
        localization: { noResults: localization.noResults },
        url: searchIdentUrl,
        urlPropsFunction: function () {
            return {
                saleType: saleType,
                priceType: priceType,
                warehouse: ($warehouse ? $warehouse.val() : undefined),
                subject: ($subject ? $subject.val() : undefined),
                wayOfSale: $wayOfSale ? $wayOfSale.val() : undefined,
                isAdvPayFisc: $isAdvPayFisc ? $isAdvPayFisc.val() === "true" : false,
                specPayment: $specPayment ? $specPayment.val() : undefined,
                limitToSubjectId: priceType === PriceType.OrderBuyer ? ($subject ? $subject.val() : undefined) : undefined,
                getByCode: $("#SetsItemSrchSubjCode").val()
            };
        },
        urlRequestMethod: "POST",
        onSelect: function (item) {
            return setInvoiceItemData(item, priceType, discountType);
        },
        options: paw.utils.value.isSet(typeaheadOptions) ? typeaheadOptions : [
            {
                icon: 'fa fa-search',
                label: localization.advancedSearch,
                onSelected: function () {
                    identSearchPopup.show();
                }
            }
        ]
    });

    $("#IdentSearch+input:not(.custom-typeahead-open), #SelectedItemQuantity, #SelectedItemPrice, #SelectedItemRebate").on('keydown', function (e) {
        if (e.keyCode === 13 || e.key === 'Enter') {
            e.preventDefault();
            triggerPositionAdd();
            if ($("#identRows tr").length === 0) {
                displayShowHideDropdown();
            }
        }
    });

    $("#IdentSearch").on('keydown', function (e) {
        if (e.keyCode !== 13 && e.keyCode !== 9) {
            selectedInvoiceItemData.data = null;
            cleanIdentInput(false);
        }
    });

    $("#IdentSearch+input:not(.custom-typeahead-open), #SelectedItemQuantity, #SelectedItemPrice, #SelectedItemRebate").bind("paste", function (e) {
        var self = $(this);
        setTimeout(function () { self.trigger("keydown"); }, 0);
    });

    $('#add-position').on('click', function () {
        triggerPositionAdd();
        if ($("#identRows tr").length === 0) {
            displayShowHideDropdown();
        }
    });

    $('#SelectedItemPrice').on('change', function () {
        $('#SelectedItemPrice').attr("data-val", toNumber($('#SelectedItemPrice').val()));
    });

    prepareIdentSearchPopup(localization, paw.lang.append({
        priceType: priceType,
        discountType: discountType
    }, identSearchPopupOptions || {}));

    $.get($("#GetSysParamsUrl").val(),
        function (data) {
            if (data) {
                actionRebateOnly = data.ActionRebateOnly
            }
        });
}

async function setInvoiceItemData(item, priceType, discountType, quantity) {
    item = {
        id: item.Ident, name: item.Name, name_only: item.Name, price: item.Price, sellingPrice: item.SellingPrice, retailPrice: item.RetailPrice,
        quantity: paw.utils.value.isSet(quantity)? quantity : 1, discount: item.Discount, rabate: item.Rebate, vat: item.VAT, vatCode: item.VATCode, vatTR: item.VATReceive, vatCodeTR: item.VATCodeTR,
        vatFiscalCode: item.VATFiscalCode, measurementUnit: item.Unit, taxPrice: 0, basisForTax: item.SuppliersPrice - (item.SuppliersPrice / 100 * 10),
        priceForValue: 0, stock: item.Stock, wsPrice: item.WSPrice, wsPrice2: item.WSPrice2, prStPrice: item.PrStPrice, contractPrice: item.ContractPrice,
        contractPriceRT: item.ContractPriceRT, contractPriceRabate: item.ContractPriceRabate, department: item.Department, costDrv: item.CostDrv, isActive: item.Active === "T",
        priceRate: item.PriceRate, setItemType: item.SetItemType, colorCode: item.ColorCode, serialNo: item.SerialNo, priceType: priceType,
        prstTime: item.PrstTime, prstUMTime: item.PrstUMTime, currency: item.Currency, warehouseStockInQty: item.WarehouseStockInQty, dateDue: item.DateDue,
        wasteQty: item.WasteQty, qtySeries: item.QtySeries, qid: item.Qid, goodsAsService: item.GoodsAsService, serviceAsGoods: item.ServiceAsGoods,
        discountBegin: item.DiscountBegin, discountEnd: item.DiscountEnd, note: item.Note, vatCalcReceiver: item.VatcalcReceiver
    };

    // if tHE_SetParamTax has settings
    if (identTaxSettings) {
        // ident is not service or combined service
        if (item.setItemType !== "S" && item.setItemType !== "U") {
            if (identTaxSettings.TaxTypeGoods && item.goodsAsService === false) {
                item.vat = identTaxSettings.TaxTypeGoodsVat;
                item.vatTR = identTaxSettings.TaxTypeGoodsVat;
                item.vatCode = identTaxSettings.TaxTypeGoods;
                item.vatCodeTR = identTaxSettings.TaxTypeGoods;
            } else if (identTaxSettings.TaxTypeGoods && item.goodsAsService === true) {
                item.vat = identTaxSettings.TaxTypeGoodsAsServiceVat;
                item.vatCode = identTaxSettings.TaxTypeGoodsAsService;
                item.vatCodeTR = identTaxSettings.TaxTypeGoodsAsService;
            }
        } else { // ident is service
            if (identTaxSettings.TaxTypeService && item.serviceAsGoods === false) {
                item.vat = identTaxSettings.TaxTypeServiceVat;
                item.vatTR = identTaxSettings.TaxTypeServiceVat;
                item.vatCode = identTaxSettings.TaxTypeService;
                item.vatCodeTR = identTaxSettings.TaxTypeService;
            } else if (identTaxSettings.TaxTypeService && item.serviceAsGoods === true) {
                item.vat = identTaxSettings.TaxTypeServiceAsGoodsVat;
                item.vatTR = identTaxSettings.TaxTypeServiceAsGoodsVat;
                item.vatCode = identTaxSettings.TaxTypeServiceAsGoods;
                item.vatCodeTR = identTaxSettings.TaxTypeServiceAsGoods;
            }
        }
    }

    var selectedItemPrice = await getPriceByType(item, item.priceRate &&
        priceType !== PriceType.ReceivedBills &&
        priceType !== PriceType.OrderSuppliers &&
        priceType !== PriceType.AdvancePaymentReceived &&
        priceType !== PriceType.AdvancePaymentIssued ?
        item.priceRate : priceType, priceType);

    $("#IdentSearch").val(item.id);
    $("#IdentSearch").next().val(item.id);
    $("#SelectedItemQuantity").val(priceType === PriceType.PartList || (priceType === PriceType.Inventory && item.serialNo !== "N") ? 0 : item.quantity);
    formatNumberInput($("#SelectedItemQuantity"));
    $("#SelectedItemPrice").val(selectedItemPrice);
    $("#SelectedItemPrice").attr("data-val", selectedItemPrice);
    formatNumberInput($("#SelectedItemPrice"));
    $("#SelectedItemRebate").val(getDiscountByType(item, discountType));
    formatNumberInput($("#SelectedItemRebate"));
    $("#SelectedItemWasteQty").val(0);
    formatNumberInput($("#SelectedItemWasteQty"));
    
    if (item.prstUMTime === $("#DurationMinute").val()) {
        let time = convertMinutesToTime(item.prstTime);
        $("#TimeDuration").val(time);
    } else if (item.prstUMTime === $("#DurationHour").val()) {
        let minutes = item.prstTime * 60;
        let time = convertMinutesToTime(minutes);
        $("#TimeDuration").val(time);
    }
    selectedInvoiceItemData.data = item;
    selectedInvoiceItemData.data.selectedItemPrice = selectedItemPrice;

    pricesForSelect = [];
    pricesForSelect.push({ Id: item.sellingPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.sellingPrice) + " - " + $("#SellingPriceLoc").val(), Rabate: 0, Selected: item.priceRate === PriceType.SalePrice });
    pricesForSelect.push({ Id: item.wsPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.wsPrice) + " - " + $("#WSPriceLoc").val(), Rabate: 0, Selected: item.priceRate === PriceType.WSPrice1 });
    pricesForSelect.push({ Id: item.wsPrice2, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.wsPrice2) + " - " + $("#WS2PriceLoc").val(), Rabate: 0, Selected: item.priceRate === PriceType.WSPrice2 });
    pricesForSelect.push({ Id: item.prStPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.prStPrice) + " - " + $("#PrStPriceLoc").val(), Rabate: 0, Selected: false });
    pricesForSelect.push({ Id: item.contractPrice, Text: formatDisplay($("#DefaultDecimalPlacesPrice").val(), item.contractPrice) + " - " + $("#ContractPriceLoc").val(), Rabate: item.contractPriceRabate, Selected: true });
    addSelectOptions(pricesForSelect, "SelectedItemPriceSelect");

    $("#isIdentPerDay").val(item.measurementUnit === $("#MeusurementUnitDay").val() ? true : false);
    if (priceType === PriceType.PriceChange)
        $('#IdentSearch').next().focus();
    else
        $("#SelectedItemQuantity").focus();
}

async function triggerPositionAdd() {
    $("#SelectedItemRebate").trigger("change");

    if (!selectedInvoiceItemData || !selectedInvoiceItemData.data || $("#SelectedItemRebate").hasClass("error-input-item"))
        return;

    $("#identSearchTable :input").prop("disabled", true);
    $("#add-position").prop("disabled", true);

    $.get($("#itemExcisesUrl").val() + "?AcKey=" + $("#AcKey").val() + "&Ident=" + selectedInvoiceItemData.data.id + "&Date=" + ($("#Date").length > 0 ? $("#Date").val() : null),
        function (data) {
            if (data) {
                selectedInvoiceItemData.data.incBase = data.IncBase;
                selectedInvoiceItemData.data.notIncBase = data.NotIncBase;
                selectedInvoiceItemData.data.incBaseP = data.IncBaseP;
                selectedInvoiceItemData.data.notIncBaseP = data.NotIncBaseP;
            }

            setIdentData();
        });
}

function changeSubjectRabate(rabate) {
    subjectRabate = rabate;
}

function setIdentData() {
    let timeStart = $("#TimeStart").val();
    let timeDuration = $("#TimeDuration").val();

    if (selectedInvoiceItemData && selectedInvoiceItemData.data) {
        selectedInvoiceItemData.data.quantity = toNumber($("#SelectedItemQuantity").val());
        selectedInvoiceItemData.data.price = toNumber($("#SelectedItemPrice").attr("data-val"));
        selectedInvoiceItemData.data.rabate = toNumber($("#SelectedItemRebate").val());
        selectedInvoiceItemData.data.pricesForSelect = pricesForSelect;
        selectedInvoiceItemData.data.timeStart = timeStart;
        selectedInvoiceItemData.data.prstTime = timeDuration ? convertTimeToMinutes(timeDuration) : 0;
        selectedInvoiceItemData.data.timeEnd = (timeStart && timeDuration) ? convertMinutesToTime(convertTimeToMinutes(timeStart) + convertTimeToMinutes(timeDuration)) : null;
        selectedInvoiceItemData.data.worker = $("#Contractor").val();
        selectedInvoiceItemData.data.fixedAsset = $("#Tools").val();

        getPriceInCurrency();
    }
}

async function getPriceInCurrency() {
    if (selectedInvoiceItemData
        && selectedInvoiceItemData.data
        && selectedInvoiceItemData.data.currency !== ""
        && $("#Currency").val() !== selectedInvoiceItemData.data.currency
        && selectedInvoiceItemData.data.priceType !== PriceType.ReceivedBills
        && selectedInvoiceItemData.data.priceType !== PriceType.PartList
    ) {
        var date;
        switch (selectedInvoiceItemData.data.priceType) {
            case PriceType.ReceivedBills: date = $("#TakeoverDate").datepicker("getDate"); break;
            case PriceType.Pos: date = $("#InvoiceDate").datepicker("getDate"); break;
            default: date = $("#Date").datepicker("getDate"); break;
        }

        $.get($("#getIdentFxRateUrl").val(), { Currency: $("#Currency").val(), IdentCurrency: selectedInvoiceItemData.data.currency, Date: new Date(date).toISOString() })
            .done(function (response) {
                if (response) {
                    selectedInvoiceItemData.data.price = toNumber(calculateWithOperation(selectedInvoiceItemData.data.price, response));

                    if (toNumber($("#RoundPrice").val()) > 0)
                        selectedInvoiceItemData.data.price = toNumber(selectedInvoiceItemData.data.price.toFixed(toNumber($("#RoundPrice").val())));
                }

                canAddPosition(selectedInvoiceItemData.data);
                selectedInvoiceItemData.data = null;
                cleanIdentInput(true);
            });
    } else {
        if (selectedInvoiceItemData.data.priceType === PriceType.PartList)
            addPositionPartList(selectedInvoiceItemData.data);
        else
            canAddPosition(selectedInvoiceItemData.data);
        selectedInvoiceItemData.data = null;
        cleanIdentInput(true);
    }
}

function canAddPosition(invoiceItemData) {
    if (invoiceItemData.priceType === PriceType.Pos && invoiceItemData.vatCalcReceiver === "T") {
        $().customModal({
            title: "",
            destroyOnClose: true,
            showCloseButton: true,
            type: "alert",
            text: stringFormat($("#VatCodeWithReversePaymentPosLoc").val(), invoiceItemData.vatCode),
            buttons: [
                {
                    icon: 'fa fa-times',
                    text: $("#NoLoc").val(),
                    closeOnAction: true,
                    type: 'ghost'
                },
                {
                    icon: 'fa fa-check',
                    text: $("#YesLoc").val(),
                    action: async function () {
                        addPosition(invoiceItemData);
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });
    } else
        addPosition(invoiceItemData);
} 

function cleanIdentInput(cleanSearch) {
    if (cleanSearch) {
        $("#IdentSearch").val('');
        $("#IdentSearch").text('');
        $("#IdentSearch").focus();
        $("#IdentSearch").next().val("");
    }

    $("#SelectedItemQuantity").val('');
    $("#SelectedItemPrice").val('');
    $("#SelectedItemRebate").val('');
    $("#TimeStart").val('');
    $("#TimeDuration").val('');
    $("#Contractor").val('');
    $("#Contractor").selectpicker('render');
    $("#Tools").val('');
    $("#Tools").selectpicker('render');
}

function getPriceByPriceType(ident, priceType) {
    if (ident.contractPrice !== null && ident.contractPrice > 0)
        return ident.ContractPrice;
    else if (priceType === PriceType.SalePrice)
        return ident.SellingPrice;
    else if (priceType === PriceType.WSPrice1)
        return ident.WSPrice;
    else if (priceType === PriceType.WSPrice2)
        return ident.WSPrice2;
    else if (priceType === PriceType.ReceivedBills || priceType === PriceType.OrderSuppliers)
        return ident.SuppliersPrice;
    else if (priceType === PriceType.Wholesale)
        return ident.SellingPrice;
    else if (priceType === PriceType.OrderBuyer)
        return ident.SellingPrice;
    else
        return ident.RetailPrice;
}

async function getPriceByType(ident, priceType, invoiceType = null) {
    if (invoiceType === PriceType.Pos && ident.contractPriceRT !== null && ident.contractPriceRT > 0)
        return ident.contractPriceRT;
    else if (invoiceType !== PriceType.Pos && ident.contractPrice !== null && ident.contractPrice > 0)
        return ident.contractPrice;
    else if (invoiceType === PriceType.Pos)
        return ident.retailPrice;
    else if (priceType === PriceType.AdvancePaymentReceived || priceType === PriceType.AdvancePaymentIssued)
        return 0;
    else if (priceType === PriceType.SalePrice) {
        if (invoiceType === PriceType.Pos)
            return round(ident.sellingPrice + (ident.sellingPrice / 100 * ident.vat));
        return ident.sellingPrice;
    } else if (priceType === PriceType.WSPrice1) {
        if (invoiceType === PriceType.Pos)
            return round(ident.wsPrice + (ident.wsPrice / 100 * ident.vat));
        else
            return ident.wsPrice;
    } else if (priceType === PriceType.WSPrice2) {
        if (invoiceType === PriceType.Pos)
            return round(ident.wsPrice2 + (ident.wsPrice2 / 100 * ident.vat));
        else
            return ident.wsPrice2;
    } else if (priceType === PriceType.ReceivedBills)
        return ident.price;
    else if (priceType === PriceType.OrderSuppliers) {
        return ident.price;
    } else if (priceType === PriceType.Wholesale || priceType === PriceType.OrderBuyer) {
        return ident.sellingPrice;
    } else if (priceType === PriceType.PartList) {
        return ident.prStPrice;
    } else {
        if (isLocale(siteLocale.HR) && ident.currency !== $("#Currency").val() && $("#Currency").val()) {
            var identFXRate = await getIdentFxRate(ident.currency);
            return ident.retailPrice / toNumber(identFXRate);
        } else
            return ident.retailPrice;
    }
}

function getDiscountByType(ident, discountType) {
    if (new Date(moment(ident.discountBegin)) > Date.now() || new Date(moment(ident.discountEnd)) < Date.now())
        ident.discount = 0;

    if (actionRebateOnly === true && ident.discount > 0)
        return ident.discount;
    else if (ident.contractPriceRabate > 0)
        return ident.contractPriceRabate;
    else if (discountType === DiscountType.SellerDiscount)
        return subjectRabate > 0 && (actionRebateOnly === false || (actionRebateOnly === true && ident.discount <= 0)) ? subjectRabate + ident.discount : ident.discount;
    else if (discountType === DiscountType.SupplierRebate)
        return subjectRabate > 0 ? subjectRabate + ident.rabate : ident.rabate;
    else
        return ident.discount;
}

function displayIdentCreateErrors(idents, err = null, continuePrint) {
    var errMsg = "";
    var firstErrorIdent = "";
    var firstError;
    var errorList = [];
    if (err && err !== "")
        errMsg += err + "<br /><br />";
    if (idents) {
        for (var i = 0; i < idents.length; i++) {
            if (idents[i].Error !== "") {
                var ident = invoiceItems.filter(x => x.AnNo === idents[i].AnNo)[0];
                if (firstErrorIdent === "")
                    firstErrorIdent = ident;

                if (errorList && !errorList.includes(idents[i].Error)) {
                    if (!firstError)
                        firstError = idents[i];

                    errMsg += idents[i].Error + "<br /><br />";
                    errorList.push(idents[i].Error);
                }
            }
        }
    }

    if (errMsg !== "") {
        $("#IdentCreateErrMsg").val(errMsg);

        $().customModal({
            destroyOnClose: true,
            showCloseButton: true,
            type: "error",
            text: errMsg,
            buttons: [
                {
                    icon: 'fa fa-check',
                    text: $("#ConfirmLoc").val(),
                    action: async function () {
                        if (continuePrint) {
                            printWindow = createPrintWindow(printWindow);
                            var func = new Function(continuePrint);
                            func();
                        } else if (firstError && firstError.Status === "39") {
                            $("#quantity-" + firstError.AnNo).focus();
                        }
                    },
                    closeOnAction: true,
                    type: 'primary'
                }
            ]
        });

        focusElement = firstErrorIdent;
    }
}

function displayErrors(response, continuePrint = null, onlyOpenIdent = false) {
    var error = "";
    var itemErrors;

    if (response.data && response.data.Error && response.data.Error !== "") {
        error += response.data.Error;
    }

    if (response.data && response.data.ItemsCreateResponse && response.data.ItemsCreateResponse.length > 0) {
        itemErrors = response.data.ItemsCreateResponse;

        if (itemErrors.some(el => el.Error !== ""))
            lockIdentSearchTable(true);
        else
            lockIdentSearchTable(false, onlyOpenIdent);
    } else
        lockIdentSearchTable(false, onlyOpenIdent);

    displayIdentCreateErrors(itemErrors, error, continuePrint);
}

function lockIdentSearchTable(isError, onlyOpenIdent = false, isUpdate = false) {
    if (isError === true) {
        $("#identSearchTable :input").prop("disabled", true);
        $("#add-position").prop("disabled", true);
    } else {
        $("#IdentCreateErrMsg").val("");
        if (onlyOpenIdent === true)
            $(".td-ident-search :input").prop("disabled", false);
        else
            $("#identSearchTable :input").prop("disabled", false);
        $("#add-position").prop("disabled", false);
        if (isUpdate === false)
            $('#IdentSearch').next().focus();
    }
}

function calculatePriceWithExcise(item) {
    var price = item.price + (item.price * item.incBaseP) + item.incBase;
    var discountedPrice = item.price - (item.price / 100 * item.rabate);
    var discountedPriceWithExcise = discountedPrice + (discountedPrice * item.incBaseP) + item.incBase;

    var vat = price / 100 * item.vat;
    var vatDiscountedPrice = discountedPriceWithExcise / 100 * item.vat;

    price = ((vat + price) + (price * item.notIncBaseP) + item.notIncBase) * item.quantity;
    discountedPriceWithExcise = ((vatDiscountedPrice + discountedPriceWithExcise) + (discountedPriceWithExcise * item.notIncBaseP) + item.notIncBase) * item.quantity;

    return {
        priceWithExcise: price,
        discountedPriceWithExcise: discountedPriceWithExcise,
        vat: vatDiscountedPrice * item.quantity,
        vatDiscount: discountedPriceWithExcise - discountedPrice * item.quantity
    };
}

function getIdentFxRate(identCurrency) {
    var date = $('#InvoiceDate').length > 0 && $("#InvoiceDate").datepicker("getDate") ? $("#InvoiceDate").datepicker("getDate") : Date.now();

    return new Promise(function (resolve, reject) {
        fetch($("#GetIdentFxRateUrl").val() + "?Currency=" + $("#Currency").val() + "&IdentCurrency=" + identCurrency + "&Date=" + new Date(date).toISOString(), {
            method: "GET",
            headers: { 'Content-Type': 'application/json' }
        }).then((response) => response.json()
        ).then((data) => {
            resolve(data);
        }).catch(() => {
            resolve(1);
        });
    });
}

function prepareIdentSearchPopup(localization, identSearchPopupOptions) {
    identSearchPopup = new paw.com.identSearch.IdentSearchPopup(identSearchPopupOptions, localization);
}