/* Minification failed. Returning unminified contents.
(861,64-65): run-time error JS1195: Expected expression: >
(861,99-100): run-time error JS1004: Expected ';': )
(951,43-44): run-time error JS1195: Expected expression: .
(1227,66-67): run-time error JS1195: Expected expression: >
(1227,154-155): run-time error JS1195: Expected expression: >
(1228,9-11): run-time error JS1195: Expected expression: ||
(1552,62-63): run-time error JS1195: Expected expression: >
(1552,97-98): run-time error JS1004: Expected ';': )
(1752,80-81): run-time error JS1195: Expected expression: >
(1752,82-85): run-time error JS1197: Too many errors. The file might not be a JavaScript file: new
(1420,1-30): run-time error JS1301: End of file encountered before function is properly closed: function DlgSend(_withPublic)
(1752,115-116): run-time error JS1004: Expected ';': )
(1752,117-119): run-time error JS1197: Too many errors. The file might not be a JavaScript file: ||
 */
parent.DataStreem = true;

var NeedInitiate = true
    , send_data
    , Need_dgFileList = true
    , cdb2_public_edit = false
    , bankrupt_edit = false
    , valueAddedTaxIncluded
    , auctionType = ""
    , N_accountNumber = 0
    , withPublic
    , severalBids = false
    , set_fields = ""
    , bids = []
    , sw_ReadOnly
    , data
    , on_first_publc
    , dgf_itemProps = ""
    , dgf_methodType = ""
    , tenderType = ""
    , registryRecord = {}
    , cdb3_dgf = false
    , cdb3_rent = false
    , d_intendedUse
    , only_transferPriorityPeriod = false
    , copy_currentTenant = false
    , rent_rectification = false
    , dutchSteps = 99
    , lot_bid_participate = {}
    , form_code = ""
    , dialog_close
    , isOwn = false
    , ReadOnly = true
    , oFormRecord = ""
    , current_state
    , doc_readonly = true
    , tender_doc_list = ""
    , current_minute = -1
    , previousAuctionId
    , id_maps = ""
    , already_participated = false
    , update_bankRuptcy_info = false
    , not_copy = false
    , d_tender_type = {}
    , similar_procedures = false
    , prev_tenderType = ""
    , withPublic_land = true
    , tenderType_for_additionalClassification_cpvs = ['alienation', 'bankRuptcy', 'basicSell', 'commercialPropertyLease', 'commercialSell', 'dgf', 'legitimatePropertyLease', 'nonperformingLoans', 'railwayCargo', 'regulationsPropertyLease', 'timber']
    , tenderType_for_additionalClassification_cvzu = ['alienation', 'bankRuptcy', 'basicSell', 'commercialPropertyLease', 'commercialSell', 'landArrested', 'landRental', 'landSell', 'largePrivatization', 'legitimatePropertyLease', 'nonperformingLoans', 'regulationsPropertyLease', 'smallPrivatization']
    , tenderType_for_additionalClassification_kvtspz = ['bankRuptcy', 'landArrested', 'landRental', 'landSell'];

var CLIENT_ID = '409235550957-shevbv1ksvm7v56ou399potcas9g43c2.apps.googleusercontent.com';
var API_KEY = 'AIzaSyDNWkG2DdgHICb6nqsrSgEUYXRo-dihINI';
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
var SCOPES = "https://www.googleapis.com/auth/calendar";

function LoadData() {
    if (NeedInitiate)
        Initiate();

    if (timeRefresh == 0) {
        GetTime();
    }
    else {
        timeRefresh--;
    }

    check_minute();
}

function check_minute() {
    var _minute = (new Date).getMinutes()
    if (current_minute == _minute)
        return;

    refresh_get_auctionPeriod_startDate();

    current_minute = _minute;
}

var attempt_auctionPeriod_startDate = 3;

function refresh_get_auctionPeriod_startDate() {

    if (isPlaceTestMode && oFormRecord != undefined && current_state == "active.tendering" && PMT == "dgfInsider"
        && oFormRecord.auctionPeriod != undefined && oFormRecord.auctionPeriod.startDate == undefined
    ) {
        if (attempt_auctionPeriod_startDate == 0) {
            setTimeout(refresh_page, 5000);
            attempt_auctionPeriod_startDate = 3;
        }
        else
            attempt_auctionPeriod_startDate--;
    }
}

function refresh_on_end_tenderPeriod() {
    if (oFormRecord != undefined && current_state == "active.tendering"
        && oFormRecord.tenderPeriod != undefined && oFormRecord.tenderPeriod.endDate <= (new Date).toIsoString()
    )
        setTimeout(refresh_page, 5000);
}

function refresh_page() {
    ShowFrame("auction/" + form_code);
}

function process() {
    //            return;
    if (xmlDoc.readyState != 4) return;
    //        alert(xmlDoc.responseXML.xml);

    if (xmlDoc.responseText == "")
        ShowFrame("Main.aspx");

    ResponseType = $(xmlDoc.responseXML).find("response").attr("type");

    try {
        switch (ResponseType) {
            case "Time":
                setTime();
                break;
        }

        if (ResponseType == "Repeat")
            DoSendCommand(doCommand, doParams);
        else
            CommandCompleated();
    }
    catch (err) {
        alert("Помилка обробки запиту: " + err.Description);
        CanalBusy = false;
    }
}

function Initiate() {
    MasterInit();

    if (page_data.row.data.auctionID != undefined)
        form_code = page_data.row.data.auctionID;
    else if (page_data.row.data.auctionId != undefined)
        form_code = page_data.row.data.auctionId;

    if (page_data.row.data.id != undefined)
        idForm = page_data.row.data.id;
    else if (page_data.row.data._id != undefined)
        idForm = page_data.row.data._id;

    NeedInitiate = false;

    show_load_data();

    HandleData(page_data);
}

function HandleData(response) {
    full_data = response;

    var message = response.message;

    if (message != "OK") {
        ErrorMessage(message);
        return;
    }

    ReadOnly = response.ReadOnly == "true";
    isOwn = response.isOwn == "true";

    var object_id = getPageParam("object_id");
    let param_priority = getPageParam("priority")
    if (object_id != undefined) {
        $.getJSON("RegistryHandler.ashx?CN=" + vCN + "&CommandName=jGetAssetRent&code=" + object_id
            , HandleObject);
        if (param_priority != undefined) {
            priority = true;
            tenderType = "legitimatePropertyLease-priorityEnglish"
        }
    }
}

var NeedShowForm = true;
jQuery(document).ajaxStop(ajaxDone);

function ajaxDone() {
    if (wait_ThemeDics)
        ThemeDicsLaded();

    if (NeedShowForm) {

        if (!hasRequestForData)
            return;

        if (oFormRecord == undefined)
            return;

        hide_load_data();

        GetThemeDics();

        NeedShowForm = false;

        if (!(idForm == 0 && member_type == 907)) {
            wait_HandleViewForm();
        } else {
            choose_commercial_tenderType();
        }
    }
}

function wait_HandleViewForm() {

    if (!check_ThemeDics_loaded()) {
        setTimeout(wait_HandleViewForm, 100);
        return;
    }

    Init();

    HandleBids();

    HandleViewForm();

    if (getPageParam("save_OK") != undefined) {
        FormTips = $("#ValidateTips");
        updateTips("Збереження виконано", "N");
    }
    else if (getPageParam("published") != undefined) {
        published_obj_type = getPageParam("published_obj_type");
        published_obj_id = getPageParam("published_obj_id");

        if (published_obj_type == "award") {
            FormTips = $("#award_ValidateTips_" + published_obj_id);
            updateTips(get_public_message(published_obj_id), "N");
        }
        if (published_obj_type == "contract") {
            FormTips = $("#" + published_obj_type + "_ValidateTips_" + published_obj_id);
            updateTips(get_contract_public_message(published_obj_id), "N");
        }
        if (published_obj_type == "qualification") {
            FormTips = $("#ql_ValidateTips_" + published_obj_id);
            updateTips(get_public_message(published_obj_id), "N");
        }
        else {
            FormTips = $("#ValidateTips");
            updateTips(get_public_message(), "N");
        }
    }

    ShowContent();
}

function HandleViewForm() {
    current_state = oFormRecord["status"];

    if (!isPlaceTestMode)
        $('.pn_test_params').hide();

    if (idForm != 0) {
        $('.tOnNew').hide();

        if (cdb == 3) {
            oFormRecord.procuringEntity = oFormRecord.sellingEntity;

            set_tenderType();
        }

        PMT = oFormRecord.procurementMethodType;

        if (cdb == 3 && oFormRecord.sellingMethod.indexOf('railwayCargo') > -1) {
            tenderType = 'railwayCargo'
        }

        if ((cdb == 2 || cdb == 3) && (full_data.canSave != 'true' && full_data.canPublic == 'true')) {
            if (tenderType == "bankrupt")
                bankrupt_edit = true;
            else
                cdb2_public_edit = true;
        }
        else if (cdb == 1 && isOwn && current_state == "active.tendering" && (full_data.canSave != 'true' && full_data.canPublic == 'true' || isDebugMode))
            cdb1_public_edit = true;

        //if (current_state == "active.tendering" || current_state == "active_tendering")
        //    $("#btnGoogleCalendar").show();

        oFormRecord.value_amount = oFormRecord.value.amount;
        oFormRecord.value_currency = oFormRecord.value.currency;

        if (oFormRecord.normativeMonetaryValuation != undefined) {
            oFormRecord.normativeMonetaryValuation = oFormRecord.normativeMonetaryValuation.amount;
        }

        if (oFormRecord.expertMonetaryValuation != undefined) {
            oFormRecord.expertMonetaryValuation = oFormRecord.expertMonetaryValuation.amount;
        }

        if (oFormRecord.budgetSpent != undefined) {
            oFormRecord.budgetSpent_amount = oFormRecord.budgetSpent.amount;
        }

        if (full_data.registrationFee != undefined)
            oFormRecord.registrationFee_amount = full_data.registrationFee.replace(",", ".");
        else if (oFormRecord.registrationFee != undefined)
            oFormRecord.registrationFee_amount = oFormRecord.registrationFee.amount;

        if (oFormRecord.currentTenantGuaranteeFee != undefined) {
            oFormRecord.currentTenantGuaranteeFee_amount = oFormRecord.currentTenantGuaranteeFee.amount;
        }

        if (oFormRecord.tenderAttempts == undefined)
            oFormRecord.tenderAttempts = "";

        if (isOwn) {
            $('.NonOwn').hide();
            if (cdb == 2 && oFormRecord.status == "active.tendering") {
                public_value_amount = oFormRecord.value.amount;
                public_minimalStep_amount = oFormRecord.minimalStep.amount
                public_guarantee_amount = oFormRecord.guarantee.amount
            }
        }
        else {
            oFormRecord.cost = CashView(oFormRecord.value_amount);

            li = GetItemById(d_currency, oFormRecord.value.currency);
            if (li != undefined)
                currency = li.list_name;
            if (currency == undefined)
                currency = oFormRecord.value_currency;

            oFormRecord.cost += " " + currency;

            if (!(tenderType.indexOf('legitimatePropertyLease') > -1)) {
                oFormRecord.PE_name = (oFormRecord.procuringEntity.name.uk_UA != undefined ? oFormRecord.procuringEntity.name.uk_UA : oFormRecord.procuringEntity.name);
                oFormRecord.CP_telephone = oFormRecord.procuringEntity.contactPoint.telephone;
            } else {
                oFormRecord.PE_name = oFormRecord.relatedOrganizations.sellingEntity.name.uk_UA;
                oFormRecord.CP_telephone = oFormRecord.relatedOrganizations.sellingEntity.contactPoint.telephone;
            }
        }

        if (is_privatization) {
            oFormRecord.procurementMethodTypeText = GetItemById(d_dict, "privatization_PMT_" + oFormRecord.tenderAttempts, 'privatization_PMT_tenderAttempts').name;
        } else if (tenderType == "dgf") {
            var li = GetItemById(d_dict, dgf_methodType, 'methodType_dgf');
            if (li != undefined) {
                oFormRecord.procurementMethodTypeText = li["name"];
            }
        } else {
            var li = GetItemById(d_dict, PMT, 'methodType');
            if (li != undefined) {
                if (lang == "en") {
                    oFormRecord.procurementMethodTypeText = li["name_en"];
                } else {
                    oFormRecord.procurementMethodTypeText = li["name"];
                }
            }
        }

        var li = set_sellingMethod(false);

        if (li != undefined) {
            if (lang == "en") {
                oFormRecord.tenderTypeText = li["name_en"];
            } else {
                oFormRecord.tenderTypeText = li["name"];
            }
        }

        show_elems_on_MethodType();

        if (oFormRecord.minimalStep != undefined)
            oFormRecord.minimalStep_amount = oFormRecord.minimalStep.amount;

        if (oFormRecord.rectificationPeriod != undefined) {
            sd = oFormRecord.rectificationPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.rectificationPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.rectificationPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.rectificationPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.rectificationPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.rectificationPeriod_endDate_Time = str_sd.substr(11, 5);
            }

            if (strStartsWith(oFormRecord.id, 'web')) {
                if (cdb == 2)
                    $("#pn_enter_rectificationPeriod").show();
            } else
                $("#pn_rectificationPeriod").show();

        }

        if (oFormRecord.transferPriorityPeriod != undefined) {
            sd = oFormRecord.transferPriorityPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.transferPriorityPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.transferPriorityPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.transferPriorityPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.transferPriorityPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.transferPriorityPeriod_endDate_Time = str_sd.substr(11, 5);
            }

            $("#pn_transferPriorityPeriod").show();
        }

        if (oFormRecord.clarificationPeriod != undefined) {
            sd = oFormRecord.clarificationPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.clarificationPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.clarificationPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.clarificationPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.clarificationPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.clarificationPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }

        if (oFormRecord.questionPeriod != undefined) {
            sd = oFormRecord.questionPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.questionPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.questionPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.questionPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.questionPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.questionPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }

        if (oFormRecord.admissionPeriod != undefined) {
            $("#pn_admissionPeriod").show();
            sd = oFormRecord.admissionPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.admissionPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.admissionPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.admissionPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.admissionPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.admissionPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }

        if (oFormRecord.enquiryPeriod != undefined) {
            sd = oFormRecord.enquiryPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.enquiryPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.enquiryPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.enquiryPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.enquiryPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.enquiryPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }

        if (oFormRecord.complaintPeriod != undefined) {
            sd = oFormRecord.complaintPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.complaintPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.complaintPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.complaintPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.complaintPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.complaintPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }
        else {
            oFormRecord.complaintPeriod_startDate_Time = "09:00";
            oFormRecord.complaintPeriod_endDate_Time = "09:00";
        }

        if (oFormRecord.tenderPeriod != undefined) {
            sd = oFormRecord.tenderPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.tenderPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.tenderPeriod_startDate_Time = str_sd.substr(11, 5);

                //            oFormRecord.enquiryPeriod_startDate_Date = oFormRecord.tenderPeriod_startDate_Date
                //            oFormRecord.enquiryPeriod_startDate_Time = oFormRecord.tenderPeriod_startDate_Time

            }
            else {
                oFormRecord.tenderPeriod_startDate_Time = "09:00";
            }

            sd = oFormRecord.tenderPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.tenderPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.tenderPeriod_endDate_Time = str_sd.substr(11, 5);


                //            oFormRecord.enquiryPeriod_endDate_Date = oFormRecord.tenderPeriod_endDate_Date;
                //            oFormRecord.enquiryPeriod_endDate_Time = oFormRecord.tenderPeriod_endDate_Time

                oFormRecord.tenderPeriod_endDate = sISO_8601_2_DMYHM(sd);
            }
        }

        if (oFormRecord.contractTerms != undefined && oFormRecord.contractTerms.leaseTerms != undefined
            && oFormRecord.contractTerms.leaseTerms.leaseDuration != undefined) {
            leaseDuration = Iso8601DurationPeriod(oFormRecord.contractTerms.leaseTerms.leaseDuration);
            oFormRecord.leaseDuration_y = leaseDuration.period.variables.Y;
            oFormRecord.leaseDuration_m = leaseDuration.period.variables.M;
            oFormRecord.leaseDuration_d = leaseDuration.period.variables.D;
        }

        if (oFormRecord.lotId != undefined)
            oFormRecord.dgfID = oFormRecord.lotId;
        else if (oFormRecord.lotIdentifier != undefined)
            oFormRecord.dgfID = oFormRecord.lotIdentifier;

        if (oFormRecord.decision != undefined && oFormRecord.decision.decisionDate != undefined) {
            oFormRecord.decision.decisionDate = sY_M_D_2DMY(oFormRecord.decision.decisionDate);
        }

        if (oFormRecord.auctionPeriod != undefined) {
            sd = oFormRecord.auctionPeriod.startDate;

            if (sd == undefined && PMT != "dgfInsider")
                sd = oFormRecord.auctionPeriod.shouldStartAfter;

            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.auctionPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.auctionPeriod_startDate_Time = str_sd.substr(11, 5);
            }
            else {
                oFormRecord.auctionPeriod_startDate_Time = "11:00";
            }

            sd = oFormRecord.auctionPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.auctionPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.auctionPeriod_endDate_Time = str_sd.substr(11, 5);

                oFormRecord.auctionPeriod_endDate = sISO_8601_2_DMYHM(oFormRecord.auctionPeriod.endDate);
                $("#pn_Position_auctionPeriod_endDate").show();
                $("#tdtpPosition_auctionPeriod_endDate_Date").text(oFormRecord.auctionPeriod_endDate_Date);
                $("#tePosition_auctionPeriod_endDate_Time").text(oFormRecord.auctionPeriod_endDate_Time);

            }
        }

        if (oFormRecord.qualificationPeriod != undefined) {
            $('.qualificationPeriod').each(function () { $(this).show() });

            sd = oFormRecord.qualificationPeriod.startDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.qualificationPeriod_startDate_Date = str_sd.substr(0, 10);
                oFormRecord.qualificationPeriod_startDate_Time = str_sd.substr(11, 5);
            }

            sd = oFormRecord.qualificationPeriod.endDate;
            if (sd != undefined) {
                var str_sd = sISO_8601_2_DMYHM(sd);
                oFormRecord.qualificationPeriod_endDate_Date = str_sd.substr(0, 10);
                oFormRecord.qualificationPeriod_endDate_Time = str_sd.substr(11, 5);
            }
        }
        else {
            oFormRecord.qualificationPeriod_startDate_Time = "09:00";
            oFormRecord.qualificationPeriod_endDate_Time = "09:00";
        }

        if (oFormRecord.guarantee != undefined) {
            if (oFormRecord.guarantee.amount > 0 || tenderType.includes("simpleSell")) {
                $("#pn_guarantee").show();
                oFormRecord.guarantee_amount = oFormRecord.guarantee.amount;
            }
        }

        if (oFormRecord.auctionPeriod != undefined && !strStartsWith(oFormRecord.id, 'web')) {//&& oFormRecord.auctionUrl!=undefined
            $("#pn_auction").show();

            sd = oFormRecord.auctionPeriod.startDate;
            if (sd != undefined) {
                oFormRecord.auctionPeriod_startDate = sISO_8601_2_DMYHM(sd);
            }

            sd = oFormRecord.auctionPeriod.endDate;
            if (sd != undefined) {
                oFormRecord.auctionPeriod_endDate = sISO_8601_2_DMYHM(sd);
            }

            if (tenderType != "renewables" && lot_bid_participate["tender"] != undefined && lot_bid_participate["tender"].participationUrl != undefined) {
                $('#aPosition_auctionUrl').text(isPlaceTestMode ? (isAdmin_kc ? "Встановлено проведення аукціону, посилання не доступне для КЦ" : lot_bid_participate["tender"].participationUrl) : 'Посилання на аукціон');
                if (!isPlaceTestMode)
                    $('#aPosition_auctionUrl').addClass("button tender-button");
                $('#aPosition_auctionUrl').prop("href", (isAdmin_kc ? "javascript:void(0);" : lot_bid_participate["tender"].participationUrl));
            } else if (oFormRecord.auctionUrl != undefined) {
                $('#aPosition_auctionUrl').text(isPlaceTestMode ? (isAdmin_kc ? "Встановлено проведення аукціону, посилання не доступне для КЦ" : oFormRecord.auctionUrl) : 'Посилання на аукціон');
                if (!isPlaceTestMode)
                    $('#aPosition_auctionUrl').addClass("button tender-button");
                $('#aPosition_auctionUrl').prop("href", (isAdmin_kc ? "javascript:void(0);" : oFormRecord.auctionUrl));
            }
        }

        if (oFormRecord.value.valueAddedTaxIncluded != undefined && oFormRecord.value.valueAddedTaxIncluded != 'False'
            && (oFormRecord.value.valueAddedTaxIncluded == 'True' || oFormRecord.value.valueAddedTaxIncluded))
            $('#cbPosition_value_valueAddedTaxIncluded').prop('checked', 'checked');


        if (!strStartsWith(oFormRecord.id, 'web')) {
            if (full_data.ReadOnly != 'true' || tenderType == "timber")
                SetViewForm('#pn_auctionType');

            if (oFormRecord.questions == undefined) amount = 0; else amount = oFormRecord.questions.length;

            $('#questions_amount').text(amount);
            $('#questions_ref').click(function () { ShowFrame("Position_questions.aspx", '&id=' + oFormRecord.id) });

            if (oFormRecord.complaints == undefined) amount = 0; else amount = oFormRecord.complaints.length;

            if (oFormRecord.awards != undefined)
                for (var a = 0; a < oFormRecord.awards.length; a++) {
                    var award = oFormRecord.awards[a];
                    if (award.complaints != undefined)
                        amount += award.complaints.length;
                }

            $('#complaints_amount').text(amount);
            $('#complaints_ref').click(function () { ShowFrame("Position_complaints.aspx", '&id=' + oFormRecord.id) });

            if (oFormRecord.bids == undefined) amount = 0; else amount = oFormRecord.bids.length;

            $('#bids_amount').text(amount);
            $('#bids_ref').click(function () { ShowFrame("Position_bids.aspx", '&id=' + oFormRecord.id) });

            if (oFormRecord.cancellations != undefined) {
                $('#cancels_ref').show().click(function () { ShowFrame("Position_cancellations.aspx", '&id=' + oFormRecord.id + "&cancellationOf=tender") });

                $('#cancels_amount').show().text(oFormRecord.cancellations.length);
            }
        }

        if (oFormRecord.bids != undefined && oFormRecord.bids.length > 0)
            bids = oFormRecord.bids;
        else
            bids = full_data.bids;

        if (bids != undefined && bids.length > 0) {
            $('#pn_bids').show();

            $('#pn_bids_content').wSHdiv({ Title: "Пропозиції" });

            Show_bid_records(bids, '');
        }

        if (oFormRecord.awards != undefined && oFormRecord.awards.length > 0) {
            $('#pnAwards').show();

            $('#pn_Award_content').wSHdiv({ Title: "Кваліфікація" });

            ShowAwardRecords();
        }

        if (oFormRecord.items != undefined)
            oFormRecord.items_count = oFormRecord.items.length;

        if (cdb == 2 || cdb == 3) {
            $('#tPosition_auctionPeriod_period').text("11-00 до 17-00");
            $('#aPosition_auctionReglament_link').attr("href", "/reglament.aspx");
        }

        if (isPlaceTestMode) {
            if (cdb == "3") {
                if (strEndsWith(oFormRecord.sellingMethod, "-fast"))
                    $("#r_auction_MethodDetails_fast").prop('checked', 'checked');
                else if (strEndsWith(oFormRecord.sellingMethod, "-initial-auction"))
                    $("#r_auction_MethodDetails_initial_auction").prop('checked', 'checked');
                else if (strEndsWith(oFormRecord.sellingMethod, "-initial-auction-manual"))
                    $("#r_auction_MethodDetails_initial_auction_manual").prop('checked', 'checked');
                else if (strEndsWith(oFormRecord.sellingMethod, "-initial-qualification"))
                    $("#r_auction_MethodDetails_initial_qualification").prop('checked', 'checked');
                else if (strEndsWith(oFormRecord.sellingMethod, "-fast-manual"))
                    $("#r_auction_MethodDetails_fast_manual").prop('checked', 'checked');

                cb_auction_MethodDetails_onchange();
            }
            else {
                $('#cb_is_quick').prop('checked', 'checked');
                var str = oFormRecord.procurementMethodDetails;

                if (str != undefined) {
                    str = str.substr(str.indexOf("=") + 1);

                    $("#ePosition_quick_value").val(str);

                    if (oFormRecord.submissionMethodDetails == "quick(mode:fast-forward)")
                        $("#r_auction_MethodDetails_fast_forward").prop('checked', 'checked');
                    else if (oFormRecord.submissionMethodDetails == "quick(mode:no-auction)")
                        $("#r_auction_MethodDetails_no_auction").prop('checked', 'checked');
                    else
                        $("#r_auction_MethodDetails_").prop('checked', 'checked');
                }
            }
        }

        if (cdb != 3 && (oFormRecord.auctionParameters != undefined && oFormRecord.auctionParameters.dutchSteps != undefined || auctionType == "appraisal.insider" || auctionType == "dutch")) {
            $("#pn_auctionParameters_dutchSteps").show();
            if (auctionType == "dutch" && oFormRecord.dutchStep != undefined)
                oFormRecord.auctionParameters_dutchSteps = oFormRecord.dutchStep.dutchStepQuantity;
            else if (oFormRecord.auctionParameters != undefined)
                oFormRecord.auctionParameters_dutchSteps = oFormRecord.auctionParameters.dutchSteps;
        }

        set_dutchStep();

        if (tenderType == "legitimatePropertyLease-english" && oFormRecord.tenderAttempts == 2) {
            oFormRecord.auctionType = "english-2";
        }

        if (tenderType == "legitimatePropertyLease-priorityEnglish" && oFormRecord.tenderAttempts == 1) {
            oFormRecord.auctionType = "priorityEnglish";
        }

        if (page_data.assetID != "") {
            $("#tPosition_assetID").attr("href", "asset/" + oFormRecord.assetID + "");
        }
        if (page_data.lotID != "") {
            $("#lotID").show();
            oFormRecord.lotID = page_data.lotID;
            $("#tPosition_lotID").attr("href", "lot/" + oFormRecord.lotID + "");
        }

        $("#tPosition_tenderID").attr("href", "auction/" + oFormRecord.auctionID + "");

        if (cdb != 3)
            bankAccount = (page_data.row.data.bankAccount != undefined ? page_data.row.data.bankAccount : oFormRecord.bankAccount);
    } else {
        $('.NonOwn').hide();
        $('.col48').css("width", "48%");

        if (full_data.canSave == 'true')
            $("[data-atid='btnSaveLast']").show();

        oFormRecord.tenderID = "Новий аукціон";
        oFormRecord.statusText = "Створення";

        $('#ToSave').show();

        if (oFormRecord.procurementMethodType == null) {
            oFormRecord.procurementMethodType = "all";
        }

        if (oFormRecord.sellingMethod != undefined && oFormRecord.procurementMethodType == undefined) {
            oFormRecord.procurementMethodType = oFormRecord.sellingMethod;
        }

        if (oFormRecord.tenderAttempts == null)
            oFormRecord.tenderAttempts = "all";

        PMT = oFormRecord.procurementMethodType;

        if (oFormRecord.auctionPeriod_startDate_Time == null)
            oFormRecord.auctionPeriod_startDate_Time = "11:00";

        oFormRecord.value_currency = "UAH";
        oFormRecord.guarantee_currency = "UAH";

        $('#pnOnId').hide();

        if (isPlaceTestMode) {
            $("#pn_quick").show();
            $("#ePosition_quick_value").val("360");
            $('#cb_is_quick').prop('checked', 'checked');
            $("#r_auction_MethodDetails_fast_forward").prop('checked', 'checked');
        }

        if (tenderType == "")
            if (member_type == "906" || member_type == "908" || member_type == "909" || member_type == "910" || member_type == 911 || member_type == 912 || member_type == 914 || member_type == 913) {
                slPosition_tenderType_onchange();
            }

        if (cdb == 2) {
            oFormRecord.minNumberOfQualifiedBids = 2;
            if (tenderType == "bankrupt")
                oFormRecord.minNumberOfQualifiedBids = 1;
        }
    }

    set_fields = "owner,lotID,dgfID,assetID,procurementMethodType,procurementMethodTypeText,tenderType"
        + ",tenderTypeText,status,statusText,title,description,title_en,description_en,value_amount,minimalStep_amount,normativeMonetaryValuation,expertMonetaryValuation,budgetSpent_amount"
        + ",guarantee_amount,registrationFee_amount,currentTenantGuaranteeFee_amount,value_currency"
        + ",enquiryPeriod_startDate_Date,enquiryPeriod_startDate_Time,enquiryPeriod_endDate_Date,enquiryPeriod_endDate_Time"
        + ",rectificationPeriod_startDate_Date,rectificationPeriod_startDate_Time,rectificationPeriod_endDate_Date,rectificationPeriod_endDate_Time"
        + ",transferPriorityPeriod_startDate_Date,transferPriorityPeriod_startDate_Time,transferPriorityPeriod_endDate_Date,transferPriorityPeriod_endDate_Time"
        + ",clarificationPeriod_startDate_Date,clarificationPeriod_startDate_Time,clarificationPeriod_endDate_Date,clarificationPeriod_endDate_Time"
        + ",questionPeriod_startDate_Date,questionPeriod_startDate_Time,questionPeriod_endDate_Date,questionPeriod_endDate_Time"
        + ",admissionPeriod_startDate_Date,admissionPeriod_startDate_Time,admissionPeriod_endDate_Date,admissionPeriod_endDate_Time"
        + ",tenderPeriod_startDate_Date,tenderPeriod_startDate_Time,tenderPeriod_endDate_Date,tenderPeriod_endDate_Time"
        + ",auctionPeriod_startDate_Date,auctionPeriod_startDate_Time,auctionPeriod_endDate,auctionPeriod_endDate_Date,auctionPeriod_endDate_Time"
        + ",complaintPeriod_startDate_Date,complaintPeriod_endDate_Date,complaintPeriod_startDate_Time,complaintPeriod_endDate_Time"
        + ",qualificationPeriod_startDate_Date,qualificationPeriod_endDate_Date,qualificationPeriod_startDate_Time,qualificationPeriod_endDate_Time"
        + ",procurementMethodRationale,cause,causeDescription"
        + ",cost,tenderPeriod_endDate,PE_name,CP_telephone"
        + ",eligibilityCriteria,previousAuctionId"
        + ",tenderAttempts,items_count,minNumberOfQualifiedBids,auctionParameters_dutchSteps"
        + ",virtualDataRoom"
        + ",auctionType"
        + (tenderType == "rent" ? ",leaseDuration_y,leaseDuration_m,leaseDuration_d" : "");

    if (cdb == 3) {
        if (oFormRecord.title != undefined && oFormRecord.title.uk_UA != undefined)
            oFormRecord.title = oFormRecord.title.uk_UA;

        if (oFormRecord.description != undefined && oFormRecord.description.uk_UA != undefined)
            oFormRecord.description = oFormRecord.description.uk_UA;
    }

    SetFormValues("Position_", set_fields, oFormRecord);

    if (oFormRecord.decision != undefined && tenderType == "dgf") {
        SetFormValues("Position_", "decisionId,decisionDate", oFormRecord.decision);
    }

    OnValueAmountChange('Position', 'minimalStep', 'amount');
    OnValueAmountChange('Position', 'guarantee', 'amount');

    if ((idForm == 0 || strStartsWith(oFormRecord.id, 'web')) && cdb == 2 && tenderType != "rent")
        $("#pn_enter_rectificationPeriod").show();

    if (bankAccount != undefined)
        show_bankAccount();

    slPosition_auctionType_onchange();

    const unacceptableTenderTypes = ['legitimatePropertyLease', 'renewables', 'bankRuptcy', 'smallPrivatization', 'largePrivatization', 'landArrested', 'nadra', 'basicSell-withoutAuction'];

    const matchTenderType = unacceptableTenderTypes.some(type => new RegExp(type).test(tenderType));

    if (!matchTenderType) {
        const options = {
            anItem: idForm == 0 ? oFormRecord : oFormRecord.procuringEntity,
            OrganisationTitle: tenderType.includes('nonperformingLoans') || tenderType.includes('nadra') ? "Інформація про Організатора аукціону" : "Замовник",
            ReadOnly: (
                (tenderType.includes("commercialPropertyLease") && (idForm == 0 || idForm.includes("web") || page_data.canPublic == "true"))
                || (tenderType.includes("bankRuptcy") && (idForm == 0 || idForm.includes("web") || page_data.canPublic === "true" || update_bankRuptcy_info))
            ) ? false : ReadOnly,
            OrganisationEditable: tenderType.includes("bankRuptcy") || tenderType.includes("commercialPropertyLease") ? true : isDebugMode,
            name_prefix: "procuringEntity"
        };

        $("#pnProcuringEntity").Tender_Organization(options);
    }

    var _els = [];

    if (tenderType == "rent" && auctionType == "dgfOtherAssets") {
        if (current_state == "created") {
            if (oFormRecord.tenderPeriod != undefined && oFormRecord.tenderPeriod.endDate != undefined) {
                $("#cb_endDate").prop('checked', 'checked');

                cb_endDate_onchange();
            }
            else
                $("#cb_endDate").prop('checked', false);
        }

        if (oFormRecord.contractTerms != undefined && oFormRecord.contractTerms.leaseTerms != undefined
            && (_els = oFormRecord.contractTerms.leaseTerms.taxHolidays) != undefined
            || !ReadOnly) {
            $("#pn_taxHolidays").show();
            $("#pn_taxHolidays_content").wSHdiv({ Title: "Орендні канікули" });

            if (!ReadOnly || cdb2_public_edit) {
                $("#pn_taxHolidays_control").show();

                SetEditForm($("#pn_Position_leaseDuration"));
            }

            if (_els != undefined && _els.length > 0) {
                for (var j = 0; j < _els.length; j++)
                    Add_taxHoliday($("#pn_taxHolidays_content"), _el = _els[j], _el.id);

                if (_els.length > 1)
                    Renumber_taxHoliday($("#pn_taxHolidays_content"));
            }
        }

        if (oFormRecord.contractTerms != undefined && oFormRecord.contractTerms.leaseTerms != undefined
            && (_els = oFormRecord.contractTerms.leaseTerms.escalationClauses) != undefined
            || !ReadOnly) {
            $("#pn_escalationClauses").show();
            $("#pn_escalationClauses_content").wSHdiv({ Title: "Індексація ціни" });

            if (!ReadOnly || cdb2_public_edit)
                $("#pn_escalationClauses_control").show();

            if (_els != undefined && _els.length > 0) {
                for (var j = 0; j < _els.length; j++)
                    Add_escalationClause($("#pn_escalationClauses_content"), _el = _els[j], _el.id);

                if (_els.length > 1)
                    Renumber_escalationClause($("#pn_escalationClauses_content"));
            }
        }
    }

    _els = [];

    doc_readonly = !isOwn || !(current_state == "created" || current_state == "active.tendering"
        || current_state == "active_tendering" || current_state == "active_rectification")
        || (cdb == 2 || cdb == 3) && !(cdb2_public_edit || bankrupt_edit) && current_state != "created"
        && current_state == "active_tendering"
        || strStartsWith(PMT, "sellout.")
        || current_state == "cancelled" || current_state == "complete" || current_state == "unsuccessful";

    can_add_doc = isOwn && (cdb == 2 || cdb == 3)
        && (current_state == "active.tendering" || current_state == "active_tendering" || current_state == "active_rectification")
        && !strStartsWith(PMT, "sellout.")
        && (oFormRecord.rectificationPeriod == undefined
            || Date.fromISO(oFormRecord.rectificationPeriod.endDate) > new Date()
            || current_state == "active_tendering"
        );

    var awardsStatus = "";

    if ((tenderType.includes("landArrested-withoutAuction") || tenderType.includes("basicSell-withoutAuction")) && isOwn) {
        awardsStatus = oFormRecord.awards?.[0]?.status;

        if ("active_awarded" == current_state && awardsStatus == "pending") {
            can_add_doc = true;
        }
    }

    tender_doc_list = tenderType == "renewables" ? "auction_renewables"
        : tenderType == "timber" ? "auction_timber"
            : tenderType.includes('legitimatePropertyLease') ? "legitimatePropertyLease_auction"
                : tenderType.includes('bankRuptcy') && !tenderType.includes('withoutAuction') ? "bankRuptcy_auction"
                    : tenderType.includes('bankRuptcy') && tenderType.includes('withoutAuction') ? "bankRuptcy_auction_withoutAuction"
                        : tenderType.includes('basicSell-english') || tenderType.includes('basicSell-dutch') || tenderType.includes("simpleSell") ? "basicSell_auction"
                            : tenderType.includes('alienation') ? "basicSell_auction"
                                : tenderType.includes('commercialSell') ? "commercialSell_auction"
                                    : tenderType.includes("landSell") || tenderType.includes("landRental") ? "landRental_auction"
                                        : tenderType.includes("landArrested-english") || tenderType.includes("landArrested-priorityEnglish") ? "landArrested_english_auction"
                                            : tenderType.includes("landArrested-withoutAuction") ? "landArrested_withoutAuction_auction"
                                                : tenderType.includes("basicSell-withoutAuction") ? "basicSell_withoutAuction_auction"
                                                    : tenderType.includes("nonperformingLoans") ? "nonperformingLoans_auction"
                                                        : tenderType.includes('regulationsPropertyLease') ? "regulationsPropertyLease_auction"
                                                            : tenderType.includes('commercialPropertyLease') ? "commercialPropertyLease_auction"
                                                                : tenderType.includes('smallPrivatization') ? "smallPrivatization_auction"
                                                                    : tenderType.includes('largePrivatization') ? "largePrivatization_auction"
                                                                        : tenderType == "dgf" ? "dgf_english_auction"
                                                                            : cdb == 2 ? (is_privatization ? "lot_cdb2" : "auction_other_cdb2")
                                                                                : tenderType == "nadra" ? "auction_nadra"
                                                                                    : tenderType.includes("railwayCargo") ? "auction_railwayCargo"
                                                                                        : PMT == "dgfOtherAssets" ? "auction_other"
                                                                                            : "auction_financial";

    if (oFormRecord.items != undefined || !ReadOnly) {
        $("#pn_items").wSHdiv({ Title: (is_privatization ? "Cклад об’єкту малої приватизації" : "Склад лотів") });

        if ((!ReadOnly || cdb2_public_edit || cdb1_public_edit) && !tenderType.includes('legitimatePropertyLease') && !tenderType.includes("landSell") && !tenderType.includes("landRental") && !tenderType.includes("landArrested")) {
            $("#pn_items_control").show();
        }

        if (oFormRecord.items != undefined) {
            for (var j = 0; j < oFormRecord.items.length; j++)
                if (oFormRecord.items[j].relatedLot == undefined)
                    _els.push(oFormRecord.items[j]);

            $("#pn_itemsContent").text("");
            id_w_item = 0;
            ar_w_item = [];

            if (_els.length > 0) {

                for (var j = 0; j < _els.length; j++) {
                    var _el = _els[j];

                    Add_Tender_item($("#pn_itemsContent"), _el, (_el.id == undefined ? j : _el.id), _el.location, j);

                    if (tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested")) {
                        //  initMap(new_id - 1, _el.location);
                        $("#lew_item_" + j + "_quantity").text("Площа земельної ділянки");

                        if (idForm != 0 && !idForm.includes("web")) {
                            $("#slw_item_" + j + "_unit_code").attr("disabled", "disabled")
                        }
                        set_land_propertis(j, _el.itemProps)
                    }
                    else {
                        $("#mapItem_" + (new_id - 1)).hide();
                    }

                    if (tenderType.indexOf('legitimatePropertyLease') > -1) {
                        changed_itemType(_el.itemType, j);
                        set_rent_propertis(_el.itemType, j, _el);

                        if (strStartsWith(oFormRecord.id, 'web')) {
                            SetViewForm($("#pnWrap_pn_w_item_" + j));

                            let unset_form = "#ew_item_" + j + "_quantity,#registrationStatus_" + j + ",#registrationID_" + j + ",#registrationDate_" + j + ",#registrationDate_Time_" + j;

                            unSetViewForm(unset_form);
                        }

                        if (_el.itemType == "realEstate") {
                            $("#lew_item_" + j + "_quantity").text("Площа об'єкта, що здається в оренду");
                            if (_el.reProps != undefined) {
                                $("#ew_item_" + j + "_quantity").val(_el.reProps.totalObjectArea).attr("disabled", "disabled");
                            }
                        } else if (_el.itemType == "otherProperty") {
                            $("#slw_item_" + j + "_unit_code").show();
                            $("#tslw_item_" + j + "_unit_code").hide();
                        }
                    }
                }

                Renumber_Tender_item($("#pn_itemsContent"));
            }
        }
    }

    _els = [];

    (_pn_trd_doc_place = $("#pn_trd_doc_place")).append(get_document_container(""));

    if (idForm != "0") {
        _els = [];

        if (oFormRecord.documents != undefined)
            for (var j = 0; j < oFormRecord.documents.length; j++)
                if (oFormRecord.documents[j].documentOf == "tender" || oFormRecord.documents[j].documentOf == "auction" || oFormRecord.documents[j].documentOf == "asset" || oFormRecord.documents[j].documentOf == "announcement" || oFormRecord.documents[j].documentOf == "item"
                    || oFormRecord.documents[j].documentOf == "lot" || oFormRecord.documents[j].documentOf == undefined)
                    _els.push(oFormRecord.documents[j]);

        if (page_data.status === 'deleted') {
            doc_readonly = true;
        }

        if (_els.length > 0 || !doc_readonly || can_add_doc) {
            ShowDocumentsRecordsTitle("", _pn_trd_doc_place, "Документи аукціону", doc_readonly && !can_add_doc
                , tender_doc_list, "auction", undefined, cdb == 3 && !strStartsWith(oFormRecord.id, 'web') && _els.length > 0, (!strStartsWith(oFormRecord.id, 'web') && cdb == 3 && isLogined && _els.length > 0));


            if (_els.length > 0) {
                ShowDocumentsRecords("", _pn_trd_doc_place, tender_doc_list, "auction", "", _els, doc_readonly && !can_add_doc);
                ShowDocumentsIllustrations(_els);
            }

            let to_exclude = (tenderType == "renewables" ? ",x_dgfAssetFamiliarization,x_verificationAct," : (oFormRecord.isPerishable != undefined && oFormRecord.isPerishable ? ",clarifications," : ""));

            if (!doc_readonly || can_add_doc)
                set_btn_documents_add("", _pn_trd_doc_place, tender_doc_list, "auction", ""
                    , undefined, undefined, to_exclude);
        }

        if (isOwn && (cdb == 2 && current_state == "active.tendering" || current_state == "active_rectification"
            || ((tenderType.includes("basicSell") || tenderType.includes("alienation")
                || tenderType.includes("commercialSell") || tenderType.includes("bankRuptcy")
                || tenderType.includes("simpleSell") || tenderType.includes("regulationsPropertyLease")
                || tenderType.includes("commercialPropertyLease") || tenderType.includes("nonperformingLoans"))
                && current_state == "active_tendering"))
            && !strStartsWith(PMT, "sellout.") && full_data.canPublic != 'true'
            && ((oFormRecord.rectificationPeriod == undefined
                || Date.fromISO(oFormRecord.rectificationPeriod.endDate) > new Date()))) {

            $("[data-atid='editButtonLast']").show();

            if (tenderType == "nadra" || tenderType.includes("simpleSell")) {
                $("[data-atid='editButtonLast']").click(function () { jQuery.getJSON("DataHandler.ashx?CN=" + vCN + "&CommandName=jAllowsEditProcedure&id=" + idForm, HandleRequest); });
            } else {
                set_element_documents_add($("[data-atid='editButtonLast']"), _pn_trd_doc_place, "auction_clarifications", "auction", idForm);
            }
        } else {
            cbd_3_public_edit = (isOwn == true && page_data.canPublic == "true");
            if (cdb != 2
                && !tenderType.includes("basicSell")
                && !tenderType.includes("alienation")
                && !tenderType.includes("commercialSell")
                && !tenderType.includes("bankRuptcy")
                && !tenderType.includes("regulationsPropertyLease")
                && !tenderType.includes("commercialPropertyLease")
                && !tenderType.includes("smallPrivatization")
                && !tenderType.includes("largePrivatization")
                && !tenderType.includes("nonperformingLoans")) {
                rent_rectification = true;
            }
        }

        if (current_state == "active_awarded" && full_data.canPublic != 'true' && awardsStatus == "pending") {
            $("[data-atid='editButtonLast']")
                .show()
                .click(function () { jQuery.getJSON("DataHandler.ashx?CN=" + vCN + "&CommandName=jAllowsEditProcedure&id=" + idForm, HandleRequest); });
        }
    }

    ShowOnState();

    if ((cdb == 2 || cdb == 3) && (full_data.canSave == 'true' || full_data.canPublic == 'true')) {
        jQuery.getJSON("Js/address_optional/cpv_codes_item_address_optional.json?v=" + version, function (data) {
            d_check_cpv = data;
        }, "json");
        jQuery.getJSON("Js/address_optional/cav_v2_codes_item_address_optional.json?v=" + version, function (data) {
            d_check_cav = data;
        }, "json");
    }

    if (isPlaceTestMode)
        $('.is_debug').each(function () {
            $(this).show();
        });

    $("#pn_static_items").hide();

    if (!tenderType.includes("landSell") && !tenderType.includes("landRental") && !tenderType.includes("landArrested") 
        && oFormRecord.items != undefined && oFormRecord.items[0].classification != undefined 
        && oFormRecord.items[0].classification.id.substr(0, 4) == '0341') { 
        $("#pn_minNumberOfQualifiedBids").show(); 
        $(".go_your_price").hide(); 
    } 

    if (oFormRecord.status == "active.tendering" || oFormRecord.status == "active_tendering") {
        $('.tlg_link_YYB').show();
    }

    if (page_data.isOwn == "false" && idForm != 0) {
        $('.tender_link').show();
        if (!(tenderType.indexOf('legitimatePropertyLease') > -1) && oFormRecord.procuringEntity.identifier.id == "37536031") {
            $('.nadra_link').show();
        }
        $('.tlg_link').attr("style", "display:flex");
    } else {
        $('.tlg_link').hide();
    }

    if (cdb == 3 && full_data.canSave != 'true' && full_data.canPublic == 'true') {
        if (!tenderType.includes("bankRuptcy-dutch")) {
            SetViewForm($("#pn_auctionParameters_dutchSteps"));
        }
    }

    if (tenderType == "timber" && oFormRecord.minNumberOfQualifiedBids == undefined) {
        $("#tslPosition_minNumberOfQualifiedBids").text("2");
        $("#pn_minNumberOfQualifiedBids").show();
    }

    if (cdb3_dgf) {
        get_dgf();
    }

    if (isOwn) {
        $(".only_customer").show();
    }

    if (tenderType.indexOf('legitimatePropertyLease') > -1 && !not_copy) {
        if (idForm != 0 || oFormRecord.tenderAttempts == 1) {
            if (oFormRecord.bankAccounts != undefined) {
                set_bankAccounts(oFormRecord.bankAccounts);
            }
        } else {
            copy_object(registryRecord);
        }

        if (!cbd_3_public_edit && idForm != 0) {
            SetViewForm($("#pn_items"));
            SetViewForm($("#pn_bankAccounts"));
        } else {
            $(".button_bankAccounts").show();
        }

        if (idForm != 0 && oFormRecord.leaseRules != undefined && oFormRecord.leaseRules.intendedUse != undefined && oFormRecord.leaseRules.intendedUse.length > 1) {
            let intendedUse_text = "";
            for (var i = 0; i < oFormRecord.leaseRules.intendedUse.length; i++) {
                let intendedUse_item = oFormRecord.leaseRules.intendedUse[i];
                intendedUse_text += (intendedUse_text == "" ? "" : "; ") + d_intendedUse[intendedUse_item].uk_UA;
            }
            $("#tintendedUse_3").text(intendedUse_text);
        }

        if (priority) {
            $("#slPosition_auctionType").val("priorityEnglish");
            $("#pn_currentTenantGuaranteeFee").show();
        }
    }

    if ((tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested")) && (full_data.canPublic != "true" && full_data.canSave != "true")) {
        SetViewForm($("#pn_items"));
    }

    if (idForm != 0 && (tenderType.includes("landSell") || tenderType.includes("landRental")) && !isOwn) {
        $("#tlg-zemlya").show();
    }

    if (idForm != 0 && !strStartsWith(oFormRecord.id, 'web') && tenderType == "bankrupt" && (oFormRecord.rectificationPeriod == undefined
        || Date.fromISO(oFormRecord.rectificationPeriod.endDate) > new Date())) {
        $("#ePosition_dgfID").attr("disabled", "disabled")
        $("#ePosition_title").attr("disabled", "disabled")
        $("#ePosition_description").attr("disabled", "disabled")
        $("#slPosition_auctionType").attr("disabled", "disabled")
        SetViewForm($('.pn_input_auction_start'))
    }

    if ((tenderType_for_additionalClassification_cpvs.some(type => tenderType.includes(type)) || tenderType_for_additionalClassification_cvzu.some(type => tenderType.includes(type))
        || tenderType_for_additionalClassification_kvtspz.some(type => tenderType.includes(type)))
        && idForm != 0 && !strStartsWith(idForm, 'web')) {
        set_additionalClassifications_text();
    }

    if (tenderType.includes("commercialSell") && idForm == 0) {
        $("#slPosition_minNumberOfQualifiedBids").val("2");
    }

    const validStatuses = ["active_qualification", "active_awarded", "complete", "unsuccessful", "cancelled"];
    const isLandArrestedWithoutAuction = (tenderType.includes("landArrested-withoutAuction") || tenderType.includes("basicSell-withoutAuction"))
        && current_state == "active_awarded" && full_data.canPublic == "true";

    if (validStatuses.includes(oFormRecord.status) && !update_bankRuptcy_info && !isLandArrestedWithoutAuction) {
        SetViewForm($("#pn_bankAccounts"));
    }

    if (oFormRecord.valueAddedTaxCharged != undefined && oFormRecord.valueAddedTaxCharged)
        $('#cbPosition_valueAddedTaxCharged').prop('checked', 'checked');

    if (tenderType.includes("landArrested") && oFormRecord.valueAddedTaxCharged != undefined) {
        $("#valueAddedTaxCharged").show();
        $("#cbPosition_valueAddedTaxCharged").attr("disabled", "disabled");
    }
}

function Init() {
    cdb = page_data.cdb;

    oFormRecord = page_data.row.data;

    if (oFormRecord._id != undefined)
        oFormRecord.id = oFormRecord._id;

    //temp nadra 
    if (member_type == 911 && oFormRecord.id == 0)
        cdb = (nadra_cdb == 3 ? 3 : 2);

    if (oFormRecord.auctionId != undefined)
        oFormRecord.auctionID = oFormRecord.auctionId;

    if (cdb == 3) {
        oFormRecord.procurementMethodType = oFormRecord.sellingMethod;

        if ((oFormRecord.id != 0 && !tenderType.includes("subsoil") && !tenderType.includes("dgf") && !tenderType.includes("bankRuptcy"))
            || (oFormRecord.id == 0 && member_type != 911))
            $("#pn_registrationFee").show();
    }

    if (cdb == 1) {
        $('.cdb1').show();
        $('.cdb2').hide();
    }
    else if (cdb == 2 || cdb == 3) {
        if (oFormRecord.procurementMethodType != undefined && strStartsWith(oFormRecord.procurementMethodType, "sellout")) {
            is_privatization = true;

            oFormRecord.assetID = page_data.assetID;

            tender_doc_list = "lot_cdb2";

            $('.non_privatization').hide();
            $('.privatization').show();
        }
        else {
            if (oFormRecord.id != 0) {
                get_tenderType();
            }

            tender_doc_list = "auction_other_cdb2";
        }

        $('.cdb1').hide();
        $('.cdb2').show();
    }

    FormTips = $("#ValidateTips");

    if (oFormRecord.id == 0) {
        set_sellingMethod(true);
    }

    if (tenderType.includes("legitimatePropertyLease")) {
        rent_rectification = (page_data.canPublic == "true" && oFormRecord.status == "active_rectification");
        $("#slPosition_tenderType").val(tenderType)
    }

    if (cdb == 3 && oFormRecord.sellingMethod != undefined && oFormRecord.sellingMethod.indexOf('dgf') > -1) {
        cdb3_dgf = true;
    }

    if (cdb3_dgf) {
        tenderType = 'dgf'
        get_dgf_dics();
    }

    if (cdb == 3) {
        oFormRecord.procurementMethodType = oFormRecord.sellingMethod;
        if (!cdb3_dgf && !tenderType.includes("bankRuptcy")) {
            $("#pn_registrationFee").show();
        }
    }

    if (cdb == 1) {
        SetDicSearchOption(d_dict, $("#slPosition_procurementMethodType"), "methodType", true, "Виберіть значення");
        SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_fgv", true, "Виберіть значення");

        tenderType = "sell";
        $("#slPosition_tenderType").val(tenderType);
        if (oFormRecord.id == 0)
            slPosition_tenderType_onchange();
    }
    else {
        SetDicSearchOption(d_dict, $("#slPosition_minNumberOfQualifiedBids"), "minNumberOfQualifiedBids", true, "");
        SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts", true, "Виберіть значення");
        checkCustomsEDRPOU(page_data.row.data.PE_identifier_id);
        if (is_privatization) {
            SetDicSearchOption(d_dict, $("#slPosition_procurementMethodType"), "privatization_PMT_tenderAttempts", true);
            $("#slPosition_procurementMethodType").val("privatization_PMT_" + oFormRecord.tenderAttempts);
        }
        else {
            if (tenderType == "dgf") {
                SetDicSearchOption(d_dict, $("#slPosition_procurementMethodType"), "methodType_dgf", true, "Виберіть значення");
            } else {
                SetDicSearchOption(d_dict, $("#slPosition_procurementMethodType"), "methodType", true, "Виберіть значення");
            }

            if (cdb == 3)
                set_auctionType();
            else
                SetDicSearchOption(d_dict, $("#slPosition_auctionType"), "auctionType_cdb2", true, "Виберіть значення", ",reporting,");

            $("#pn_auctionType").show();

            if (idForm != 0) {
                auctionType = (cdb == 2 ? (oFormRecord.procurementMethodType == "appraisal.insider" ? "appraisal.insider" : "dgfOtherAssets")
                    : oFormRecord.sellingMethod.indexOf("-multiAwards") > -1 ? "multiAwards"
                        : oFormRecord.sellingMethod.indexOf("-dutch") > -1 ? "dutch"
                            : "english");

                if (tenderType == "bankrupt")
                    oFormRecord.auctionType = auctionType + "_" + oFormRecord.tenderAttempts;
                else
                    oFormRecord.auctionType = auctionType;
            }

            PMT_cdb2 = oFormRecord.procurementMethodType;

            if (PMT != "dgf") {
                oFormRecord.procurementMethodType = "dgfOtherAssets";
            }

            if (tenderType == "timber") {
                $("#slPosition_auctionType").val("dgfOtherAssets");
            }

            if (tenderType == "bankrupt") {
                $("#pn_tenderAttempts").hide();

                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_bankrupt", true, "Виберіть значення");
                SetDicSearchOption(d_dict, $("#slPosition_auctionType"), "auctionType_bankrupt", "NONE", "Виберіть значення");
            }
            else if (auctionType == "appraisal.insider")
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_fgv", true, "Виберіть значення");
            else if (cdb == 2 || cdb == 3 && !tenderType.includes('legitimatePropertyLease') && !tenderType.includes('alienation'))
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_10", true, "Виберіть значення");
            else if (tenderType.includes('legitimatePropertyLease'))
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_3", true, "Виберіть значення");
            else if (tenderType.includes('alienation')) {
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts_3", true, "Виберіть значення");
                $("#slPosition_tenderAttempts option[value='3']").remove();
            } else
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts"), "tenderAttempts", true, "Виберіть значення");

            if (oFormRecord.id != 0 && tenderType == "dgf") {
                dgf_classification_methodType(oFormRecord.items[0].classification.id);
            } else {
                $("#slPosition_procurementMethodType").val(oFormRecord.procurementMethodType);
            }

            if (oFormRecord.id == 0)
                slPosition_procurementMethodType_onchange();
        }
    }

    SetEditFormFields($("#pnPositionFormData"));

    $("[data-atid='btnSaveLast']").click(function () { DlgSend(false); });

    $("#pnMainParamsContent").wSHdiv({ Title: "Основні параметри" });
}

function DlgSend(_withPublic) {

    withPublic = _withPublic;
    bValid = true;
    FormTips = $("#ValidateTips");
    updateTips("", "");

    ClearError();

    dMinDate = sISO2date("19000101");
    dMaxDate = Today();
    dMaxDate.setYear(dMaxDate.getFullYear() + 5);

    data = {};
    if (tenderType != "dgf") {
        if ($("#slPosition_procurementMethodType").val() == "all") {
            updateTips("Не встановлено поле \"Оголошення аукціону з продажу\"", "Y");
            return false;
        }

        if (!checkNonSelect($("#slPosition_procurementMethodType"), "Тип аукціону"))
            return;
    }
    on_first_publc = !_withPublic || oFormRecord.id == 0 || strStartsWith(oFormRecord.id, 'web');

    if (on_first_publc) {
        if (cdb != "3")
            data.procurementMethodType = lastCheckValue;

        if (tenderType == "rent" && auctionType == "dgfOtherAssets")
            data.procurementMethodType = "propertyLease";
        else if (auctionType == "appraisal.insider" || tenderType == "bankrupt")
            data.procurementMethodType = auctionType;
        else if (tenderType == "renewables")
            data.sellingMethod = tenderType;
        else if (cdb == "3" && tenderType == "nadra")
            data.sellingMethod = "subsoil-" + auctionType;
        else if (tenderType == "timber")
            data.sellingMethod = "timber-english";
        else
            data.sellingMethod = tenderType;

        if (oFormRecord.isPerishable == undefined && !oFormRecord.isPerishable && !$("#isPerishable").is(':checked') && !tenderType.includes("withoutAuction") && !not_copy) {
            data.auctionPeriod = {};

            if (!withPublic && $("#dtpPosition_auctionPeriod_startDate_Date").val() == "") {
                data.auctionPeriod.startDate = getISO_datetime(Today(), "11:00");
            } else {
                if (!checkDate($("#dtpPosition_auctionPeriod_startDate_Date"), "", dMinDate, dMaxDate)) return;
                _date = lastCheckValue;

                if (cdb != 3
                    || $("#r_auction_MethodDetails_fast").prop('checked')
                    || $("#r_auction_MethodDetails_fast_manual").prop('checked')) {
                    if (!checkTime($("#ePosition_auctionPeriod_startDate_Time"))) return;

                    data.auctionPeriod.startDate = getISO_datetime(_date, lastCheckValue, cdb == 3);
                }
                else
                    data.auctionPeriod.startDate = Date2PHP(lastCheckValue);
            }
        }
    }

    if (tenderType == "dgf") {
        if ($("#ePosition_virtualDataRoom").val() != "") {
            data.virtualDataRoom = $("#ePosition_virtualDataRoom").val();
        }
        if ($('#ePosition_eligibilityCriteria').val() != "all") {
            data.eligibilityCriteria = $('#ePosition_eligibilityCriteria').val();
        }
    }

    if (cdb == "3" && (tenderType == "nadra" || tenderType == "timber" || tenderType.includes('legitimatePropertyLease') || tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested") || tenderType.includes("basicSell") || tenderType.includes("alienation") || tenderType.includes("commercialSell") || tenderType.includes("bankRuptcy") || tenderType.includes("regulationsPropertyLease") || tenderType.includes("commercialPropertyLease") || tenderType.includes("nonperformingLoans")) && $("[data-atid='tenderAttempts']").val() != 1) {
        if (!checkLength($("#ePosition_previousAuctionId"), "", 3, 50)) return;
        data.previousAuctionId = lastCheckValue;

        if (tenderType == "nadra" && !checkRegexp($("#ePosition_previousAuctionId")
            , /^([a-zA-Z]{3}[0-9]{3}-[a-zA-Z]{2}-[0-9]{8}-[0-9]{5}|[a-zA-Z]{2}-[a-zA-Z]{2}-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}-[0-9]{1})$/
            , " SUE000-UA-YYYYMMMM-00000 або SUD000-UA-YYYYMMMM-00000 або UA-PS-YYYY-MM-DD-000000-0")) return;

        if (tenderType == "timber" && !checkRegexp($("#ePosition_previousAuctionId")
            , /^([a-zA-Z]{3}[0-9]{3}-[a-zA-Z]{2}-[0-9]{8}-[0-9]{5}|[a-zA-Z]{2}-[a-zA-Z]{2}-[0-9]{4}-[0-9]{2}-[0-9]{2}-[0-9]{6}-[0-9]{1})$/
            , " TIE000-UA-YYYYMMDD-00000 або UA-PS-YYYY-MM-DD-000000-0")) return;
    }

    if ((tenderType != "nadra" && tenderType != "simpleSell-withoutAuction") || cdb != 3) {
        if (!checkLength($("#ePosition_dgfID"), "", (tenderType.includes("landArrested-withoutAuction") ? 0 : 3), 50)) return;

        if (cdb == 3)
            data.lotId = lastCheckValue;
        else if (cdb == 2 && (isPlaceTestMode || auctionType == "appraisal.insider" || tenderType == "rent"))
            data.lotIdentifier = lastCheckValue;
        else
            data.dgfID = lastCheckValue;
    }

    if (!checkLength($("#ePosition_title"), "", 3, 10000)) return;
    data.title = lastCheckValue;

    if (!checkLength($("#ePosition_description"), "", cdb == 3 ? 3 : 0, 30000)) return;
    data.description = lastCheckValue;

    if (PMT != "dgfInsider" && tenderType != "simpleSell-withoutAuction") {
        if ($("#slPosition_tenderAttempts").val() == "all") {
            updateTips("Не встановлено поле \"Лоти виставляються\"", "Y");
            return false;
        }

        if ($("#slPosition_tenderAttempts").val() != "")
            data.tenderAttempts = $("#slPosition_tenderAttempts").val();
        else {
            if (withPublic && !strEndsWith(data.description, "Торги проводяться повторно"))
                data.description += (data.description.length > 0 ? " " : "") + "Торги проводяться повторно";
        }
    }

    data.value = {};
    data.value.currency = tenderType == "renewables" ? "eurocent" : "UAH";

    if (!checkfloat($("#ePosition_value_amount"), 0, 1000000000000)) return;
    data.value.amount = lastCheckValue;
    tender_value = data.value.amount;

    if ($('#cbPosition_value_valueAddedTaxIncluded').prop('checked'))
        data.value.valueAddedTaxIncluded = 'True';
    else {
        data.value.valueAddedTaxIncluded = "False";
    }

    const acceptableTenderTypes = ['legitimatePropertyLease', 'bankRuptcy', 'nonperformingLoans'];

    const matchTenderType = acceptableTenderTypes.some(type => new RegExp(type).test(tenderType));

    if (matchTenderType) {
        data.valueAddedTaxCharged = $('#cbPosition_valueAddedTaxCharged').prop('checked');
    }

    if (tenderType.includes('bankRuptcy')) {
        if ($('#cbPosition_isTaxInvoiceProvided').prop('checked')) {
            data.isTaxInvoiceProvided = true
        } else {
            data.isTaxInvoiceProvided = false
        }
    }

    if (data.procurementMethodType != "dgfInsider" && data.procurementMethodType != "appraisal.insider"
        && tenderType != "renewables" && auctionType != "dutch" && !tenderType.includes("dutch") && !tenderType.includes("withoutAuction")) {
        data.minimalStep = {};

        /* 
        if (!checkfloat($("#ePosition_minimalStep_amount") 
            , (tenderType == "nadra" ? 0.01 : Math.round(data.value.amount * 1) / 100) 
            , (cdb == 1 ? data.value.amount : (tenderType == "nadra" ? Math.round(data.value.amount * 60) / 100: Math.round(data.value.amount * 10) / 100))) 
            && !isDebugMode) return; 
        data.minimalStep.amount = lastCheckValue; 
        */

        if (tenderType == "nadra" || tenderType == "legitimatePropertyLease-english" || tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested-english") || tenderType.includes("landArrested-priorityEnglish")) {
            if (!checkfloat($("#ePosition_minimalStep_amount"), 0.01, 1000000000000000)) return false;
            data.minimalStep.amount = lastCheckValue;
        } else {
            if (!checkfloat($("#ePosition_minimalStep_amount"), Math.round(data.value.amount * 1) / 100, (cdb == 1 ? data.value.amount : Math.round(data.value.amount * 10) / 100)) && !isDebugMode)
                return;
            data.minimalStep.amount = lastCheckValue;
        }

        if (cdb == 3)
            data.minimalStep.currency = "UAH";
        else
            data.minimalStep.valueAddedTaxIncluded = data.value.valueAddedTaxIncluded;
    }

    if (!tenderType.includes("bankRuptcy-withoutAuction") && !tenderType.includes("landArrested-withoutAuction") && !tenderType.includes("basicSell-withoutAuction")) {
        data.guarantee = {};
        if (tenderType != "nadra" && tenderType != "renewables" && tenderType != "rent" && !tenderType.includes('legitimatePropertyLease') && !tenderType.includes("landSell") && !tenderType.includes("landRental") && !tenderType.includes("landArrested") && !tenderType.includes("simpleSell") && !tenderType.includes("regulationsPropertyLease")) {
            if (!checkfloat($("#ePosition_guarantee_amount")
                , (cdb == 1 ? Math.round(data.value.amount * 5) / 100 : Math.round(data.value.amount * 2) / 100)
                , (cdb == 1 ? data.value.amount : Math.round(data.value.amount * 20) / 100))
                && !isDebugMode) return;
            data.guarantee.amount = lastCheckValue;
        } else if (tenderType.includes('legitimatePropertyLease') || tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested") || tenderType.includes("simpleSell")) {
            if (!checkfloat($("#ePosition_guarantee_amount"), 0, 1000000000000000)) return false;
            data.guarantee.amount = lastCheckValue;
        } else {
            if (!checkfloat($("#ePosition_guarantee_amount"), 0.0000000001, 1000000000000000)) return false;
            data.guarantee.amount = lastCheckValue;
        }

        if (tenderType != "nadra") {
            if ($("#ePosition_guarantee_amount").val() == "")
                data.guarantee.amount = data.value.amount * 0.05;
        }

        if (tenderType == "renewables")
            data.guarantee.currency = "EUR";
        else
            data.guarantee.currency = data.value.currency;

        if (false && tenderType != "renewables") {
            data.guarantee.valueAddedTaxIncluded = data.value.valueAddedTaxIncluded;
        }
    }

    if (!tenderType.includes("landArrested-withoutAuction") && !tenderType.includes("basicSell-withoutAuction")) {
        if (tenderType == "bankrupt" && data.procurementMethodType == "appraisal.insider") {
            data.registrationFee = { amount: 0 };
        } else if (tenderType.includes("legitimatePropertyLease") || tenderType.includes("land") || tenderType.includes("basicSell") || tenderType.includes("alienation") || tenderType.includes("commercialSell") || tenderType.includes("regulationsPropertyLease") || tenderType.includes("commercialPropertyLease")) {
            if (!checkfloat($("#ePosition_registrationFee_amount"), 0.01, 1000000000000000)) return;
            data.registrationFee = { amount: lastCheckValue, currency: "UAH" };
        } else if (data.procurementMethodType == "appraisal.insider" || cdb == 3 && on_first_publc && !cdb3_dgf && tenderType != "nadra" && tenderType != "renewables" && !tenderType.includes("bankRuptcy") && !tenderType.includes("simpleSell-withoutAuction") && !tenderType.includes("nonperformingLoans")) {
            if (!checkfloat($("#ePosition_registrationFee_amount"), 0.0, data.value.amount) && !isDebugMode) return;

            data.registrationFee = { amount: lastCheckValue, currency: "UAH" };
        }
    }
    if (tenderType != "bankrupt" && tenderType != "nadra" && tenderType != "rent" && data.procurementMethodType == "appraisal.insider") {
        var bankAccount = get_bankAccount();

        if (bankAccount != undefined)
            data.bankAccount = bankAccount;
    }

    if (priority && !tenderType.includes("landSell-priorityEnglish") && !tenderType.includes("landArrested-priorityEnglish") && prev_tenderType != "landArrested-priorityEnglish") {
        data.currentTenantGuaranteeFee = {};
        if (!checkfloat($("#ePosition_currentTenantGuaranteeFee_amount"), 0.0000000001, $("#ePosition_value_amount").val())) return false;
        data.currentTenantGuaranteeFee.amount = lastCheckValue;
        data.currentTenantGuaranteeFee.currency = "UAH";
    }

    if ((idForm == 0 || strStartsWith(oFormRecord.id, 'web')) && cdb != 3 && $("#dtpPosition_rectificationPeriod_endDate_Date").val() != "") {
        data.rectificationPeriod = {};
        if (!checkDate($("#dtpPosition_rectificationPeriod_endDate_Date"), "", dMinDate, dMaxDate)) return;
        _date = lastCheckValue;

        if (!checkTime($("#ePosition_rectificationPeriod_endDate_Time"))) return;
        data.rectificationPeriod.endDate = getISO_datetime(_date, lastCheckValue);
    }

    if (cdb3_dgf) {
        data.decision = {};
        if (!checkLength($("#ePosition_decisionId"), "", 1, 100)) return;
        data.decision.decisionId = lastCheckValue;

        if (!checkDate($("#dtpPosition_decisionDate"), "", dMinDate, dMaxDate)) return;

        data.decision.decisionDate = getISO_datetime(lastCheckValue, "00:00");
    }

    if (tenderType == "bankrupt" && auctionType == "dgfOtherAssets") {
        data.minNumberOfQualifiedBids = 1;
    }

    if (tenderType == 'comercial' && auctionType != 'appraisal.insider') {
        data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
    }

    if (tenderType == "rent" && auctionType == "dgfOtherAssets") {

        if ($("#cb_endDate").prop('checked'))
            data.tenderPeriod = { endDate: data.auctionPeriod.startDate };

        if ($("#slPosition_minNumberOfQualifiedBids").val() != "")
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();

        if (!checkInt($("#ePosition_leaseDuration_y"), 0, 50)) return;
        leaseDuration_y = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_m"), 0, 12)) return;
        leaseDuration_m = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_d"), 0, 31)) return;
        leaseDuration_d = lastCheckValue;

        leaseDuration = "P" + leaseDuration_y + "Y" + leaseDuration_m + "M" + leaseDuration_d + "D";

        data.contractTerms = { type: "lease", leaseTerms: { escalationClauses: [], taxHolidays: [], leaseDuration: leaseDuration } };

        if (ar_w_escalationClause.length > 0) {
            var _els = [];

            for (var j = 0; j < ar_w_escalationClause.length; j++) {
                var el = ar_w_escalationClause[j].Save();

                if (!bValid)
                    return;
                _els.push(el);
            }

            data.contractTerms.leaseTerms.escalationClauses = _els;
        }

        if (ar_w_taxHoliday.length > 0) {
            var _els = [];

            for (var j = 0; j < ar_w_taxHoliday.length; j++) {
                var el = ar_w_taxHoliday[j].Save();

                if (!bValid)
                    return;
                _els.push(el);
            }

            data.contractTerms.leaseTerms.taxHolidays = _els;
        }
    }

    if (auctionType == "dgfOtherAssets" && $("#slPosition_minNumberOfQualifiedBids").val() != "") {
        data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
    }

    if (tenderType == "nadra" && cdb == 2)
        dutchSteps = 90;

    if (cdb != 3 && (data.procurementMethodType == "appraisal.insider" || auctionType == "dutch" && on_first_publc)) {
        if (!checkInt($("#ePosition_auctionParameters_dutchSteps"), 1, dutchSteps)) return;
        if (auctionType == "dutch")
            data.dutchStep = { dutchStepQuantity: lastCheckValue };
        else
            data.auctionParameters = { dutchSteps: lastCheckValue };
    }

    const acceptableTenderTypesDutchStep = [
        "legitimatePropertyLease-dutch",
        "basicSell-dutch",
        "commercialSell-dutch",
        "regulationsPropertyLease-dutch",
        "commercialPropertyLease-dutch",
        "nonperformingLoans-dutch",
        "bankRuptcy-dutch"
    ];

    const matchTenderTypeDutchStep = acceptableTenderTypesDutchStep.some(type => new RegExp(type).test(tenderType)) || (tenderType == 'nadra' && auctionType == 'dutch');

    if (matchTenderTypeDutchStep) {
        data.dutchStep = {};

        let dutchStepQuantity = 99;

        if (tenderType.includes("commercialSell-dutch") || tenderType.includes("nonperformingLoans-dutch")) {
            if ($("#dutchStep_dutchStepPercent").val() != "") {
                if ($("#dutchStep_dutchStepPercent").val().replace(",", ".") != 0.1 && $("#dutchStep_dutchStepPercent").val().replace(",", ".") != 1) {
                    updateTips('Значення поля "Відсоток зниження" має бути 0.1 або 1', "Y");
                    bValid = false;
                } else {
                    data.dutchStep.dutchStepPercent = $("#dutchStep_dutchStepPercent").val().replace(",", ".");
                }
            }

            if (data.dutchStep.dutchStepPercent != undefined && data.dutchStep.dutchStepPercent == 0.1) {
                dutchStepQuantity = 999;
            } else if (tenderType.includes("nonperformingLoans-dutch") && data.dutchStep.dutchStepPercent != undefined && data.dutchStep.dutchStepPercent == 1) {
                dutchStepQuantity = 99;
            }
        }

        if (!checkInt($("#dutchStep_dutchStepQuantity"), 1, dutchStepQuantity)) return;
        data.dutchStep.dutchStepQuantity = lastCheckValue;

        if (tenderType == "nadra" && idForm != 0 && !strStartsWith(oFormRecord.id, 'web')) {
            delete data.dutchStep;
        }
    }

    if (tenderType.includes('landArrested-priorityEnglish') || tenderType.includes('landSell-priorityEnglish')) {
        data.numberOfCurrentTenants = $("#numberOfCurrentTenants").val();
    }

    if (!bValid)
        return;

    if (!(tenderType.indexOf('legitimatePropertyLease') > -1)) {
        sellingEntity = $("#pnProcuringEntity").Tender_Organization("Save");

        if (cdb == 3)
            data.sellingEntity = sellingEntity;
        else
            data.procuringEntity = sellingEntity;
    }

    if (!bValid)
        return;

    if (ar_w_item.length > 0) {
        var _els = [];

        for (var j = 0; j < ar_w_item.length; j++) {
            var el = ar_w_item[j].Save();

            if (!bValid)
                return;
            _els.push(el);
        }

        data.items = _els;
    }
    else {
        updateTips("Додайте хоча б один актив", "Y");
        return false;
    }

    if (tenderType == "renewables") {
        if (!checkfloat($("#ePosition_guarantee_amount"), 0.9 * 5, 1.1 * 5)) return false;
    }

    if (tenderType == "timber" && cdb == "2") {
        data.minNumberOfQualifiedBids = 1;

        if (withPublic && $(".documentType:contains('technicalSpecifications')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Лоти аукціону'", "Y");

            return;
        }
    }

    if (tenderType == "dgf" && withPublic && $(".documentType:contains('technicalSpecifications')", "#pn_trd_doc_place").length == 0) {
        updateTips("Додайте документ 'Технічні специфікації'", "Y");

        return;
    }

    if (isPlaceTestMode && on_first_publc) {
        var add_test_bids = false;

        if (cdb == 3) {
            if ($("#r_auction_MethodDetails_fast").prop('checked'))
                data.sellingMethod += "-fast";
            else if ($("#r_auction_MethodDetails_fast_manual").prop('checked'))
                data.sellingMethod += "-fast-manual";
            else if ($("#r_auction_MethodDetails_initial_auction").prop('checked')) {
                data.sellingMethod += "-initial-auction";
                add_test_bids = true;
            }
            else if ($("#r_auction_MethodDetails_initial_auction_manual").prop('checked')) {
                data.sellingMethod += "-initial-auction-manual";
                add_test_bids = true;
            }
            else if ($("#r_auction_MethodDetails_initial_qualification").prop('checked')) {
                data.sellingMethod += "-initial-qualification";
                add_test_bids = true;
            }
        }
        else if ($('#cb_is_quick').prop('checked')) {
            data.procurementMethodDetails = 'quick, accelerator=' + $("#ePosition_quick_value").val();

            if ($("#r_auction_MethodDetails_fast_forward").prop('checked'))
                data.submissionMethodDetails = "quick(mode:fast-forward)";
            else if ($("#r_auction_MethodDetails_no_auction").prop('checked'))
                data.submissionMethodDetails = "quick(mode:no-auction)";
            else
                data.submissionMethodDetails = "quick";

            //        data.submissionMethodDetails = 'quick';// (cdb == 1 && PMT != "dgfInsider" ? 'quick(mode:fast-forward)' : 'quick');
        }
        if (add_test_bids) {
            if (cdb == "3") {
                data.bids = get_TestBids(data.value.amount, data.items[0].quantity, data.value.currency);
            }
        }
    }


    if (cdb == 3) {
        data.title = { uk_UA: data.title };
        data.description = { uk_UA: data.description };

        switch (tenderType) {
            case "renewables": if (!get_renewables()) return;
                break;
            case "nadra": if (!get_nadra()) return;
                break;
            case "timber": if (!get_timber()) return;
                break;
        }
    }

    if (cdb3_dgf) {
        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }
        data.bankAccount = [get_BankAccount($("[data-atid='BankAccount']", $("#pn_bankAccount_place")))];

        if ((discount = get_discount_field("discount", true)) != undefined)
            data.discount = discount;
    }

    if (similar_procedures) {
        var result = get_bankAccounts();

        if (result.bankAccounts.length == 0 && !tenderType.includes("landArrested-withoutAuction") && !tenderType.includes("basicSell-withoutAuction")) {
            updateTips("Відсутні банківські рахунки", "Y");
            return;
        }

        if (result.errors.length > 0) {
            updateTips(result.errors[0].message, "Y", result.errors[0].id);
            return;
        }

        if (result.bankAccounts.length > 0) {
            data.bankAccounts = result.bankAccounts;
        }

        if (result.bankAccounts.length == 0 && (tenderType.includes("landArrested-withoutAuction") || tenderType.includes("basicSell-withoutAuction"))) {
            data.bankAccounts = [{}];
        }
    }

    if (tenderType.includes('legitimatePropertyLease')) {
        if ((data.leaseRules = get_LeaseRules($("#pn_leaseRulesContent"))) == undefined)
            return;

        if (!bValid)
            return;

        // data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();

        data.relatedOrganizations = {};
        data.relatedOrganizations.propertyOwner = $("#pn_propertyOwner").Tender_Organization("Save");
        data.relatedOrganizations.sellingEntity = $("#pn_sellingEntity").Tender_Organization("Save");

        if (!copy_currentTenant) {
            let currentTenant = $("#pn_currentTenant").Tender_Organization("Save");

            if (currentTenant != "NONE" && currentTenant != false)
                data.relatedOrganizations.currentTenants = [currentTenant];
        }

        data.relatedOrganizations.ownershipType = $("[data-atid='relatedOrganizations.ownershipType']").val();

        data.registryId = (idForm == 0 ? (oFormRecord.registryId != undefined ? oFormRecord.registryId : registryRecord._id) : oFormRecord.registryId);

        data.valuePeriod = $("[data-atid='valuePeriod']").val();

        if (!checkInt($("#ePosition_leaseDuration_y"), 0, 50)) return;
        leaseDuration_y = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_m"), 0, 12)) return;
        leaseDuration_m = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_d"), 0, 31)) return;
        leaseDuration_d = lastCheckValue;

        leaseDuration = "P" + leaseDuration_y + "Y" + leaseDuration_m + "M" + leaseDuration_d + "D";

        data.leaseDuration = leaseDuration;

        if (!priority && (discount = get_discount_field("discount", true)) != undefined && discount.discount != undefined && discount.discount != false)
            data.discount = discount;
        if (!bValid)
            return;

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if (withPublic && tenderType == "legitimatePropertyLease-dutch") {
            delete data.tenderAttempts
        }

        if ($("#martialLawDisclaimer_true").is(':checked')) {
            data.martialLawDisclaimer = true;
        } else {
            data.martialLawDisclaimer = false;
        }
    }

    if (tenderType.includes("landSell") || tenderType.includes("landRental")) {
        if (tenderType.includes("Rental")) {
            if (!checkInt($("#ePosition_leaseDuration_y"), 0, 50)) return;
            leaseDuration_y = lastCheckValue;

            if (!checkInt($("#ePosition_leaseDuration_m"), 0, 12)) return;
            leaseDuration_m = lastCheckValue;

            if (!checkInt($("#ePosition_leaseDuration_d"), 0, 31)) return;
            leaseDuration_d = lastCheckValue;

            leaseDuration = "P" + leaseDuration_y + "Y" + leaseDuration_m + "M" + leaseDuration_d + "D";

            data.leaseDuration = leaseDuration;
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='conditions.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='conditions.uk_UA']"), "", 1, 10000)) return;
            data.conditions = { uk_UA: lastCheckValue };
        }

        if (tenderType.includes("landSell")) {
            data.saleType = $("#slPosition_leaseType").val();
        }

        if (withPublic) {
            if ($(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0 && $(".documentType:contains('contractProforma')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ 'Фотографічні зображення земельної ділянки та ілюстрації' та 'Проєкт договору'", "Y");
                return;
            }

            if ($(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ 'Фотографічні зображення земельної ділянки та ілюстрації'", "Y");
                return;
            }

            if ($(".documentType:contains('contractProforma')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ 'Проєкт договору'", "Y");
                return;
            }
        }

        if ($("#ePosition_normativeMonetaryValuation").val() != "") {
            data.normativeMonetaryValuation = {};
            if (!checkfloat($("#ePosition_normativeMonetaryValuation"), 0, 1000000000000)) return;
            data.normativeMonetaryValuation.amount = lastCheckValue;
            data.normativeMonetaryValuation.currency = "UAH";
        }

        if ($("#ePosition_expertMonetaryValuation").val() != "") {
            data.expertMonetaryValuation = {};
            if (!checkfloat($("#ePosition_expertMonetaryValuation"), 0, 1000000000000)) return;
            data.expertMonetaryValuation.amount = lastCheckValue;
            data.expertMonetaryValuation.currency = "UAH";
        }

        if ($("#ePosition_budgetSpent_amount").val() != "") {
            data.budgetSpent = {};
            if (!checkfloat($("#ePosition_budgetSpent_amount"), 0, 1000000000000)) return;
            data.budgetSpent.amount = lastCheckValue;
            data.budgetSpent.currency = "UAH";

            if ($('#cbPosition_budgetSpent_valueAddedTaxIncluded').prop('checked'))
                data.budgetSpent.valueAddedTaxIncluded = true;
            else {
                data.budgetSpent.valueAddedTaxIncluded = false;
            }
        }

        if (tenderType == "landSell-priorityEnglish" && !copy_currentTenant) {
            if (only_transferPriorityPeriod) {
                data = {};
            }
            let currentTenant = $("#pn_currentTenant").Tender_Organization("Save");

            if (currentTenant != "NONE" && currentTenant != false) {
                data.currentTenants = [currentTenant];
            }

            if ($("#numberOfCurrentTenants").val() == 2) {
                let currentTenant_2 = $("#pn_currentTenant_2").Tender_Organization("Save");

                if (currentTenant_2 != "NONE" && currentTenant_2 != false) {
                    data.currentTenants.push(currentTenant_2);
                }
            }
        }
    }

    if (tenderType.includes("landArrested")) {
        data.saleType = $("#saleType").val();

        if (ar_w_arrest.length > 0) {
            var _els = [];

            for (var j = 0; j < ar_w_arrest.length; j++) {
                var el = ar_w_arrest[j].Save();

                if (!bValid)
                    return;
                _els.push(el);
            }

            data.arrests = _els;
        } else {
            updateTips("Заповніть \"Інформацію про арешти\"", "Y");
            return false;
        }

        if (!tenderType.includes("withoutAuction")) {
            if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
                data.accessDetails = { uk_UA: lastCheckValue };
            }

            if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
                data.x_documentRequirements = { uk_UA: lastCheckValue };
            }

            if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
                data.x_additionalInformation = { uk_UA: lastCheckValue };
            }

            if ($("[data-atid='conditions.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='conditions.uk_UA']"), "", 1, 10000)) return;
                data.conditions = { uk_UA: lastCheckValue };
            }

            if ($("[data-atid='restrictions.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='restrictions.uk_UA']"), "", 1, 10000)) return;
                data.restrictions = { uk_UA: lastCheckValue };
            }

            if ($("#ePosition_normativeMonetaryValuation").val() != "") {
                data.normativeMonetaryValuation = {};
                if (!checkfloat($("#ePosition_normativeMonetaryValuation"), 0, 1000000000000)) return;
                data.normativeMonetaryValuation.amount = lastCheckValue;
                data.normativeMonetaryValuation.currency = "UAH";
            }

            if ($("#ePosition_expertMonetaryValuation").val() != "") {
                data.expertMonetaryValuation = {};
                if (!checkfloat($("#ePosition_expertMonetaryValuation"), 0, 1000000000000)) return;
                data.expertMonetaryValuation.amount = lastCheckValue;
                data.expertMonetaryValuation.currency = "UAH";
            }

            if ($("#ePosition_budgetSpent_amount").val() != "") {
                data.budgetSpent = {};
                if (!checkfloat($("#ePosition_budgetSpent_amount"), 0, 1000000000000)) return;
                data.budgetSpent.amount = lastCheckValue;
                data.budgetSpent.currency = "UAH";

                if ($('#cbPosition_budgetSpent_valueAddedTaxIncluded').prop('checked'))
                    data.budgetSpent.valueAddedTaxIncluded = true;
                else {
                    data.budgetSpent.valueAddedTaxIncluded = false;
                }
            }

            if (tenderType.includes("priorityEnglish") && !copy_currentTenant && prev_tenderType != "landArrested-priorityEnglish") {
                if (only_transferPriorityPeriod) {
                    data = {};
                }
                let currentTenant = $("#pn_currentTenant").Tender_Organization("Save");

                if (currentTenant != "NONE" && currentTenant != false) {
                    data.currentTenants = [currentTenant];
                }

                if ($("#numberOfCurrentTenants").val() == 2) {
                    let currentTenant_2 = $("#pn_currentTenant_2").Tender_Organization("Save");

                    if (currentTenant_2 != "NONE" && currentTenant_2 != false) {
                        data.currentTenants.push(currentTenant_2);
                    }
                }
            }
        }

        if (tenderType.includes("withoutAuction") && prev_tenderType != "landArrested-english" && prev_tenderType != "landArrested-priorityEnglish" && oFormRecord.status != "active_awarded") {
            get_award_withoutAuction(data);
        }

        if (withPublic && !tenderType.includes("withoutAuction")) {
            if ($(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0 && $(".documentType:contains('technicalSpecifications')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ \"Фотографічні зображення земельної ділянки та ілюстрації\" та \"Копії документів та матеріалів на лот\"", "Y");
                return;
            }

            if ($(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ \"Фотографічні зображення земельної ділянки та ілюстрації\"", "Y");
                return;
            }

            if ($(".documentType:contains('technicalSpecifications')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ \"Копії документів та матеріалів на лот\"", "Y");
                return;
            }
        }
    }

    if (tenderType.includes("basicSell") || tenderType.includes("simpleSell") || tenderType.includes("alienation")) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1 && !tenderType.includes("withoutAuction")) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }

        if ($('#cbPosition_valueAddedTaxCharged').prop('checked')) {
            data.valueAddedTaxCharged = true
        } else {
            data.valueAddedTaxCharged = false
        }

        if (!tenderType.includes("simpleSell") && !tenderType.includes("basicSell-withoutAuction")) {
            if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
                data.accessDetails = { uk_UA: lastCheckValue };
            }

            if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
                data.x_documentRequirements = { uk_UA: lastCheckValue };
            }
        }

        if (!tenderType.includes("simpleSell")) {
            if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
                if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
                data.x_additionalInformation = { uk_UA: lastCheckValue };
            }
        }

        if (!tenderType.includes("alienation") && !tenderType.includes("simpleSell") && !tenderType.includes("basicSell-withoutAuction") && withPublic && $(".documentType:contains('technicalSpecifications')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Технічні специфікації'", "Y");

            return;
        }

        if (tenderType.includes("alienation") && withPublic && $(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Ілюстрації'", "Y");

            return;
        }

        if ($("#isPerishable").is(':checked')) {
            data.isPerishable = true;
            delete data.auctionPeriod;
        }

        if (!not_copy && tenderType.includes("simpleSell") && (idForm == 0 || strStartsWith(oFormRecord.id, 'web'))) {
            data.tenderPeriod = {};
            dMaxDate = Today();
            dMaxDate.setDate(dMaxDate.getDate() + 8);
            if (!checkDate($("#simpleSell_tenderPeriod_endDate_Date"), "", Today(), dMaxDate)) return;
            _date = lastCheckValue;

            if (!checkTime($("#simpleSell_tenderPeriod_endDate_Time"))) {
                updateTips("Вкажіть час Період подання пропозицій до", "Y");
                return;
            }
            data.tenderPeriod.endDate = getISO_datetime(_date, lastCheckValue, cdb == 3);
        }

        if (tenderType.includes("basicSell-withoutAuction") && prev_tenderType != "basicSell-english" && prev_tenderType != "basicSell-dutch" && oFormRecord.status != "active_awarded") {
            get_award_withoutAuction(data);
        }
    }

    if (tenderType.includes('commercialSell')) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }
    }

    if (tenderType.includes('bankRuptcy')) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1 && !tenderType.includes("withoutAuction")) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='bankruptcyCaseNumber.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='bankruptcyCaseNumber.uk_UA']"), "", 1, 10000)) return;
            data.bankruptcyCaseNumber = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='economicCourtName.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='economicCourtName.uk_UA']"), "", 1, 10000)) return;
            data.economicCourtName = { uk_UA: lastCheckValue };
        }

        if (tenderType.includes("withoutAuction") && $("[data-atid='restrictions.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='restrictions.uk_UA']"), "", 1, 10000)) return;
            data.restrictions = { uk_UA: lastCheckValue };
        }

        data.debtorInformation = $("#pn_debtorInformation").Tender_Organization("Save");
        if (data.debtorInformation == "NONE") {
            delete data.debtorInformation
        }

        if (withPublic) {
            if ($(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
                updateTips("Додайте документ 'Ілюстрації'", "Y");
                return;
            }

            if (!tenderType.includes("withoutAuction") && $(".documentType:contains('contractProforma')", "#pn_trd_doc_place").length == 0) {
                updateTips('Додайте документ "Проєкт акту/договору"', "Y");
                return;
            }
        }

        if (tenderType.includes("withoutAuction")) {
            get_award_withoutAuction(data);
        }
    }

    if (tenderType.includes("regulationsPropertyLease")) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }

        if (!checkInt($("#ePosition_leaseDuration_y"), 0, 50)) return;
        leaseDuration_y = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_m"), 0, 12)) return;
        leaseDuration_m = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_d"), 0, 31)) return;
        leaseDuration_d = lastCheckValue;

        leaseDuration = "P" + leaseDuration_y + "Y" + leaseDuration_m + "M" + leaseDuration_d + "D";

        data.leaseDuration = leaseDuration;

        data.valuePeriod = $("[data-atid='valuePeriod']").val();

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        let schedule = get_schedule();

        if (Object.keys(schedule).length > 0)
            data.schedule = schedule;

        if (withPublic && $(".documentType:contains('contractProforma')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Проєкт договору оренди'", "Y");

            return;
        }

        if (withPublic && $(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Фотографічне зображення майна'", "Y");

            return;
        }
    }

    if (tenderType.includes("commercialPropertyLease")) {
        if ((idForm == 0 || idForm.includes("web")) && tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }

        if (!checkInt($("#ePosition_leaseDuration_y"), 0, 50)) return;
        leaseDuration_y = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_m"), 0, 12)) return;
        leaseDuration_m = lastCheckValue;

        if (!checkInt($("#ePosition_leaseDuration_d"), 0, 31)) return;
        leaseDuration_d = lastCheckValue;

        leaseDuration = "P" + leaseDuration_y + "Y" + leaseDuration_m + "M" + leaseDuration_d + "D";

        data.leaseDuration = leaseDuration;

        data.valuePeriod = $("[data-atid='valuePeriod']").val();

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        let schedule = get_schedule();

        if (Object.keys(schedule).length > 0)
            data.schedule = schedule;

        if (withPublic && $(".documentType:contains('contractProforma')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Проєкт договору оренди'", "Y");

            return;
        }

        if (withPublic && $(".documentType:contains('illustration')", "#pn_trd_doc_place").length == 0) {
            updateTips("Додайте документ 'Ілюстрації'", "Y");

            return;
        }
    }

    if (tenderType.includes('smallPrivatization') || tenderType.includes('largePrivatization')) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        data.assetHolder = $("#pn_assetHolder").Tender_Organization("Save");

        if (data.assetHolder == "NONE") {
            delete data.assetHolder
        }
    }

    if (tenderType.includes("nonperformingLoans")) {
        if (tenderType.includes("english")) {
            data.minNumberOfQualifiedBids = $("#slPosition_minNumberOfQualifiedBids").val();
        }

        if (data.tenderAttempts > 1) {
            if ((discount = get_discount_field("discount", true)) != undefined)
                data.discount = discount;
        }


        if ($("[data-atid='accessDetails.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='accessDetails.uk_UA']"), "", 1, 10000)) return;
            data.accessDetails = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_additionalInformation.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_additionalInformation.uk_UA']"), "", 1, 10000)) return;
            data.x_additionalInformation = { uk_UA: lastCheckValue };
        }

        if ($("[data-atid='x_documentRequirements.uk_UA']").val() != "") {
            if (!checkLength($("[data-atid='x_documentRequirements.uk_UA']"), "", 1, 10000)) return;
            data.x_documentRequirements = { uk_UA: lastCheckValue };
        }
    }

    if (!bValid)
        return;

    send_data = data;

    cb_command = "DataHandler.ashx?CN=" + vCN + (only_transferPriorityPeriod ? "&CommandName=jSetPositionCurrentTenant&id=" : "&CommandName=jSetPosition&id=") + idForm + "&lastOpr=" + lastOpr;

    cb_data = "&id=" + idForm + (withPublic ? "&withPublic=true" : "") + ((tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested")) && withPublic_land ? "&withPublic_land=true" : "") + "&JData=" + encodeURIComponent(JSON.stringify((only_transferPriorityPeriod ? send_data : { data: send_data })));

    if (tenderType == "bankrupt" && withPublic && strStartsWith(oFormRecord.id, 'web')) {
        $.get("DataHandler.ashx?CommandName=jGetAuctonByLotIdentifier&id=" + idForm + "&lotIdentifier=" + $("#ePosition_dgfID").val() + "&lastOpr=" + lastOpr
            , cb_check_previous);
    }
    else
        cb_send_confirm()
}

function cb_check_previous(data) {
    var message = "";
    var id_prev = undefined;

    data.length > 0
    var the_same_id = send_data.tenderAttempts == 1 && data.length > 0;

    if (!the_same_id && data.length > 0)
        for (i = 0; i < data.length; i++)
            if (data[i].tenderAttempts == send_data.tenderAttempts
                && (send_data.procurementMethodType != undefined && data[i].procurementMethodType == send_data.procurementMethodType
                    || send_data.sellingMethod != undefined && data[i].sellingMethod == send_data.procurementMethod)) {
                the_same_id = true;
                break;
            }

    if (the_same_id)
        message = "У системі знайдено аукціони зі вказаним ідентифікатором лота. Прохання опублікувати повторний аукціон або перевірити коректність введеного ідентифікатору";
    else if (send_data.tenderAttempts == 2 && data.length == 0) {
        for (i = 0; i < data.length; i++)
            if (data[i].tenderAttempts == 2) {
                id_prev = data[i].id;
                break;
            }
        if (id_prev == undefined)
            message = "У системі відсутні попередні аукціони зі вказаним ідентифікатором лота. Прохання опублікувати аукціон без можливості зниження початкової ціни або перевірити коректність введеного ідентифікатору";
    }
    else if (send_data.tenderAttempts == 3) {
        for (i = 0; i < data.length; i++)
            if (data[i].tenderAttempts == 2) {
                id_prev = data[i].id;
                break;
            }
        if (id_prev == undefined)
            message = "У системі відсутні попередні аукціони зі вказаним ідентифікатором лота. Прохання опублікувати перший повторний аукціон або перевірити коректність введеного ідентифікатору";
    }

    if (message != "")
        ConfirmAction(message, cb_send_confirm);
    else
        cb_send_confirm();
}

function cb_send_confirm() {
    if (withPublic)
        updateTips("Очікування публікації в ЦБД", "N");

    $.post(cb_command, cb_data, HandleRequest);
}

function SetStatus(status) {
    data = { id: idForm, status: status };

    jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=jSetPositionStatus&id=" + idForm + "&lastOpr=" + lastOpr
        , "&id=" + idForm + "&JData=" + encodeURIComponent(JSON.stringify(data))
        , HandleRequest);
}

function HandleRequest(data) {
    if (NeedLoginData(data))
        return;

    if (data.row != undefined)
        full_data = data;

    if (data.message == "save_OK") {
        oFormRecord = full_data.row.data;

        if (oFormRecord._id != undefined)
            oFormRecord.id = oFormRecord._id;

        if (oFormRecord.auctionId != undefined)
            oFormRecord.auctionID = oFormRecord.auctionId;

        form_code = oFormRecord.auctionID;
        idForm = oFormRecord.id;

        ShowFrame("auction/" + form_code + '?save_OK=Y'
            + (data.obj_type == undefined ? "" : "&published_obj_type=" + data.obj_type + "&published_obj_id=" + data.obj_id) + (previousAuctionId != undefined ? "&previousAuctionId=" + previousAuctionId : "")
        );
    }
    else if (data.message == "document_delete_OK") {
        updateTips("Документ видалено", "N");
        $("#pn_document_" + data.id_doc).remove();
    }
    else if (data.message == "public_refresh") {
        oFormRecord = full_data.row.data;

        if (oFormRecord.auctionId != undefined)
            oFormRecord.auctionID = oFormRecord.auctionId;

        if (oFormRecord.auctionID != undefined)
            form_code = oFormRecord.auctionID;

        ShowFrame("auction/" + form_code + '?published=Y'
            + (data.obj_type == undefined ? "" : "&published_obj_type=" + data.obj_type + "&published_obj_id=" + data.obj_id)
        );
    }
    else if (data.message == "refresh")
        ShowFrame("auction/" + form_code);
    else if (data.message == "message_land") {
        let result = confirm('Для вказаної вами земельної ділянки вже було опубліковано аукціон іншим Організатором, ви впевнені, що хочете продовжити публікацію?')

        if (result) {
            withPublic_land = false;
            DlgSend(true);
        } else {
            updateTips("Публікацію відмінено", "Y");
        }
    } else if (data.message == "OK")
        ShowFrame("auction/" + full_data.row.data.auctionID, '&id=' + data.row.data.id);
    else {
        updateTips(data.message, "Y");
    }
}

function ShowOnState() {
    if (current_state == undefined || current_state == "created")
        $('.draft_view').show();
    else {
        if (!tenderType.includes("bankRuptcy-withoutAuction") && !tenderType.includes("landArrested-withoutAuction")) {
            $('.public_view').show();
        }
    }

    if (tenderType.includes("simpleSell")) {
        $('.not_simpleSell').hide();
    }

    if (tenderType.includes("basicSell-withoutAuction")) {
        $('.not_basicSell_withoutAuction').hide();
    }

    const protocolStatus = new Set([
        "active_qualification",
        "active_awarded",
        "pending_payment",
        "pending_admission",
        "complete",
        "cancelled",
        "unsuccessful",
        "qualification",
        "active.awarded",
        "active.qualification"
    ]);

    if (protocolStatus.has(current_state) && !tenderType.includes("bankRuptcy-withoutAuction") && !tenderType.includes("landArrested-withoutAuction") && !tenderType.includes("basicSell-withoutAuction")) {
        if (cdb == 3) {
            var ProtocolUrl = (cdb3_dgf ? "https://dgf-procedure.prozorro.sale/api/protocol/" : "https://procedure.prozorro.sale/api/protocol/") + oFormRecord.auctionID;
            if (isPlaceTestMode) {
                var ProtocolUrl = "https://procedure-sandbox.prozorro.sale/api/protocol/" + oFormRecord.auctionID;
            }
        } else {
            var ProtocolUrl = "https://www.prozorro.sale/auction/" + oFormRecord.auctionID + "/print/protocol";
        }

        if (cdb == 3) {
            $('#prnPDF').click(function () { ShowPage("OpenHandler.ashx", `CommandName=GetAuctionProtocol&id=${idForm}&tenderID=${oFormRecord.auctionID}&OperationType=${(cdb == 3 ? `download` : `pdf`)}`); });
            $('#prnHTML').click(function () { ShowPage("OpenHandler.ashx", `CommandName=GetAuctionProtocol&id=${idForm}&tenderID=${oFormRecord.auctionID}&OperationType=${(cdb == 3 ? `print` : `html`)}`); });
            $('#prnWORD').click(function () { ShowPage("OpenHandler.ashx", `CommandName=GetAuctionProtocol&id=${idForm}&tenderID=${oFormRecord.auctionID}&OperationType=doc`); });
        }
        else {
            $('#prnPDF').click(function () { window.open(`${ProtocolUrl}/pdf`, "_blank"); });
            $('#prnHTML').click(function () { window.open(`${ProtocolUrl}/html`, "_blank"); });
            $('#prnWORD').hide();
        }

        $('#prnArea').show();
    }

    if (current_state != undefined && current_state != "") {
        if (tenderType == "bankrupt" && current_state == "active.awarded") {
            contract = oFormRecord.contracts[0];

            var has_annex = false;

            if (contract.documents != undefined)
                for (var i = 0; i < contract.documents.length; i++)
                    if (contract.documents[i].documentType == "contractAnnexe") {
                        has_annex = true;
                        break;
                    }

            if (!has_annex)
                statusText += " (Очікується оплата)";
        }

        $("#tPosition_statusText").text(page_data.StateText);
    }

    if (oFormRecord.auctionID != undefined)
        $("#tPosition_tenderID").text(oFormRecord.auctionID);

    sd = oFormRecord.dateModified;
    if (sd != undefined) {
        $("#tPosition_last_Modified").text(oFormRecord.last_Modified = sISO_8601_2_DMYHM(sd));
    }

    if (oFormRecord.datePublished != undefined && idForm != 0) {
        $("#tPosition_datePublished").text(oFormRecord.datePublished = sISO_8601_2_DMYHM(oFormRecord.datePublished));
    }

    if (oFormRecord.disqualifiedBids != undefined && oFormRecord.disqualifiedBids.length > 0) {
        $("#pn_disqualifiedBids").show();

        for (var i = 0; i < oFormRecord.disqualifiedBids.length; i++) {
            $("#disqualifiedBids_list").append("<div class='row mb-2'><div class='col-12'><span class='font-weight-bold'>Код ЄДРПОУ: </span> <span>" + oFormRecord.disqualifiedBids[i] + "</span></div></div>")

            if ((tenderType.includes("landRental") || tenderType.includes("smallPrivatization") || tenderType.includes("largePrivatization") || tenderType.includes("landArrested")) && oFormRecord.disqualifiedBids[i] == member_identifier_id) {
                already_participated = true;
            }
        }
    }

    if (isOwn && tenderType == "renewables" && (current_state == "active_qualification")) {
        all_finshed = true;

        for (var i = 0; i < oFormRecord.awards.length; i++)
            if (oFormRecord.awards[i].status != "waiting" && oFormRecord.awards[i].status != "unsuccessful" && oFormRecord.awards[i].status != "active") {
                all_finshed = false;
                break;
            }

        if (all_finshed)
            for (var i = 0; i < oFormRecord.contracts.length; i++)
                if (oFormRecord.contracts[i].status == "pending") {
                    all_finshed = false;
                    break;
                }

        if (all_finshed)
            $("[data-atid='btnComplete']").show()
                .click(function () { SetStatus("complete"); });
    }
    else if (isOwn && cdb == 3 && current_state == "active_awarded" || current_state == "pending_admission") {
        has_active_contract = current_state == "pending_admission";

        if (!has_active_contract && oFormRecord.contracts != undefined)
            for (var i = 0; i < oFormRecord.contracts.length; i++)
                if (oFormRecord.contracts[i].status == "active") {
                    has_active_contract = true;
                    break;
                }

        if (has_active_contract)
            $("[data-atid='btnComplete']").show()
                .click(function () { SetStatus("complete"); });
    } else if (isOwn && tenderType.includes("simpleSell") && current_state == "active_qualification") {
        $("[data-atid='btnComplete']").show()
            .click(function () { SetStatus("complete"); });
    }

    if (full_data.canSave == 'true')
        $("[data-atid='btnSaveLast']").show();
    else {
        $("[data-atid='btnSaveLast']").hide();

        if (full_data.ReadOnly == 'true' && !cbd_3_public_edit) {

            SetViewForm('#pnMainParams');
            SetViewForm('#pnContactPoint');
        }
    }

    if (cdb1_public_edit) {
        $('.public_edit').each(function () {
            SetEditForm($(this));
        });
    }
    else if (cdb2_public_edit) {
        $('.cdb2_public_edit').each(function () {
            SetEditForm($(this));
        });
    }
    else if (bankrupt_edit) {
        $(".bankrupt_edit").each(function () {
            SetEditForm($(this));
        });
    }
    else {
        if (full_data.ReadOnly == 'true' && (oFormRecord.tenderAttempts == undefined || oFormRecord.tenderAttempts == ""))
            $('#pn_tenderAttempts').hide();
        else
            if (full_data.ReadOnly != 'true')
                $('#tPosition_tenderAttempts_text').hide();
            else {
                $('#slPosition_tenderAttempts').hide();
                if (cdb == 2) {
                    if (oFormRecord.tenderAttempts == 1)
                        $('#tPosition_tenderAttempts_text').text("Лот виставляється вперше");
                    else
                        $('#tPosition_tenderAttempts_text').text("Лот виставляється повторно");
                }
            }
    }

    if (full_data.canQuestion == 'true')
        $('#btn_question').show()
            .click(function () {
                ShowFrame("Position_questions.aspx", '&id=' + oFormRecord.id + "&questionOf=" + (cdb == 3 ? "auction" : "tender"))
            });

    if (full_data.canShowBids == 'true') {
        $('#bids_ref').show();
        $('#bids_ref').show();
    }

    if (full_data.canCancel == 'true')
        $('#btnСancel').show()
            .click(function () {
                if (strStartsWith(oFormRecord.id, 'web'))
                    $.post("DataHandler.ashx?CommandName=jDeleteObj&id=" + idForm
                        , "&JData=" + encodeURIComponent(JSON.stringify({ main_object: "tender", main_id: idForm }))
                        , HandleRequest);
                else
                    ShowFrame("Position_cancellations.aspx", '&id=' + oFormRecord.id + "&cancellationOf=tender");
            });

    $('#btnBid').click(function () { ShowFrame("BidForm.aspx", '&id=' + idForm + (severalBids ? '&id_bid=0' : "") + (already_participated ? "&already_participated=true" : "")); });
    $('#btnShowBid').click(function () { ShowFrame("BidForm.aspx", '&id=' + idForm + "&id_bid=" + full_data.id_bid + (already_participated ? "&already_participated=true" : "")); });

    $('#btnGoogleCalendar').click(function () {
        $('#GoogleCalendarModal').modal("show");
        load_GCalendar();
    });

    if (full_data.canBid == 'true' && (full_data.id_bid == undefined || severalBids))
        $('#btnBid').show();

    if (full_data.id_bid != undefined)
        $('#btnShowBid').show();

    if (full_data.InList == undefined && idForm != "0" && !isOwn && isLogined)
        $('#btnInList').show()
            .click(function () {
                jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=jSetInList&lastOpr=" + lastOpr
                    , "&id=" + idForm + "&InList=Y"
                    , HandleRequest);

            });

    if (full_data.InList != undefined)
        $('#btnOutList').show()
            .click(function () {
                jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=jSetInList&lastOpr=" + lastOpr
                    , "&id=" + idForm + "&InList=N"
                    , HandleRequest);

            });

    if (idForm != "0" && isAllowRegister && (member_type != 900 && member_type != 903 && member_type != 904)) {
        if (cdb == 2
            || (member_type == 905 && tenderType.includes("basicSell"))
            || (member_type == 915 && tenderType.includes("nonperformingLoans"))
            || (member_type == 914 && tenderType.includes("alienation"))
            || (member_type == 907 && (tenderType.includes("commercialSell") || tenderType.includes("commercialPropertyLease")))
            || (member_type == 901 && (tenderType.includes("landSell") || tenderType.includes("landRental")))
            || (member_type == 916 && tenderType.includes("landArrested"))
            || (member_type == 910 && tenderType.includes("timber"))
            || (member_type == 911 && tenderType.includes("nadra"))
            || (member_type == 909 && tenderType.includes("renewables"))
            || (member_type == 908 && tenderType.includes("bankRuptcy"))
            || (member_type == 905 && tenderType.includes("simpleSell"))
            || (member_type == 913 && tenderType.includes("regulationsPropertyLease"))
            || (member_type == 912 && tenderType.includes("legitimatePropertyLease"))
        ) {
            $('#btnCopy').show().click(function () { PrepareCopyForm() });
        }

        if (tenderType == "legitimatePropertyLease-english" && oFormRecord.tenderAttempts == 1) {
            $('#btnCopy').text('Створити копію аукціону')
        }

        if (tenderType == "legitimatePropertyLease-english" && oFormRecord.tenderAttempts == 2) {
            $('#btnCopy').text('Створити копію аукціону зі зниженням стартової ціни')
        }

        if (tenderType == "legitimatePropertyLease-dutch" && oFormRecord.tenderAttempts == 3) {
            $('#btnCopy').text('Створити копію аукціону за методом покрокового зниження')
        }

        if (tenderType.indexOf('legitimatePropertyLease') > -1 && oFormRecord.status != "unsuccessful" && oFormRecord.status != "cancelled") {
            $('#btnCopy').hide()
        }

        if (cdb == 2 && (member_type == 914 || member_type == 905 || member_type == 907 || member_type == 908 || member_type == 913)) {
            $('#btnCopy').hide();
        }
    }

    if (cdb == 2 && (member_type == 914 || member_type == 905 || member_type == 907 || member_type == 908 || member_type == 913)) {
        $('#btnCopy').hide();
    }

    if (isOwn && idForm != "0" && !strStartsWith(oFormRecord.id, 'web') && tenderType == "legitimatePropertyLease-english" && oFormRecord.tenderAttempts == 1 && (oFormRecord.status == "unsuccessful" || oFormRecord.status == "cancelled")) {
        $("#btnTA2").show().click(function () {
            PrepareCopyForm_TA2()
        });
    }

    if (isOwn && idForm != "0" && !strStartsWith(oFormRecord.id, 'web') && tenderType == "legitimatePropertyLease-english" && oFormRecord.tenderAttempts == 2 && (oFormRecord.status == "unsuccessful" || oFormRecord.status == "cancelled" || oFormRecord.status == "complete")) {
        $("#btn_dutch").show().click(function () {
            PrepareCopyForm_dutch()
        });
    }

    if (isOwn && idForm != "0" && !strStartsWith(oFormRecord.id, 'web') && priority && !tenderType.includes("landSell") && !tenderType.includes("landRental") && !tenderType.includes("landArrested") && (oFormRecord.status == "unsuccessful" || oFormRecord.status == "cancelled")) {
        $("#btn_priority").show().click(function () {
            $("#priority_modal").modal("show");
            $("#go_to_object").attr("href", "asset_rent/" + oFormRecord.registryObjectId)
        });
    }

    if (full_data.canPublic == 'false' && full_data.canSave == 'false' && oFormRecord.auctionID == "UA-PS-2021-03-30-000091-2") {
        $(".UA-auction").show()
    }

    if (full_data.canPublic == 'true'
        || isOwn && (isDebugMode || full_data.canPublic == 'true' && (cdb == 2 || cdb == 3) && !strStartsWith(PMT, "sellout."))
        && (current_state == "active.tendering" || current_state == "active_rectification")
    ) {
        $('#ToPublic').show();

        $("[data-atid='publc']").show().click(function () {
            DlgSend(true);
        });
    }

    if (oFormRecord.status != "active_rectification" && isOwn && oFormRecord.status == "active_tendering" && oFormRecord.transferPriorityPeriod != undefined
        && Date.fromISO(oFormRecord.transferPriorityPeriod.endDate) > new Date()) {
        $("[data-atid='publc']").show().click(function () {
            DlgSend(true);
        });

        only_transferPriorityPeriod = true;
    }

    if (cdb == 2 && strStartsWith(oFormRecord.id, 'web') && (member_type == 905 || member_type == 907 || member_type == 908)) {
        $("[data-atid='publc']").hide();
    }

    if (cdb == 2 && strStartsWith(oFormRecord.id, 'web') && (member_type == 905 || member_type == 907 || member_type == 908 || member_type == 913)) {
        $("[data-atid='publc']").hide();
    }
	
	if (strStartsWith(oFormRecord.id, 'web') && member_type == 916 && (tenderType.includes("landSell") || tenderType.includes("landRental"))) { 
        $("[data-atid='publc']").hide(); 
    } 

    if (isOwn && tenderType == "renewables" && current_state == "qualification") {

        all_finshed = true;

        for (i = 0; i < oFormRecord.awards.length; i++)
            if (oFormRecord.awards[i].status != "waiting" && oFormRecord.awards[i].status != "unsuccessful") {
                all_finshed = false;
                break;
            }

        if (all_finshed) {

            var has_x_verificationAct = false;

            for (i = 0; i < oFormRecord.documents.length; i++)
                if (oFormRecord.documents[i].documentType == "x_verificationAct") {
                    has_x_verificationAct = true;
                    break;
                }

            if (has_x_verificationAct)
                $("[data-atid='btnActiveQualification']").show().click(function () { SetStatus("active_qualification"); });
            else {
                $("[data-atid='sendDoc_x_VerificationAct']").show();

                set_element_documents_add($("[data-atid='sendDoc_x_VerificationAct']"), _pn_trd_doc_place, "auction_verificationAct", "auction", idForm);
            }
        }
    }

    if (ReadOnly && !isDebugMode) {
        $('#tePosition_title').html('<H1>' + $('#tePosition_title').html() + '</H1>');
    }

    if (cdb == 3 && (idForm != 0 && !strStartsWith(oFormRecord.id, 'web'))) {
        SetViewForm($(".pn_input_auction_start"));
        SetViewForm($("#pn_full_field_Procedure_x_platformLegalDetails"));
    }

    if (oFormRecord.x_platformLegalDetails != undefined) {
        $("[data-atid='x_platformLegalDetails'] div span").html("<a href='" + oFormRecord.x_platformLegalDetails + "' target='_blank'>" + oFormRecord.x_platformLegalDetails + "</a>")
    }
}

function slPosition_procurementMethodType_onchange() {
    SetViewForm('#pn_header_param_on_new');

    PMT = $("#slPosition_procurementMethodType").val();

    tender_doc_list = (PMT == "dgfOtherAssets" ? "auction_other" : "auction_financial");

    show_elems_on_MethodType();
}

function slPosition_tenderType_onchange() {
    if (member_type == 901) {
        spec_land($("#slPosition_tenderType").val());
    } else {
        SetViewForm('#pn_header_tenderType');

        tenderType = $("#slPosition_tenderType").val();

        SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts")
            , (tenderType == "bankrupt" ? "tenderAttempts_bankrupt" : "tenderAttempts_10")
            , true, "Виберіть значення");

        if (tenderType == 'comercial') {
            $("#pn_minNumberOfQualifiedBids").show();
        }

        show_elems_on_MethodType();
    }
}

function slPosition_auctionType_onchange() {
    auctionType = $("#slPosition_auctionType").val();

    if (auctionType == "all")
        return;

    if (tenderType == "bankrupt") {
        $("#slPosition_tenderAttempts").val(auctionType.substr(auctionType.indexOf("_") + 1));

        auctionType = auctionType.substr(0, auctionType.indexOf("_"));
    }

    if ((PMT.substr(PMT.indexOf(".") + 1, PMT.length) == "insider" || auctionType == "appraisal.insider" || auctionType == "sellout.insider" || auctionType == "dutch" || PMT == "dgfInsider") && !tenderType.includes("basicSell-dutch") && !tenderType.includes("regulationsPropertyLease-dutch") && !tenderType.includes("commercialPropertyLease-dutch") && !tenderType.includes("commercialSell-dutch") && !tenderType.includes("legitimatePropertyLease-dutch") && !tenderType.includes("nonperformingLoans-dutch") && tenderType != "nadra" && !tenderType.includes("dgf") && !tenderType.includes("bankRuptcy-dutch")) {
        $(".non_dgfInsider").hide();

        $("#pn_auctionParameters_dutchSteps").show();

        if (oFormRecord.auctionParameters == undefined || oFormRecord.auctionParameters.dutchSteps == undefined) {
            if (tenderType == "nadra" && cdb == 2) {
                dutchSteps = 90;
            }

            if ($("#ePosition_auctionParameters_dutchSteps").val() == "")
                $("#ePosition_auctionParameters_dutchSteps").val(dutchSteps);

            if (cdb == 2 && tenderType != "bankrupt")
                SetDicSearchOption(d_dict, $("#slPosition_tenderAttempts")
                    , (tenderType == "bankrupt" ? "tenderAttempts_bankrupt" : "tenderAttempts_fgv")
                    , true, "Виберіть значення");
        }

        if (tenderType != "bankrupt" && !tenderType.includes("bankRuptcy-dutch")) {
            if (cdb != 3 || tenderType != "nadra")
                $("#pn_registrationFee").show();

            $("#pn_tenderAttempts").show();
        }
        if (auctionType == "appraisal.insider" && tenderType != "rent")
            $("#pn_minNumberOfQualifiedBids").hide();
        /*show_bankAccount();*/

    } else if (tenderType.includes("commercialPropertyLease-dutch") || tenderType.includes("regulationsPropertyLease-dutch") || tenderType.includes("basicSell-dutch") || (tenderType.includes("dgf") && auctionType == "dutch") || tenderType.includes("commercialSell-dutch") || tenderType.includes("legitimatePropertyLease-dutch") || tenderType.includes("nonperformingLoans-dutch") || (tenderType == "nadra" && auctionType == "dutch") || tenderType.includes("bankRuptcy-dutch")) {
        show_cdb3_dutchStep();
    } else {
        if (!tenderType.includes("withoutAuction")) {
            $(".non_dgfInsider").show();
        }

        $("#pn_auctionParameters_dutchSteps").hide();

        if (tenderType != "bankrupt")
            $(".pn_tenderAttempts").show();

        if (tenderType != "rent" && bankAccount == undefined)
            $("#pn_auction_bankAccount").hide();

        if (auctionType == "dgfOtherAssets" && oFormRecord.minNumberOfQualifiedBids != undefined && tenderType != "bankrupt")
            $("#pn_minNumberOfQualifiedBids").show();

        if (tenderType == "rent") {
            $(".rent").show();

            if (!ReadOnly || cdb2_public_edit)
                $("#pn_rent_endDate").show();

            if (idForm == 0) {
                $("#slPosition_minNumberOfQualifiedBids").val("1");

                $("#pn_taxHolidays").show();
                $("#pn_taxHolidays_content").wSHdiv({ Title: "Орендні канікули" });
                $("#pn_taxHolidays_control").show();

                $("#pn_escalationClauses").show();
                $("#pn_escalationClauses_content").wSHdiv({ Title: "Індексація ціни" });
                $("#pn_escalationClauses_control").show();
            }

            if (!ReadOnly && member_type == "912")
                SetViewForm($("#pn_minNumberOfQualifiedBids"));
        }
        else if (tenderType == "renewables") {

            $('.pn_input_minimalStep').hide();
        }
    }

    if (cdb3_dgf) {
        add_dgf(auctionType);
    }
}

function show_elems_on_MethodType() {
    Get_swagger_Procedure();

    if (tenderType == "rent") {
        SetDicSearchOption(d_dict, $("#slPosition_auctionType"), "auctionType_cdb2_rent", true, "Виберіть значення");
        //   auctionType = "";
    } else if (tenderType == "nadra") {
        cav_cpv_mask = ["09", "14", "15981", "411", "76"];

        if (idForm == 0 && isPlaceTestMode)
            cdb = (nadra_cdb == 3 ? 3 : 2);

        if (cdb == 3) {
            if (swagger_Procedure == "") {
                swagger_tenderType = "subsoil";
                swagger_Procedure = "subsoil-english.SubsoilEnglishProcedure";
            }
        }

        $("#due_to_reglament").hide();
    } else if (tenderType == "bankrupt") {
        $(".bankrupt").show();
        $("#pn_tenderAttempts").hide();

        SetDicSearchOption(d_dict, $("#slPosition_auctionType"), "auctionType_bankrupt", "NONE", "Виберіть значення");
    } else if (tenderType == "timber") {
        $("#pn_auctionType").hide();
        ReplaceDicById(d_document_type, "technicalSpecifications", "auction_other_cdb2", "auction_timber_technicalSpecifications");

        if (cdb != 2)
            cdb = 3;

        if (cdb == 3) {
            cav_cpv_mask = ["03410", "03411", "03412", "03413", "03414", "03415"];
        }
    }
    else if (tenderType == "renewables") {
        cdb = 3;
        $('.value_currency').text("євро центи");
        $('.guarantee_currency').text("євро");

        //        $('[x-name="guarantee"]').text("Банківська ганантія"); 
        //        $('[x-name="value"]').text("Стартова вартість"); 
        $('[x-name="quantity"]').text("Кількість активів (обсяг квоти)");

        $('.pn_input_minimalStep').hide();
        $('.aw_quantity').show();

        $('#pnPosition_guarantee_percent').hide();

        severalBids = true;
    }

    if (cdb == 3) {
        $('.non_cbd3').hide();
        $('.cbd3').show();
        $("#pnPosition_previousAuctionId").show();
        set_auctionType();

        Ajax_syncGet(path_swagger + ".json?v=" + version, function (data) { obj_swagger = data; on_swagger(); })
    }

    if (PMT == "dgfInsider")
        $(".non_dgfInsider").hide();

    if (tenderType == "renewables" || tenderType == "timber" || tenderType == "nadra") {
        $('#btn_items_add').hide();

        if (oFormRecord.items == undefined || oFormRecord.items.length == 0)
            AddEmpty_Tender_item($('#pn_itemsContent'));
    }
    else {
        $('#btn_items_add').text("Додати актив");
    }

    $('.pn_input_enquiryPeriod').hide();

    if ((PMT == "dgfOtherAssets" || PMT == "dgfFinancialAssets" || PMT == "dgfInsider") && !tenderType.includes("withoutAuction")) {
        $('.pn_input_auction_start').each(function () { $(this).show() });

        if (current_state != undefined && current_state != "draft" && current_state != "create")
            $('.pn_read_tenderPeriod').each(function () { $(this).css("display", "") });
    }

    if (tenderType.includes("basicSell") || tenderType.includes("simpleSell") || tenderType.includes("alienation")) {
        spec_basicSell_type();
    }

    if (tenderType.includes("commercialSell")) {
        spec_commercialSell_type();
    }

    if (tenderType.includes("bankRuptcy")) {
        spec_bankRuptcy_type();
    }

    if (tenderType.includes("regulationsPropertyLease")) {
        spec_regulationsPropertyLease_type();
    }

    if (tenderType.includes("commercialPropertyLease")) {
        spec_commercialPropertyLease_type();
    }

    if (tenderType.includes("nonperformingLoans")) {
        spec_nonperformingLoans_type();
    }

    if (tenderType.includes("landArrested")) {
        spec_landArrested_type();
    }

    if (isOwn && (page_data.canPublic == "true" || page_data.canSave == "true")) {
        $(".hint").show();
    }
}

function goBack() {
    ShowFrame(isLogined ?
        (tenderType.includes('legitimatePropertyLease') ? "filter/legitimate-property-lease"
            : tenderType.includes('landRental') ? "filter/landRental"
                : tenderType.includes('landSell') ? "filter/landSell"
                    : "PositionList.aspx")
        : "Main.aspx");
}

function PrepareCopyForm() {
    idForm = 0;
    if (tenderType == "rent") {
        alert("Оголошення нових перших аукціонів відбувається за оновленою процедурою та здійснюється виключно через опублікований об'єкт оренди у переліку. Інструкції з публікації об'єктів та аукціонів за новою процедурою розміщено у розділі 'Допомога' нижнього меню майданчика. За старою процедурою допускається публікація виключно повторних аукціонів по об'єктах, за якими було здійснено публікацію першого аукціону за старою процедурою.")
    }
    jQuery.getJSON("DataHandler.ashx?CN=" + vCN + "&CommandName=jGetPosition&code=&TimeMark=" + getNTime(), HandleDataEmptyPosition);
}

function PrepareCopyForm_dutch() {
    idForm = 0;
    $("#ePosition_previousAuctionId").val(oFormRecord.auctionID);
    jQuery.getJSON("DataHandler.ashx?CN=" + vCN + "&CommandName=jGetPosition&code=&TimeMark=" + getNTime(), HandleDataEmptyPosition_dutch);
}

function HandleDataEmptyPosition_dutch(response) {
    $("#slPosition_tenderAttempts").val(3);
    $("#slPosition_auctionType").val("dutch");
    tenderType = "legitimatePropertyLease-dutch"
    $("#dutchStep_dutchStepQuantity").val(99);
    let prev_id = oFormRecord.auctionID;
    full_data = response;

    var message = response.message;

    oFormRecord = $.extend(oFormRecord, response.row.data);
    isOwn = response.isOwn == "true";

    $('.NonOwn').hide();

    $('.col48').css("width", "48%");

    oFormRecord.tenderID = "Новий аукціон";
    oFormRecord.statusText = "Створення";
    oFormRecord.status = "";
    current_state = undefined;

    oFormRecord.auctionUrl = undefined
    ReadOnly = false;
    isOwn = true;

    SetEditForm('#pnMainParams');

    $('#pnOnId').hide();

    $('#btnPublic').hide();
    $('#btnCopy').hide();
    $('#btnСancel').hide();

    $("#pn_auction").hide();
    $("#pn_bids").hide();
    $("#pn_trd_doc_place").html("");
    $("#pnWrap_pnAwards").hide();
    $("#ePosition_previousAuctionId").val(prev_id)

    DlgSend(false);
}

function PrepareCopyForm_TA2() {
    idForm = 0;
    jQuery.getJSON("DataHandler.ashx?CN=" + vCN + "&CommandName=jGetPosition&code=&TimeMark=" + getNTime(), HandleDataEmptyPosition_TA2);
}

function HandleDataEmptyPosition_TA2(response) {
    $("#slPosition_tenderAttempts").val(2);
    $("#slPosition_auctionType").val("english-2");
    let prev_id = oFormRecord.auctionID;
    full_data = response;

    var message = response.message;

    oFormRecord = $.extend(oFormRecord, response.row.data);
    isOwn = response.isOwn == "true";

    $('.NonOwn').hide();

    $('.col48').css("width", "48%");

    oFormRecord.tenderID = "Новий аукціон";
    oFormRecord.statusText = "Створення";
    oFormRecord.status = "";
    current_state = undefined;

    oFormRecord.auctionUrl = undefined
    ReadOnly = false;
    isOwn = true;

    SetEditForm('#pnMainParams');

    $('#pnOnId').hide();

    $('#btnPublic').hide();
    $('#btnCopy').hide();
    $('#btnСancel').hide();

    $("#pn_auction").hide();
    $("#pn_bids").hide();
    $("#pn_trd_doc_place").html("");
    $("#pnWrap_pnAwards").hide();
    $("#ePosition_previousAuctionId").val(prev_id)

    DlgSend(false);
}

var trans_ids = {};

function HandleDataEmptyPosition(response) {
    if (isPlaceTestMode && !tenderType.includes("bankRuptcy")) {
        if (cdb == "3") {
            if (strEndsWith(oFormRecord.sellingMethod, "-initial-qualification")
                || oFormRecord.bids != undefined && oFormRecord.bids.length > 0)
                $("#r_auction_MethodDetails_initial_qualification").prop('checked', 'checked');
            else if (strEndsWith(oFormRecord.sellingMethod, "-fast"))
                $("#r_auction_MethodDetails_fast").prop('checked', 'checked');
            else if (strEndsWith(oFormRecord.sellingMethod, "-initial-auction"))
                $("#r_auction_MethodDetails_initial_auction").prop('checked', 'checked');
            else if (strEndsWith(oFormRecord.sellingMethod, "-initial-auction-manual"))
                $("#r_auction_MethodDetails_initial_auction_manual").prop('checked', 'checked');
            else if (strEndsWith(oFormRecord.sellingMethod, "-fast-manual"))
                $("#r_auction_MethodDetails_fast_manual").prop('checked', 'checked');

            cb_auction_MethodDetails_onchange();
        }
        else if (oFormRecord.submissionMethodDetails == "quick" || oFormRecord.submissionMethodDetails == "quick(mode:fast-forward)") {

            $('#cb_is_quick').prop('checked', 'checked');
            var str = oFormRecord.procurementMethodDetails;
            str = str.substr(str.indexOf("=") + 1);

            $("#ePosition_quick_value").val("144");
        }
    }

    full_data = response;

    var message = response.message;

    oFormRecord = $.extend(oFormRecord, response.row.data);
    isOwn = response.isOwn == "true";

    $('.NonOwn').hide();

    $('.col48').css("width", "48%");

    oFormRecord.tenderID = "Новий аукціон";
    oFormRecord.statusText = "Створення";
    oFormRecord.status = "";
    current_state = undefined;

    oFormRecord.tenderType = tenderType;

    if (tenderType == "timber" && cdb == "2"
        || tenderType == "nadra" && cdb == "2" && nadra_cdb == 3) {
        cdb = "3";
        oFormRecord.title = { uk_UA: oFormRecord.title };
        oFormRecord.description = { uk_UA: oFormRecord.description };
    }

    oFormRecord.auctionUrl = undefined
    ReadOnly = false;
    isOwn = true;

    SetEditForm('#pnMainParams');

    $('#pnOnId').hide();

    $('#btnPublic').hide();
    $('#btnCopy').hide();
    $('#btnСancel').hide();

    $("#pn_auction").hide();
    $("#pn_bids").hide();
    $("#pn_trd_doc_place").html("");
    $("#pnWrap_pnAwards").hide();

    has_swagger = false;

    not_copy = true;

    HandleViewForm();

    if (!tenderType.includes("legitimatePropertyLease") && !tenderType.includes("landSell") && !tenderType.includes("landRental") && !tenderType.includes("basicSell") && !tenderType.includes("regulationsPropertyLease") && !tenderType.includes("commercialPropertyLease") && !tenderType.includes("alienation") && !tenderType.includes("commercialSell") && !tenderType.includes("bankRuptcy") && !tenderType.includes("smallPrivatization") && !tenderType.includes("largePrivatization") && !tenderType.includes("simpleSell") && !tenderType.includes("nonperformingLoans") && !tenderType.includes("landArrested")) {
        show_elems_on_MethodType();
    }

    if (oFormRecord.procuringEntity != undefined) {
        $("#pnProcuringEntity").Tender_Organization("destroy");

        $("#pnProcuringEntity").Tender_Organization({
            anItem: oFormRecord
            , OrganisationTitle: "Замовник", ReadOnly: false, OrganisationEditable: false
        });
    }

    if ((oFormRecord.relatedOrganizations != undefined && oFormRecord.relatedOrganizations.currentTenant == undefined) || oFormRecord.currentTenant == undefined) {
        copy_currentTenant = true;
    }

    trans_ids = {};

    if (ar_w_item.length > 0) {
        for (var j = 0; j < ar_w_item.length; j++) {
            ar_w_item[j].ReID();
        }
    }

    $("[data-atid='VerificationDocumentPlace']", $("#pnProcuringEntity")).html("");

    if (!tenderType.includes("basicSell") && !tenderType.includes("regulationsPropertyLease") && !tenderType.includes("commercialPropertyLease") && !tenderType.includes("alienation") && !tenderType.includes("commercialSell") && !tenderType.includes("bankRuptcy") && !tenderType.includes("smallPrivatization") && !tenderType.includes("largePrivatization") && !tenderType.includes("simpleSell") && !tenderType.includes("nonperformingLoans")) {
        $("#pn_bankAccount_place").html("");
    }

    if (tenderType == "renewables") {
        add_VerificationDocuments($("[data-atid='VerificationDocumentPlace']", $("#pnProcuringEntity"))
            , full_data.j_content == undefined ? undefined : full_data.j_content.x_verificationDocuments_renewables
            , "renewables.ProcuringEntity", "x_verificationDocuments", ReadOnly);
    }
    if (tenderType == "renewables" || tenderType == "timber") {
        add_BankAccount($("#pn_bankAccount_place")
            , full_data.j_content == undefined ? undefined : full_data.j_content.bankAccount_cbd3
            , ReadOnly);
    }

    if (cdb == "3")
        $("#pn_test_bids_contetnt").text("");

    if (tenderType.includes("landSell") || tenderType.includes("landRental") || tenderType.includes("landArrested")) {
        previousAuctionId = oFormRecord.auctionID;
    }

    if (tenderType == "nadra") {
        $("#slPosition_tenderAttempts").val(2);
        if (!strStartsWith(oFormRecord.auctionID, 'loc')) {
            $("#ePosition_previousAuctionId").val(oFormRecord.auctionID);
        }
    }

    DlgSend(false);
}

function HandleBids() {
    if (full_data.bids == undefined)
        return;


    if (oFormRecord.lots == undefined || oFormRecord.lots.length == 1) {
        full_data.id_bid = full_data.bids[0].id;

        if (oFormRecord.lots == undefined)
            lot_bid_participate["tender"] = { participationUrl: full_data.bids[0].participationUrl }
        else if (oFormRecord.lots.length == 1)
            lot_bid_participate[oFormRecord.lots[0].id] = { participationUrl: full_data.bids[0].lotValues[0].participationUrl }

        return;
    }

    for (var i = 0; i < full_data.bids.length; i++) {
        el_bid = full_data.bids[i];

        if (el_bid.lotValues.length == 1) {
            if (lot_bid_participate[el_bid.lotValues[0].relatedLot] == undefined
                || el_bid.lotValues[0].value < lot_bid_participate[el_bid.lotValues[0].relatedLot].value)
                lot_bid_participate[el_bid.lotValues[0].relatedLot] = { participationUrl: el_bid.lotValues[0].participationUrl, value: el_bid.lotValues[0].value };

            lot_bid_participate[el_bid.lotValues[0].relatedLot].id_lot_bid = el_bid.id;
        }
        else {
            full_data.id_bid = el_bid.id;

            for (var j = 0; j < el_bid.lotValues.length; j++) {
                if (lot_bid_participate[el_bid.lotValues[j].relatedLot] == undefined
                    || el_bid.lotValues[0].value < lot_bid_participate[el_bid.lotValues[j].relatedLot].value)
                    lot_bid_participate[el_bid.lotValues[j].relatedLot] = { participationUrl: el_bid.lotValues[j].participationUrl, value: el_bid.lotValues[j].value }
            }

        }
    }
}

function OnValueAmountChange(block, group, elem, container) {
    s_value = $("#e" + block + "_value_amount", container).val();

    f_value = s2float(s_value);
    if (isNaN(f_value) || f_value == 0)
        return;

    if (tenderType == "bankrupt" && group == "guarantee" && elem == "amount"
        && $("#ePosition_guarantee_percent").val() == ""
        && tenderType != "renewables") {
        $("#ePosition_guarantee_percent").val("10");
        $("#ePosition_guarantee_amount").val(Math.round(10 * f_value) / 100);
    }

    s_step = $("#e" + block + "_" + group + "_" + elem, container).val();


    f_step = s2float(s_step);
    if (isNaN(f_step))
        return;

    if (elem == "amount")
        $("#e" + block + "_" + group + "_percent", container).val(Math.round(100 * 100 * f_step / f_value) / 100);
    else
        $("#e" + block + "_" + group + "_amount", container).val(Math.round(f_step * f_value) / 100);

    if (group == "guarantee" && !ReadOnly && tenderType == "bankrupt") {
        if ((s_guarantee_percent = $("#ePosition_guarantee_percent", container).val()) != ""
            && !isNaN(f_guarantee_percent = s2float(s_guarantee_percent))
            && f_guarantee_percent != 10
        )
            $("#bankrupt_guarantee_not_10", container).show();
        else
            $("#bankrupt_guarantee_not_10", container).hide();
    }
}

function similar_tender() {
    localStorage.setItem('similar_tender', page_data.row.data.items[0].classification.id);
    window.open(".?ftype=sm");
}

function similar_tlg() {
    var item_tlg = page_data.row.data.items[0].classification.id;
    if (item_tlg.startsWith('34') == true) {
        $('#btnSimilarTLG').attr("href", "http://t.me/Uub_Cars")
    } else if (item_tlg.startsWith('04') == true) {
        $('#btnSimilarTLG').attr("href", "http://t.me/Uub_RealEstate")
    } else if (item_tlg.startsWith('1491') == true) {
        $('#btnSimilarTLG').attr("href", "http://t.me/Uub_ScrapMetal")
    }
}

function cb_endDate_onchange() {
    cb_endDate_checked = $("#cb_endDate").prop('checked');

    if (cb_endDate_checked) {
        $("#pn_endDate_enter_comment").show();
    }
    else {
        $("#pn_endDate_enter_comment").hide();
    }
}

function rename_bankrupt_elements() {
    $("#pn_contract_record_title___id").text("Акт");
    $("#l_contract_index___value_amount").text("Сума відповідно до акту (з урахуванням ПДВ та інших податків)");
    $("#bt_contract_save_index__").text("Зберегти дані");
}

has_swagger = false;

function on_swagger() {
    if (has_swagger)
        return;

    has_swagger = true;

    $(".sw_lang").each(function () {
        set_swagger_legalName(this);
    });

    sw_ReadOnly = ReadOnly && full_data.canSave != 'true' && full_data.canPublic != 'true';

    $("#pn_position_fields").html("");
    $("#pn_position_periods").html("");
    $("[data-atid='VerificationDocumentPlace']", $("#pnProcuringEntity")).html("");
    $("#pn_bankAccount_place").html("");

    switch (tenderType) {
        case "renewables": set_renewables()
            break;
        case "nadra": set_nadra();
            break;
        case "timber": set_timber();
            break;
        case "dgf": set_dgf();
            break;
        case "railwayCargo": set_railwayCargo();
            break;
        case "legitimatePropertyLease-english":
        case "legitimatePropertyLease-priorityEnglish":
        case "legitimatePropertyLease-dutch": (idForm == 0 ? set_legitimatePropertyLease() : get_legitimatePropertyLease());
            break;
        case "landSell-priorityEnglish":
        case "landRental-english":
        case "landSell-english": spec_landRental();
            break;
        case "basicSell-dutch":
        case "basicSell-withoutAuction":
        case "simpleSell-withoutAuction":
        case "alienation-english":
        case "basicSell-english": spec_basicSell();
            break;
        case "commercialSell-dutch":
        case "commercialSell-english": spec_commercialSell();
            break;
        case "bankRuptcy-dutch":
        case "bankRuptcy-withoutAuction":
        case "bankRuptcy-english": spec_bankRuptcy();
            break;
        case "regulationsPropertyLease-english":
        case "regulationsPropertyLease-dutch": spec_regulationsPropertyLease();
            break;
        case "commercialPropertyLease-english":
        case "commercialPropertyLease-dutch": spec_commercialPropertyLease();
            break;
        case "smallPrivatization-english":
        case "smallPrivatization-dutch": spec_smallPrivatization();
            break;
        case "largePrivatization-english": spec_largePrivatization();
            break;
        case "nonperformingLoans-english":
        case "nonperformingLoans-dutch": spec_nonperformingLoans();
            break;
        case "landArrested-english":
        case "landArrested-priorityEnglish":
        case "landArrested-withoutAuction": spec_landArrested();
            break;
    }
}

function cb_auction_MethodDetails_onchange() {
    MethodDetails = $("[name='r_auction_MethodDetails']input:checked").val();

    if (MethodDetails == "initial-auction" || MethodDetails == "initial-auction-manual" || MethodDetails == "initial-qualification") {
        if ($("#pn_test_bids_contetnt").text() == "") {
            $("#pn_test_bids").show();

            if (oFormRecord.bids != undefined)
                for (var i = 0; i < oFormRecord.bids.length; i++)
                    AddTestBid(oFormRecord.bids[i]);
        }
    }
    else {
        $("#pn_test_bids").hide();
        $("#pn_test_bids_contetnt").text("");
    }
}

function tenderAttempts_lotId_change() {
    if ($("[data-atid='tenderAttempts']").val() == 1) {
        $("#pn_discount_field_Procedure_discount").hide();
        $("#pnPosition_previousAuctionId").hide();
    }
    else {
        $("#pn_discount_field_Procedure_discount").show();
        $("#pnPosition_previousAuctionId").show();
    }
}

function load_GCalendar() {
    gapi.load('client:auth2', initClient);
}

function initClient() {
    gapi.client.init({
        apiKey: API_KEY,
        clientId: CLIENT_ID,
        discoveryDocs: DISCOVERY_DOCS,
        scope: SCOPES
    }).then(function () {
        gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
        updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
    }, function (error) {
        appendPre(JSON.stringify(error, null, 2));
    });
}

function updateSigninStatus(isSignedIn) {
    if (isSignedIn) {
        $("#authorize_button").hide();
        $("#signout_button").show();
        $("#btnGoogleCalendarAuction").show();
        $("#btnGoogleCalendarTenderPeriod").show();
        $("#txtGoogleCalendar").show();
    } else {
        $("#authorize_button").show();
        $("#signout_button").hide();
        $("#btnGoogleCalendarAuction").hide();
        $("#btnGoogleCalendarTenderPeriod").hide();
        $("#txtGoogleCalendar").hide();
    }
}

function handleAuthClick() {
    gapi.auth2.getAuthInstance().signIn();
}

function handleSignoutClick() {
    gapi.auth2.getAuthInstance().signOut();
}

function tenderPeriod_event() {
    var event = {
        'summary': page_data.row.data.title,
        'description': 'Кінець періоду подачі пропозиції',
        'start': {
            'dateTime': page_data.row.data.tenderPeriod.endDate,
            'timeZone': 'Europe/Kiev'
        },
        'end': {
            'dateTime': page_data.row.data.tenderPeriod.endDate,
            'timeZone': 'Europe/Kiev'
        },
        'reminders': {
            'useDefault': false,
            'overrides': [
                { 'method': 'email', 'minutes': 60 * 24 },
                { 'method': 'popup', 'minutes': 60 * 24 }
            ]
        }
    };

    var request = gapi.client.calendar.events.insert({
        'calendarId': 'primary',
        'resource': event
    });

    request.execute(function (event) {
        window.open(event.htmlLink, '_blank');
    });
}

function auc_event() {
    var event = {
        'summary': page_data.row.data.title,
        'description': 'Початок аукціону',
        'start': {
            'dateTime': page_data.row.data.auctionPeriod.startDate,
            'timeZone': 'Europe/Kiev'
        },
        'end': {
            'dateTime': page_data.row.data.auctionPeriod.startDate,
            'timeZone': 'Europe/Kiev'
        },
        'reminders': {
            'useDefault': false,
            'overrides': [
                { 'method': 'email', 'minutes': 60 },
                { 'method': 'popup', 'minutes': 60 }
            ]
        }
    };

    var request = gapi.client.calendar.events.insert({
        'calendarId': 'primary',
        'resource': event
    });

    request.execute(function (event) {
        window.open(event.htmlLink, '_blank');
    });
}

function checkCustomsEDRPOU(edrpou) {
    if (edrpou == "43333459" ||
        edrpou == "43332958" ||
        edrpou == "43335608" ||
        edrpou == "43336287" ||
        edrpou == "43350542") {
        $('#slPosition_minNumberOfQualifiedBids option').val("1");
        $("#slPosition_minNumberOfQualifiedBids").prop('disabled', true);
    }
}

function GetProtocol(OperationType) {
    jQuery.post("DataHandler.ashx?CN=" + vCN + "&CommandName=GetAuctionProtocol&id=" + idForm + "&OperationType=" + OperationType
        , "&id=" + idForm);
}

const showModalDateModified = () => {
    const response = (data) => {
        $("#modalNotificationMessageEmailConfirm").text('').addClass("font-weight-bold");
        for (var i = 0; i < data.length; i++) {
            $("#modalNotificationMessageEmailConfirm").append(data[i] + '<br/>')
        }

        $("#modalNotificationEmailConfirm").modal("show");
    };

    jQuery.getJSON("AdminHandler.ashx?CN=0&CommandName=GetObjectOprDates&id=" + idForm, response);
};;
