$.fn.serializeObject = function() {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || "");
        } else {
            o[this.name] = this.value || "";
        }
    });
    return o;
};



const callback_url = "http://185.113.249.32:8080/membership/";
// const serverURL = "http://185.113.249.32:8080/membership/";
const serverURL = "https://demo2.bsl.co.ke/api/v1/";
const API_BASE= "https://demo2.bsl.co.ke/api/v1/";
const serverURL_V = "https://demo2.bsl.co.ke/api/"; // without /v1/

// const serverURL = "http://192.168.1.73:8080/api/v1/";
// const API_BASE= "http://192.168.1.73:8080/api/v1/";



// mapboxgl.accessToken = "pk.eyJ1IjoiaG9zZWFrb3NrZWkiLCJhIjoiY21paDdkeDRpMDA3bTNkc2FwZGd1dWxoZyJ9.Lp_Nxc6q9-ZnAN0Zr7cWZw";



const draftID = 24;
const inProgressID = 47;
const completedID = 33;
const rejectedID = 56;
const ammendID = 65;
isClicked = false;

const tableRegister_consignmentInspectionRequest = 185;
const tableRegister_exporter_low_risk_commodity = 59;
const tableRegister_exporter_inspection_request = 199;
const tableRegister_pest_risk_analysis_request_list = 2;
const tableRegister_quarantine_product_request = 216;
const tableRegister_quarantine_facility = 186;
const tableRegister_evaluation_application = 213;
const tableRegister_exporter_consignment = 154;
const tableRegister_printout_replacement = 211;
const tableRegister_split_consignment = 212;
const tableRegister_agent_registration = 133;
const tableRegister_export_requirements = 129;
const tableRegister_import_requirements = 165;
const tableRegister_exporter_registration = 54;
const tableRegister_commodities = 181;
const tableRegister_exporter_farm = 46;
const tableRegister_exporter_firm = 44;
const tableRegister_storage_location = 30;
const tableRegister_pip_application = 91;
const tableRegister_importer = 75;
const tableRegister_commodities_class = 58;
const tableRegister_commodities_category = 74;
const tableRegister_commodity_family = 58;
const tableRegister_product_form = 99;
const tableRegister_product_variety = 108;
const tableRegister_county = 136;
const tableRegister_inspection_Requirement = 191;
const tableRegister_inspection_Location = 12;
const tableRegister_ban_list = 94;
const tableRegister_subcounty = 134;
const tableRegister_ward = 82;
const reprint_application = 215;
const userRoleID = localStorage.getItem("currentRole");
const document_Type_ID = 0;

isInstitutionletter = false;
isreadOnly = false;
isGlobalDocument = false;
isReadandWrite = false;
isWrite = false;
isEditOnly = false;
isReadViewOnly = false;
isCrudAttachmentview = false;
crudsaveLinesInspection = false;
crudOnetimeExportImportLineeSaveInspection = false;
crudeImportConsLineSaveInspection = false;
crudexportLineSaveInspection = false;
globalCell = false;
isPaymentEdit = false;
isPaid = false;
registered = false;
inprogress = false;
isNew = false;
isSeed = false;
var interval;

isEdit = false;
isAdd = false;
isResearcher = false;
isResearcherLicence = false;

const productsArray = [];

const table_ID = "";
const main_url = "";
const form_type_id = 0;
const reponseObj_obj = "";

var commoditiesArray = [];

var clicked = false;
var setupObj = [];
var allFormObj = [];
var SelectedData = [];
var phytoDataArray = [];

var toBeApprovedActivity = [];
var ids = [];
var recordsIds = [];
var Applications = [];
var inspectionrecords = [];
var stkPushRecords = [];
var CountriesSetup = [];
var pipsLists = [];

var Exporter_Importer = [];
var booleanView = false;

// var userObj =  localStorage.getItem("userObj"); 
var userObj = JSON.parse(localStorage.getItem("userObj"));


const publicPages = ["profile", "change-password", "error", "dashboard"];
const errorArray = [];
const commodityCategory = [];
const mainSettings = {};
const tableRegisterMap = {};
var controller = {
        init: function(formObj) {
            this.myFormObj = formObj;
            var winObj = controller.getWindowURLObject();
            this.windowId = winObj[winObj.length - 1];
            this.pageName = winObj[winObj.length - 2];
            if (!isNaN(this.windowId)) {
                controller.getRelationObjects(this.myFormObj.formName, true);
            } else {
                controller.getRelationObjects(this.myFormObj.formName, false);
            }
        },
        index: function(ctx) {
            formData2 = {};
            var url = ctx.canonicalPath;
            var page = controller.getSecondPart(url);
            if (page == false) {
                window.location = "login.html";
                $(".content-wrapper").load("/forms/shared/error.html");
            } else {
                page_2 = controller.getThirdPart(url);
                var n = publicPages.includes(page_2);
                if (n) {
                    urlPage = "shared";
                } else {
                    urlPage = page;
                }
                window.page = page;
                try {
                    recordID = controller.getFourthPart(url);
                } catch (e) {
                    recordID = "";
                }

                
                if (!isNaN(recordID)) {} else {}
                var http = new XMLHttpRequest();
                http.open("HEAD", "forms/app/main.html", false);
                http.send();
                if (http.status != 404) {
                    $(".content-wrapper").load("forms/app/main.html", function() {
                        controller.setMenu(page, page_2);
                        jQuery.loadScript = function(url, callback) {
                            jQuery.ajax({
                                url: url,
                                dataType: "script",
                                success: callback,
                                async: true,
                            });
                        };
                        if (typeof someObject == "undefined")
                            $.loadScript("js/app/" + page_2 + ".js", function() {
                                if (page_2 == "dashboard" || page_2 == "notifications") {} else {
                                    try {
                                        $(".headerTitle").html(formObj.title);
                                    } catch (e) {}
                                }
                            });
                    });
                } else {
                    $(".content-wrapper").load("forms/shared/error.html");
                    $(".headerTitleSection").html("Error");
                    $(".headerTitle").html("Error");
                }
            }
        },
        manualTabClick: function(activeTab, tabPosition, parentPos = true) {
            for (i in allFormObj) {
                var formObj_ = allFormObj[i];
                if (formObj_.url_id == "tab") {}
            }
            $(".crud_section_lines").hide();
            $(".crud_section_2").hide();
            $(".crud_section_3").hide();
            var activeTab = activeTab;
            var currentTabPos = tabPosition;
            var previousTabPos = 0;
            var highestAccessedTab = 0;
            var formObj_ = allFormObj[activeTab];
            try {
                previousTabPos = allFormObj["previousTabPos"];
                if (previousTabPos == undefined || previousTabPos == "undefined") {
                    allFormObj["previousTabPos"] = 0;
                    previousTabPos = 0;
                }
            } catch (e) {
                allFormObj["previousTabPos"] = 0;
                previousTabPos = 0;
            }
            try {
                highestAccessedTab = allFormObj["highestAccessedTab"];
            } catch (e) {}
            if (formObj_.url_id == "tab") {
                var formLinkToName = formObj_["parentName"];
                var formLinkTo = formObj_["parentID"];
                var formLinkFrom = formObj_["linkID"];
                var targetId = formObj_["targetId"];
                var parentPosition = 0;
                try {
                    parentPosition = formObj_.parentPosition;
                    if (parentPosition == "undefined" || parentPosition == undefined) {
                        parentPosition = 0;
                    }
                } catch (e) {}
                if (parentPosition == 0) {
                    selectedObj = allFormObj["parent_selected"];
                } else {
                    selectedObj = allFormObj["tab_" + formLinkToName];
                }
                if (selectedObj == undefined || selectedObj == "undefined") {
                    selectedObj = [];
                }
                try {
                    selectParentID = selectedObj[formLinkTo];
                    if (
                        selectedObj["exporterConsignment"] &&
                        selectedObj["split_export_consignment_id"] &&
                        activeTab == "exporterConsignmentVarietyDetails"
                    ) {
                        selectParentID = allFormObj["selected"][formLinkTo];
                    } else if (selectedObj["assign_inspection_id"]) {
                        selectParentID =
                            selectedObj["consignmentInspectionRequest"][
                                "consignmentInspectionRequestID"
                            ];
                    } else if (allFormObj["parent_selected"]["exporterFirmID"]) {
                        selectParentID = selectedObj["company"]["company_id"];
                    } else {
                        selectParentID = selectedObj[formLinkTo];
                    }
                } catch (e) {}
                try {
                    if (selectParentID == undefined) {
                        selectParentID = 0;
                    }
                } catch (e) {
                    selectParentID = 0;
                }
                var staticData = false;
                var staticDataContent = "";
                if (formLinkTo == "usedetails.roles") {
                    staticDataContent = selectedObj["usedetails"]["roles"];
                    try {
                        staticData = formObj_["staticData"];
                        if (staticData == undefined || staticData == "undefined") {
                            staticData = false;
                        } else {
                            staticData = true;
                        }
                    } catch (e) {}
                } else {
                    try {
                        staticData = formObj_["staticData"];
                        if (staticData == undefined || staticData == "undefined") {
                            staticData = false;
                        } else {
                            staticData = true;
                            staticDataContent = setupObj[activeTab];
                        }
                    } catch (e) {}
                }
                if (activeTab == "documents") {
                    controller.loadDocumentsUploadStatus(
                        "#Attachments",
                        formObj_["listUrl"] + selectParentID,
                        formObj_["formType_id"],
                        function() {}
                    );
                    return;
                }
                if (activeTab == "documents_reports") {
                    checkAttachemnts();
                    return;
                }
                if (activeTab == "previousapproversremarks") {
                    loaddpreviousApproversremarks();
                    return;
                }
                if (activeTab == "documents_attachments") {
                    checkPayementAttachemnts();
                    return;
                }
                var listUrl = formObj_.listUrl;
                if (
                    (selectParentID == "undefined" || selectParentID == undefined) &&
                    currentTabPos > previousTabPos
                ) {
                    controller.renderNoDataFound(activeTab, formObj_, function() {});
                } else {
                    if (selectedObj["assign_authorisation_id"]) {
                        selectParentID = selectParentID["pipApplicationID"];
                    }
                    listUrl = listUrl.replace("parentID", selectParentID);
                    listUrl = listUrl.substring(0, listUrl.lastIndexOf("=") + 1);
                    listUrl = listUrl + selectParentID;
                    formObj_.listUrl = listUrl;
                    if (parentPos == true) {
                        controller.renderCRUDFormTabs(
                            activeTab,
                            formObj_,
                            function() {},
                            staticData,
                            staticDataContent
                        );
                    }
                }
                if (currentTabPos > previousTabPos) {
                    allFormObj["highestAccessedTab"] = currentTabPos;
                }
            } else {}
            allFormObj["previousTabPos"] = currentTabPos;
        },
        initializeTabs: function() {
            for (i in allFormObj) {
                var formObj_ = allFormObj[i];
                if (formObj_.url_id == "tab") {}
            }
            $(".crud_section ul.nav li")
                .off("click")
                .on("click", function(event) {
                    if (!event.detail || event.detail == 1) {
                        event.preventDefault();
                        $(".crud_section_lines").hide();
                        $(".crud_section_2").hide();
                        $(".crud_section_3").hide();
                        var activeTab = $(this).attr("data-tab");
                        var currentTabPos = $(this).attr("tab-position");
                        var previousTabPos = 0;
                        var highestAccessedTab = 0;
                        try {
                            var formObj_ = allFormObj[activeTab];
                        } catch (e) {}
                        try {
                            previousTabPos = allFormObj["previousTabPos"];
                            if (previousTabPos == undefined || previousTabPos == "undefined") {
                                allFormObj["previousTabPos"] = 0;
                                previousTabPos = 0;
                            }
                        } catch (e) {
                            allFormObj["previousTabPos"] = 0;
                            previousTabPos = 0;
                        }
                        try {
                            highestAccessedTab = allFormObj["highestAccessedTab"];
                        } catch (e) {}
                        if (formObj_.url_id == "tab") {
                            var formLinkToName = formObj_["parentName"];
                            var formLinkTo = formObj_["parentID"];
                            var formLinkFrom = formObj_["linkID"];
                            var targetId = formObj_["targetId"];
                            var parentPosition = 0;
                            try {
                                parentPosition = formObj_.parentPosition;
                                if (
                                    parentPosition == "undefined" ||
                                    parentPosition == undefined
                                ) {
                                    parentPosition = 0;
                                }
                            } catch (e) {}
                            if (parentPosition == 0) {
                                selectedObj = allFormObj["parent_selected"];
                            } else {
                                selectedObj = allFormObj["tab_" + formLinkToName];
                            }
                            try {
                                selectParentID = selectedObj[formLinkTo];
                                if (
                                    selectedObj["exporterConsignment"] &&
                                    selectedObj["split_export_consignment_id"] &&
                                    activeTab == "exporterConsignmentVarietyDetails"
                                ) {
                                    selectParentID = allFormObj["selected"][formLinkTo];
                                } else if (selectedObj["assign_inspection_id"]) {
                                    selectParentID =
                                        selectedObj["consignmentInspectionRequest"][
                                            "consignmentInspectionRequestID"
                                        ];
                                } else if (allFormObj["parent_selected"]["exporterFirmID"]) {
                                    selectParentID = selectedObj["company"]["company_id"];
                                } else {
                                    selectParentID = selectedObj[formLinkTo];
                                }
                            } catch (e) {}
                            var staticData = false;
                            var staticDataContent = "";
                            if (formLinkTo == "usedetails.roles") {
                                staticDataContent = selectedObj["usedetails"]["roles"];
                                try {
                                    staticData = formObj_["staticData"];
                                    if (staticData == undefined || staticData == "undefined") {
                                        staticData = false;
                                    } else {
                                        staticData = true;
                                    }
                                } catch (e) {}
                            } else {
                                try {
                                    staticData = formObj_["staticData"];
                                    if (staticData == undefined || staticData == "undefined") {
                                        staticData = false;
                                    } else {
                                        staticData = true;
                                        staticDataContent = setupObj[activeTab];
                                    }
                                } catch (e) {}
                            }
                            if (activeTab == "documents") {
                                document.getElementsByClassName(
                                    "xcrud-top-actions btn-group"
                                )[0].style.display = "none";
                                controller.loadDocumentsUploadStatus(
                                    "#Attachments",
                                    formObj_["listUrl"] + selectParentID,
                                    formObj_["formType_id"],
                                    function() {}
                                );
                                return;
                            }
                            if (activeTab == "documents_reports") {
                                document.getElementsByClassName(
                                    "xcrud-top-actions btn-group"
                                )[0].style.display = "none";
                                checkAttachemnts();
                                return;
                            }
                            if (activeTab == "documents_attachments") {
                                checkPayementAttachemnts();
                                return;
                            }
                            if (activeTab == "previousapproversremarks") {
                                loaddpreviousApproversremarks();
                                return;
                            }
                            var listUrl = formObj_.listUrl;
                            if (
                                (selectParentID == "undefined" || selectParentID == undefined) &&
                                currentTabPos > previousTabPos
                            ) {
                                controller.renderNoDataFound(activeTab, formObj_, function() {});
                            } else {
                                if (selectedObj["assign_authorisation_id"]) {
                                    selectParentID = selectParentID["pipApplicationID"];
                                }
                                listUrl = listUrl.replace("parentID", selectParentID);
                                listUrl = listUrl.substring(0, listUrl.lastIndexOf("=") + 1);
                                listUrl = listUrl + selectParentID;
                                formObj_.listUrl = listUrl;
                                controller.renderCRUDFormTabs(
                                    activeTab,
                                    formObj_,
                                    function() {},
                                    staticData,
                                    staticDataContent
                                );
                            }
                            if (currentTabPos > previousTabPos) {
                                allFormObj["highestAccessedTab"] = currentTabPos;
                            }
                        } else {}
                        allFormObj["previousTabPos"] = currentTabPos;
                    }
                });
        },
        renderCRUDForm: function(
            target,
            thisObj,
            callback,
            method = "GET",
            params = ""
        ) {
            controller.init(thisObj);
            var formName = thisObj.formName;
            var visibility = "visible";
            postType = "GET";
            try {
                postType = thisObj.postType;
            } catch (e) {}
            var crudAdd = true;
            try {
                crudAdd = thisObj.crudAdd;
                if (crudAdd == undefined || crudAdd == "undefined") {
                    crudAdd = true;
                }
            } catch (e) {}
            var crudsaveLines = true;
            try {
                crudsaveLines = thisObj.crudsaveLines;
                if (crudsaveLines == undefined || crudsaveLines == "undefined") {
                    crudsaveLines = true;
                }
            } catch (e) {}
            var crudAddPhytoProducts = true;
            try {
                crudAddPhytoProducts = thisObj.crudAddPhytoProducts;
                if (
                    crudAddPhytoProducts == undefined ||
                    crudAddPhytoProducts == "undefined"
                ) {
                    crudAddPhytoProducts = true;
                }
            } catch (e) {}
            var crudOnetimeExportImportLineeSave = true;
            try {
                crudOnetimeExportImportLineeSave =
                    thisObj.crudOnetimeExportImportLineeSave;
                if (
                    crudOnetimeExportImportLineeSave == undefined ||
                    crudOnetimeExportImportLineeSave == "undefined"
                ) {
                    crudOnetimeExportImportLineeSave = true;
                }
            } catch (e) {}
            var crudexportLineSave = true;
            try {
                crudexportLineSave = thisObj.crudexportLineSave;
                if (
                    crudexportLineSave == undefined ||
                    crudexportLineSave == "undefined"
                ) {
                    crudexportLineSave = true;
                }
            } catch (e) {}
            var crudeImportConsLineSave = true;
            try {
                crudeImportConsLineSave = thisObj.crudeImportConsLineSave;
                if (
                    crudeImportConsLineSave == undefined ||
                    crudeImportConsLineSave == "undefined"
                ) {
                    crudeImportConsLineSave = true;
                }
            } catch (e) {}
            var crudeAddReprint = true;
            try {
                crudeAddReprint = thisObj.crudeAddReprint;
                if (crudeAddReprint == undefined || crudeAddReprint == "undefined") {
                    crudeAddReprint = true;
                }
            } catch (e) {}
            var crudeAddPhytoReprint = true;
            try {
                crudeAddPhytoReprint = thisObj.crudeAddPhytoReprint;
                if (
                    crudeAddPhytoReprint == undefined ||
                    crudeAddPhytoReprint == "undefined"
                ) {
                    crudeAddPhytoReprint = true;
                }
            } catch (e) {}
            var crudeAddImportConsigmntReprint = true;
            try {
                crudeAddImportConsigmntReprint = thisObj.crudeAddImportConsigmntReprint;
                if (
                    crudeAddImportConsigmntReprint == undefined ||
                    crudeAddImportConsigmntReprint == "undefined"
                ) {
                    crudeAddImportConsigmntReprint = true;
                }
            } catch (e) {}
            var crudPrint = true;
            try {
                crudPrint = thisObj.crudPrint;
                if (crudPrint == undefined || crudPrint == "undefined") {
                    crudPrint = true;
                }
                if (crudDownloadPdf == false) {
                    crudPrint = "hidden";
                } else {
                    crudPrint = "visible";
                }
            } catch (e) {}
            var crudDownloadPdf = true;
            try {
                crudDownloadPdf = thisObj.crudDownloadPdf;
                if (crudDownloadPdf == undefined || crudDownloadPdf == "undefined") {
                    crudDownloadPdf = true;
                }
                if (crudDownloadPdf == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var crudfilterQueryReport = true;
            try {
                crudfilterQueryReport = thisObj.crudfilterQueryReport;
                if (
                    crudfilterQueryReport == undefined ||
                    crudfilterQueryReport == "undefined"
                ) {
                    crudfilterQueryReport = true;
                }
                if (crudfilterQueryReport == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var filterexporterFirmRecords = true;
            try {
                filterexporterFirmRecords = thisObj.filterexporterFirmRecords;
                if (
                    filterexporterFirmRecords == undefined ||
                    filterexporterFirmRecords == "undefined"
                ) {
                    filterexporterFirmRecords = true;
                }
                if (filterexporterFirmRecords == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var filterinLRCRecords = true;
            try {
                filterinLRCRecords = thisObj.filterinLRCRecords;
                if (
                    filterinLRCRecords == undefined ||
                    filterinLRCRecords == "undefined"
                ) {
                    filterinLRCRecords = true;
                }
                if (filterinLRCRecords == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var filterImportConsignmentRecords = true;
            try {
                filterImportConsignmentRecords = thisObj.filterImportConsignmentRecords;
                if (
                    filterImportConsignmentRecords == undefined ||
                    filterImportConsignmentRecords == "undefined"
                ) {
                    filterImportConsignmentRecords = true;
                }
                if (filterImportConsignmentRecords == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var refreshBtn = true;
            try {
                refreshBtn = thisObj.refreshBtn;
                if (refreshBtn == undefined || refreshBtn == "undefined") {
                    refreshBtn = true;
                }
                if (refreshBtn == false) {
                    visibility = "hidden";
                } else {
                    visibility = "visible";
                }
            } catch (e) {}
            var formName = thisObj.formName;
            var tableTitle = thisObj.tableTitle;
            var htmlCrudForm =
                "<div id='" +
                formName +
                "_form' form-name='" +
                formName +
                "' class='crud_form " +
                formName +
                " parsley-form'>";
            htmlCrudForm += "<div class=''>";
            htmlCrudForm +=
                "<div class='row'><div class='col-md-12'><h2 class='headerTitle'> " +
                tableTitle +
                "</h2></div>";
            htmlCrudForm += "</div></div></div>";
            htmlCrudForm += "<div class='xcrud-top-actions'>";
            htmlCrudForm += "<div class='btn-group pull-left'>";
            htmlCrudForm +=
                "<div id='print-btn' class='row' style ='margin-left: 2px;'>";
            htmlCrudForm +=
                "<div class='col-md-3' style ='margin-left: 0px;display: block;'>";
            if (crudAdd) {
                htmlCrudForm +=
                    "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                    formName +
                    "' data-task='create' class='btn btn-success xcrud-action addRecord' style = 'margin-left:2px'><i class='fa fa-plus'></i> Add</a><div class='clearfix'></div></div>";
            }
            htmlCrudForm += "</div>";
            if (crudsaveLinesInspection == true) {
                htmlCrudForm +=
                    '<div class="row" style="display: flex;  margin-right: 20px;float: left;" >';
                htmlCrudForm += '<div  style="width: 100%; display: flex" >';
                htmlCrudForm +=
                    ' <a style="width: 100%;  margin-right: 20px"  data-task="create" class="btn btn-warning xcrud-action saverecordlinesReject"><i class="icon-arrow-right"></i>Not Recommend</a>';
                htmlCrudForm +=
                    '<a   data-task="create" class="btn btn-success xcrud-action saverecordlines"><i class="icon-arrow-right"></i>Recommended</a>';
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            if (crudexportLineSaveInspection == true) {
                htmlCrudForm +=
                    "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                    formName +
                    "' data-task='create' class='btn btn-success xcrud-action crudexportLineSave' style = 'margin-left:2px'><i class='icon-arrow-right'></i>Save</a><div class='clearfix'></div></div>";
            }
            if (crudOnetimeExportImportLineeSaveInspection == true) {
                htmlCrudForm +=
                    '<div class="row" style="display: flex;  margin-right: 20px;float: left;" >';
                htmlCrudForm += '<div  style="width: 100%; display: flex" >';
                htmlCrudForm +=
                    ' <a style="width: 100%;  margin-right: 20px"  data-task="create" class="btn btn-warning xcrud-action crudOnetimeExportImportLineereject"><i class="icon-arrow-right"></i>Not Recommend</a>';
                htmlCrudForm +=
                    '<a   data-task="create" class="btn btn-success xcrud-action crudOnetimeExportImportLineeSave"><i class="icon-arrow-right"></i>Recommended</a>';
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            if (crudeImportConsLineSaveInspection == true) {
                htmlCrudForm +=
                    '<div class="row" style="display: flex;  margin-right: 20px;float: left;" >';
                htmlCrudForm += '<div  style="width: 100%; display: flex" >';
                htmlCrudForm +=
                    ' <a style="width: 100%;  margin-right: 20px"  data-task="create" class="btn btn-warning xcrud-action saverecordImportlinesReject"><i class="icon-arrow-right"></i>Not Recommend</a>';
                htmlCrudForm +=
                    '<a   data-task="create" class="btn btn-success xcrud-action crudimportConsignmentLineSave"><i class="icon-arrow-right"></i>Recommended</a>';
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }

            if (formName == "allReprints") {
                htmlCrudForm +=
                    "<div class='col-md-3' style ='margin-left: -29px;display: block;'>";
                if (crudeAddReprint) {
                    htmlCrudForm +=
                        "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                        formName +
                        "' data-task='create' class='btn btn-success xcrud-action crudAddreprintbtn' style = 'margin-left:2px'><i class='icon-arrow-right'></i>Raise Reprint</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
            }
            if (formName == "allPhytoReprints") {
                htmlCrudForm +=
                    "<div class='col-md-3' style ='margin-left: -29px;display: block;'>";
                if (crudeAddPhytoReprint) {
                    htmlCrudForm +=
                        "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                        formName +
                        "' data-task='create' class='btn btn-success xcrud-action crudAddPhytoreprintbtn' style = 'margin-left:2px'><i class='icon-arrow-right'></i>Raise Reprint</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
            }
            if (formName == "allPhytoReprintsByUser") {
                htmlCrudForm +=
                    "<div class='col-md-3' style ='margin-left: -29px;display: block;'>";
                if (crudeAddPhytoReprint) {
                    htmlCrudForm +=
                        "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                        formName +
                        "' data-task='create' class='btn btn-success xcrud-action crudAddPhytoreprintByUserbtn' style = 'margin-left:2px'><i class='icon-arrow-right'></i>Raise Reprint</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
            }
            if (formName == "allImportConsignmentReprints") {
                htmlCrudForm +=
                    "<div class='col-md-3' style ='margin-left: -29px;display: block;'>";
                if (crudeAddImportConsigmntReprint) {
                    htmlCrudForm +=
                        "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                        formName +
                        "' data-task='create' class='btn btn-success xcrud-action crudAddImportConsReprintbtn' style = 'margin-left:2px'><i class='icon-arrow-right'></i>Raise Reprint</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
            }
            if (formName == "allPhytolicationreports") {}
            if (
                formName == "exporterConsignmentInspectionHeaderList" ||
                formName == "allfirmfarlrcfinspections" ||
                formName == "exporterLowRiskCommodityInspectionHeaderList"
            ) {
                htmlCrudForm += "<div class='xcrud-top-actions'>";
                htmlCrudForm +=
                    "<div class='btn-group pull-right'  style ='margin-right: 0px; margin-bottom: 2px'>";
                htmlCrudForm += "<div  style='margin-left:-55px'>";
                htmlCrudForm +=
                    "<div id='filterRecordstable' class='col-md-3' style ='margin-left: 28px;display: block; margin-right: -12px'>";
                if (crudfilterQueryReport) {
                    htmlCrudForm +=
                        "<div id='filterinspectionsRecords' class='filterinspectionsRecords'><a  href='javascript:;' form-name='" +
                        "" +
                        "' data-task='create' class='btn btn-success xcrud-action filterinspectionsRecords'><i class='fa fa-sort-amount-desc'></i>Filter Records</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            if (formName == "exporterFirmInspectionHeaderList") {
                htmlCrudForm += "<div class='xcrud-top-actions'>";
                htmlCrudForm +=
                    "<div class='btn-group pull-right'  style ='margin-right: 0px; margin-bottom: 2px'>";
                htmlCrudForm += "<div  style='margin-left:-55px'>";
                htmlCrudForm +=
                    "<div id='filterRecordstable' class='col-md-3' style ='margin-left: 28px;display: block; margin-right: -12px'>";
                if (filterexporterFirmRecords) {
                    htmlCrudForm +=
                        "<div id='filterexporterFirmRecords' class='filterexporterFirmRecords'><a  href='javascript:;' form-name='" +
                        "" +
                        "' data-task='create' class='btn btn-success xcrud-action filterexporterFirmRecords'><i class='fa fa-sort-amount-desc'></i>Filter Records</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            if (formName == "exporterLowRiskCommodityInspectionHeaderList") {
                htmlCrudForm += "<div class='xcrud-top-actions'>";
                htmlCrudForm +=
                    "<div class='btn-group pull-right'  style ='margin-right: 0px; margin-bottom: 2px'>";
                htmlCrudForm += "<div  style='margin-left:-55px'>";
                htmlCrudForm +=
                    "<div id='filterRecordstable' class='col-md-3' style ='margin-left: 28px;display: block; margin-right: -12px'>";
                if (filterinLRCRecords) {
                    htmlCrudForm +=
                        "<div id='filterinLRCRecords' class='filterinLRCRecords'><a  href='javascript:;' form-name='" +
                        "" +
                        "' data-task='create' class='btn btn-success xcrud-action filterinspectionsRecords'><i class='fa fa-sort-amount-desc'></i>Filter Records</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            if (formName == "oprallpipapplicationreports") {
                htmlCrudForm += "<div class='xcrud-top-actions'>";
                htmlCrudForm +=
                    "<div class='btn-group pull-right'  style ='margin-right: 0px; margin-bottom: 2px'>";
                htmlCrudForm += "<div  style='margin-left:-55px'>";
                htmlCrudForm +=
                    "<div id='filterRecordstable' class='col-md-3' style ='margin-left: 28px;display: none; margin-right: -12px'>";
                if (crudfilterQueryReport) {
                    htmlCrudForm +=
                        "<div id='filterRecord' class='filterRecord'><a  href='javascript:;' form-name='" +
                        "" +
                        "' data-task='create' class='btn btn-success xcrud-action filterrecords'><i class='fa fa-sort-amount-desc'></i>Filter Records</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            }
            htmlCrudForm +=
                "<div id='download-csv' class='col-md-3' style ='display: none;'>";
            if (crudDownloadPdf) {}
            htmlCrudForm += "</div>";
            htmlCrudForm +=
                "<div id='printbtnpdf' class='col-md-3' style ='display: none;'>";
            if (crudDownloadPdf) {}
            htmlCrudForm += "</div>";
            htmlCrudForm += "</div>";
            htmlCrudForm += "</div>";
            if (
                formName == "exporterConsignmentReports" ||
                formName == "ban_list" ||
                formName == "packagingType" ||
                formName == "product_variety" ||
                formName == "product_category" ||
                formName == "product_form" ||
                formName == "product_class" ||
                formName == "import_requirement" ||
                formName == "export_requirement" ||
                formName == "phytoApplicationReports" ||
                formName == "querypipapplicationreports" ||
                formName == "productHscode" ||
                formName == "products" ||
                formName == "importConsignment"
            ) {
                var formName = thisObj.formName;
                var tableTitle = thisObj.tableTitle;
                var htmlCrudForm =
                    "<div id='" +
                    formName +
                    "_form' form-name='" +
                    formName +
                    "' class='crud_form " +
                    formName +
                    " parsley-form'>";
                htmlCrudForm += "<div class=''>";
                htmlCrudForm +=
                    "<div class='row'><div class='col-md-12'><h2 class='headerTitle'> " +
                    tableTitle +
                    "</h2></div>";
                htmlCrudForm += "</div></div></div>";
                htmlCrudForm += "<div class='xcrud-top-actions'>";
                htmlCrudForm +=
                    "<div class='btn-group pull-left'  style =' margin-bottom: 2px; margin-left:-15px; margin-right:6px'>";
                htmlCrudForm +=
                    "<div class='col-md-3' style ='display: block;text-align:left'>";
                if (crudAdd) {
                    htmlCrudForm +=
                        "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                        formName +
                        "' data-task='create' class='btn btn-success xcrud-action addRecord' style = 'margin-left:2px'><i class='fa fa-plus'></i> Add</a><div class='clearfix'></div></div>";
                }
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm +=
                    "<div class='btn-group pull-right'  style =' margin-bottom: 2px;'>";
                htmlCrudForm += "<div>";
                htmlCrudForm +=
                    "<div id='printbtncsv' class='col-md-3' style ='margin-left: 200px; display: block; margin-right: 20px' >";
                if (crudDownloadPdf) {}
                htmlCrudForm += "</div>";
                htmlCrudForm +=
                    "<div id='printbtnpdf' class='col-md-3' style ='display: block; margin-right: -12px'>";
                if (crudDownloadPdf) {}
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
                htmlCrudForm += "</div>";
            } else {
                $("#printbtncsv").css("display", "none");
                $("#printbtncsv").removeAttr("style");
            }
            htmlCrudForm +=
                "</div><div class='listings' id='listings_" +
                formName +
                "'></div><div class='listings_edit' id='listings_edit_" +
                formName +
                "' style='position: absolute; display: none;top: -1px'></div></div>";
            try {
                controller.show_progress;
                $("." + target)
                    .html(htmlCrudForm)
                    .promise()
                    .done(function() {
                        controller.initActions();
                        var targetIdentifier = "#listings_" + formName;
                        controller.show_progress();
                        controller.loadTable(
                            thisObj.listingsArr,
                            thisObj["listUrl"] + params,
                            thisObj.buttonsArr,
                            thisObj.formName,
                            targetIdentifier,
                            thisObj.groupBy,
                            postType
                        );
                        controller.refreshCrudTables(targetIdentifier);
                    });
            } catch (error) {}
            callback(thisObj);
        },
        renderCRUDFormByName: function(target, formName, callback, method = "GET") {
            var thisObj = allFormObj[formName];
            controller.init(thisObj);
            var crudAdd = true;
            try {
                crudAdd = thisObj.crudAdd;
                if (crudAdd == undefined || crudAdd == "undefined") {
                    crudAdd = true;
                }
            } catch (e) {}
            var crudsaveLines = true;
            try {
                crudsaveLines = thisObj.crudsaveLines;
                if (crudsaveLines == undefined || crudsaveLines == "undefined") {
                    crudsaveLines = true;
                }
            } catch (e) {}
            var crudOnetimeExportImportLineeSave = true;
            try {
                crudOnetimeExportImportLineeSave =
                    thisObj.crudOnetimeExportImportLineeSave;
                if (
                    crudOnetimeExportImportLineeSave == undefined ||
                    crudOnetimeExportImportLineeSave == "undefined"
                ) {
                    crudOnetimeExportImportLineeSave = true;
                }
            } catch (e) {}
            var crudAddPhytoProducts = true;
            try {
                crudAddPhytoProducts = thisObj.crudAddPhytoProducts;
                if (
                    crudAddPhytoProducts == undefined ||
                    crudAddPhytoProducts == "undefined"
                ) {
                    crudAddPhytoProducts = true;
                }
            } catch (e) {}
            var crudexportLineSave = true;
            try {
                crudexportLineSave = thisObj.crudexportLineSave;
                if (
                    crudexportLineSave == undefined ||
                    crudexportLineSave == "undefined"
                ) {
                    crudexportLineSave = true;
                }
            } catch (e) {}
            var crudeImportConsLineSave = true;
            try {
                crudeImportConsLineSave = thisObj.crudeImportConsLineSave;
                if (
                    crudeImportConsLineSave == undefined ||
                    crudeImportConsLineSave == "undefined"
                ) {
                    crudeImportConsLineSave = true;
                }
            } catch (e) {}
            var crudeAddReprint = true;
            try {
                crudeAddReprint = thisObj.crudeAddReprint;
                if (crudeAddReprint == undefined || crudeAddReprint == "undefined") {
                    crudeAddReprint = true;
                }
            } catch (e) {}
            var crudeAddPhytoReprint = true;
            try {
                crudeAddPhytoReprint = thisObj.crudeAddPhytoReprint;
                if (
                    crudeAddPhytoReprint == undefined ||
                    crudeAddPhytoReprint == "undefined"
                ) {
                    crudeAddPhytoReprint = true;
                }
            } catch (e) {}
            var crudeAddImportConsigmntReprint = true;
            try {
                crudeAddImportConsigmntReprint = thisObj.crudeAddImportConsigmntReprint;
                if (
                    crudeAddImportConsigmntReprint == undefined ||
                    crudeAddImportConsigmntReprint == "undefined"
                ) {
                    crudeAddImportConsigmntReprint = true;
                }
            } catch (e) {}
            var crudPrint = false;
            try {
                crudPrint = thisObj.crudPrint;
                if (crudPrint == undefined || crudPrint == "undefined") {
                    crudPrint = true;
                }
            } catch (e) {}
            var crudfilterQueryReport = false;
            try {
                crudfilterQueryReport = thisObj.crudfilterQueryReport;
                if (
                    crudfilterQueryReport == undefined ||
                    crudfilterQueryReport == "undefined"
                ) {
                    crudfilterQueryReport = true;
                }
            } catch (e) {}
            var filterexporterFirmRecords = false;
            try {
                filterexporterFirmRecords = thisObj.filterexporterFirmRecords;
                if (
                    filterexporterFirmRecords == undefined ||
                    filterexporterFirmRecords == "undefined"
                ) {
                    filterexporterFirmRecords = true;
                }
            } catch (e) {}
            var filterinLRCRecords = false;
            try {
                filterinLRCRecords = thisObj.filterinLRCRecords;
                if (
                    filterinLRCRecords == undefined ||
                    filterinLRCRecords == "undefined"
                ) {
                    filterinLRCRecords = true;
                }
            } catch (e) {}
            var filterImportConsignmentRecords = false;
            try {
                filterImportConsignmentRecords = thisObj.filterImportConsignmentRecords;
                if (
                    filterImportConsignmentRecords == undefined ||
                    filterImportConsignmentRecords == "undefined"
                ) {
                    filterImportConsignmentRecords = true;
                }
            } catch (e) {}
            var crudDownloadPdf = false;
            try {
                crudDownloadPdf = thisObj.crudDownloadPdf;
                if (crudDownloadPdf == undefined || crudDownloadPdf == "undefined") {
                    crudDownloadPdf = true;
                }
            } catch (e) {}
            var tableTitle = thisObj.tableTitle;
            var htmlCrudForm =
                "<div id='" +
                formName +
                "_form' form-name='" +
                formName +
                "' class='crud_form " +
                formName +
                " parsley-form'><h2 class='headerTitle'> " +
                tableTitle +
                "</h2>";
            htmlCrudForm += "<div class='xcrud-top-actions'>";
            htmlCrudForm += "<div class='btn-group pull-left'>";
            if (crudAdd) {
                htmlCrudForm +=
                    "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                    formName +
                    "' data-task='create' class='btn btn-success xcrud-action addRecord'><i class='fa fa-plus'></i> Add</a><div class='clearfix'></div></div>";
            }
            htmlCrudForm +=
                "</div><div class='listings' id='listings_" +
                formName +
                "'></div><div class='listings_edit' id='listings_edit_" +
                formName +
                "' style='position: absolute; display: none;top: -1px'></div></div>";
            try {
                $("." + target)
                    .html(htmlCrudForm)
                    .promise()
                    .done(function() {
                        controller.initActions();
                        var targetIdentifier = "#listings_" + formName;
                        controller.show_progress();
                        controller.loadTable(
                            thisObj.listingsArr,
                            thisObj["listUrl"],
                            thisObj.buttonsArr,
                            thisObj.formName,
                            targetIdentifier,
                            thisObj.groupBy,
                            method
                        );
                    });
            } catch (error) {}
            callback();
        },
        renderNoDataFound: function(target, thisObj, callback) {
            var formName = thisObj.formName;
            var htmlCrudForm =
                "<div id='" +
                formName +
                "_form' form-name='" +
                formName +
                "' class='crud_form " +
                formName +
                " parsley-form'><h3 class='headerTitle'> Please select a record on previous tab to proceed..</h3></div>";
            $("." + target).html(htmlCrudForm);
        },
        renderCRUDFormTabs: function(
            target,
            thisObj,
            callback,
            staticData = false,
            staticDataContent = ""
        ) {
            var formName = thisObj.formName;
            postType = "GET";
            try {
                postType = thisObj.postType;
            } catch (e) {}
            var crudAdd = true;
            try {
                crudAdd = thisObj.crudAdd;
                if (crudAdd == undefined || crudAdd == "undefined") {
                    crudAdd = true;
                }
            } catch (e) {}
            var crudsaveLines = true;
            try {
                crudsaveLines = thisObj.crudsaveLines;
                if (crudsaveLines == undefined || crudsaveLines == "undefined") {
                    crudsaveLines = true;
                }
            } catch (e) {}
            var crudOnetimeExportImportLineeSave = true;
            try {
                crudOnetimeExportImportLineeSave =
                    thisObj.crudOnetimeExportImportLineeSave;
                if (
                    crudOnetimeExportImportLineeSave == undefined ||
                    crudOnetimeExportImportLineeSave == "undefined"
                ) {
                    crudOnetimeExportImportLineeSave = true;
                }
            } catch (e) {}
            var crudexportLineSave = true;
            try {
                crudexportLineSave = thisObj.crudexportLineSave;
                if (
                    crudexportLineSave == undefined ||
                    crudexportLineSave == "undefined"
                ) {
                    crudexportLineSave = true;
                }
            } catch (e) {}
            var crudeImportConsLineSave = true;
            try {
                crudeImportConsLineSave = thisObj.crudeImportConsLineSave;
                if (
                    crudeImportConsLineSave == undefined ||
                    crudeImportConsLineSave == "undefined"
                ) {
                    crudeImportConsLineSave = true;
                }
            } catch (e) {}
            var crudPrint = true;
            try {
                crudPrint = thisObj.crudPrint;
                if (crudPrint == undefined || crudPrint == "undefined") {
                    crudPrint = true;
                }
            } catch (e) {}
            var crudfilterQueryReport = true;
            try {
                crudfilterQueryReport = thisObj.crudfilterQueryReport;
                if (
                    crudfilterQueryReport == undefined ||
                    crudfilterQueryReport == "undefined"
                ) {
                    crudfilterQueryReport = true;
                }
            } catch (e) {}
            var filterexporterFirmRecords = true;
            try {
                filterexporterFirmRecords = thisObj.filterexporterFirmRecords;
                if (
                    filterexporterFirmRecords == undefined ||
                    filterexporterFirmRecords == "undefined"
                ) {
                    filterexporterFirmRecords = true;
                }
            } catch (e) {}
            var filterinLRCRecords = true;
            try {
                filterinLRCRecords = thisObj.filterinLRCRecords;
                if (
                    filterinLRCRecords == undefined ||
                    filterinLRCRecords == "undefined"
                ) {
                    filterinLRCRecords = true;
                }
            } catch (e) {}
            var filterImportConsignmentRecords = true;
            try {
                filterImportConsignmentRecords = thisObj.filterImportConsignmentRecords;
                if (
                    filterImportConsignmentRecords == undefined ||
                    filterImportConsignmentRecords == "undefined"
                ) {
                    filterImportConsignmentRecords = true;
                }
            } catch (e) {}
            var crudDownloadPdf = true;
            try {
                crudDownloadPdf = thisObj.crudDownloadPdf;
                if (crudDownloadPdf == undefined || crudDownloadPdf == "undefined") {
                    crudDownloadPdf = true;
                }
            } catch (e) {}
            var htmlCrudForm =
                "<div id='" +
                formName +
                "_form'   form-name='" +
                formName +
                "' class='crud_form parsley-form " +
                formName +
                "'><h2 class='headerTitle'></h2>";
            htmlCrudForm += "<div class='xcrud-top-actions'>";
            htmlCrudForm += "<div class='btn-group pull-left'>";
            if (crudAdd) {
                htmlCrudForm +=
                    "<div class='add_btn_section'><a href='javascript:;' form-name='" +
                    formName +
                    "' data-task='create' class='btn btn-success xcrud-action addRecord'><i class='fa fa-plus'></i> Add</a><div class='clearfix'></div></div>";
            }
            htmlCrudForm +=
                "</div><div class='listings' id='listings_" +
                formName +
                "'></div><div class='listings_edit' id='listings_edit_" +
                formName +
                "' style='display:none;position:absolute;top: -1px'></div></div>";
            $("." + target)
                .html(htmlCrudForm)
                .promise()
                .done(function() {
                    controller.initActions();
                    var targetIdentifier = "#listings_" + formName;
                    $(targetIdentifier).html("loading");
                    controller.show_progress();
                    if (!staticData) {
                        controller.loadTable(
                            thisObj["listingsArr"],
                            thisObj["listUrl"],
                            thisObj.buttonsArr,
                            thisObj.formName,
                            targetIdentifier,
                            thisObj.groupBy,
                            postType
                        );
                    } else {
                        controller.loadTableStaticData(
                            thisObj["listingsArr"],
                            staticDataContent,
                            thisObj.buttonsArr,
                            thisObj.formName,
                            targetIdentifier,
                            thisObj.groupBy,
                            postType
                        );
                    }
                });
            callback();
        },
        renderCRUDTable: function(thisObj, method = "GET") {
            try {
                controller.show_progress();
                var targetIdentifier = "#listings_" + thisObj.formName;
                $("#listings_edit_" + thisObj.formName).hide();
                controller.loadTable(
                    thisObj.listingsArr,
                    thisObj["listUrl"],
                    thisObj.buttonsArr,
                    thisObj.formName,
                    targetIdentifier,
                    thisObj.groupBy,
                    method
                );
            } catch (error) {}
        },
        loadUserDetails: function() {
            var url = "";
            if (window.page == "adminNot used") {
                url = "api/getUserDetailsAdmin.json";
            } else {
                url = "api/getUserDetails.json";
            }
            $.ajax({
                url: url,
                method: "get",
                async: true,
                success: function(data) {
                    var dashboardHTML = "";
                    var firstName = userObj.email;
                    var lastName = "";
                    var role = data.role;
                    var windowAccess = data.windowAccess;
                    var windowAccessAdmin = data.windowAccessAdmin;
                    org = urlPage;
                    if (org == "Admin") {
                        controller.loadToolBarMenu(windowAccessAdmin, org);
                    } else {
                        controller.loadToolBarMenu(windowAccess, org);
                    }
                    $("#fullNames").html(firstName + " " + lastName);
                    window.windowAccess = data.windowAccess;
                    window.windowAccessAdmin = data.windowAccessAdmin;
                    window.org = org;
                },
                fail: function() {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        getFile: function(url, handleData) {
            console.log("x.namex.name", url);
            $j.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                cache: false,
                xhr: function() {
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = "blob";
                    return xhr;
                },
                success: function(data) {
                    var url = window.URL || window.webkitURL;
                    fileSRC = url.createObjectURL(data);
                    handleData(fileSRC);
                },
                error: function() {},
            });
        },

        getFile: function(url, handleData) {
            console.log("x.namex.name", url);
            $j.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                cache: false,
                xhr: function() {
                    var xhr = new XMLHttpRequest();
                    xhr.responseType = "blob";
                    return xhr;
                },
                success: function(data) {
                    var url = window.URL || window.webkitURL;
                    fileSRC = url.createObjectURL(data);
                    handleData(fileSRC);
                },
                error: function() {
                    controller.showToastMsg(
                        "Sorry! File not found in this server",
                        "#ff6666"
                    );
                },
            });
        },

        loadRoleSelect: function(rolesArr, selectedVal) {
            var option = "";
            for (var j = 0; j < rolesArr.length; j++) {
                var itemO = rolesArr[j];
                if (selectedVal == itemO.role_id) {
                    option +=
                        "<option selected value=" +
                        itemO.role_id +
                        ">" +
                        itemO.name +
                        "</option>";
                } else {
                    option +=
                        "<option value=" + itemO.role_id + ">" + itemO.name + "</option>";
                }
            }
            return option;
        },
        loadUserAccess: function() {
            var tmpUserObj = JSON.parse(localStorage.getItem("userObj"));
            rolesArr = tmpUserObj.roles;
            var count = 0;
            var tmpAccessArr = ["app/dashboard", "app/notifications"];
            for (var j = 0; j < rolesArr.length; j++) {
                var itemO = rolesArr[j];
                if (itemO.role_id == 697) {
                    for (var j = 0; j < importerMenu.menu.length; j++) {
                        var itemO = importerMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 699) {
                    for (var j = 0; j < exporterMenu.menu.length; j++) {
                        var itemO = exporterMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 703) {
                    for (var j = 0; j < contentManagerMenu.menu.length; j++) {
                        var itemO = contentManagerMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 691) {
                    for (var j = 0; j < regionalManagerMenu.menu.length; j++) {
                        var itemO = regionalManagerMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 24282) {
                    for (var j = 0; j < accountantMenu.menu.length; j++) {
                        var itemO = accountantMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 693) {
                    for (var j = 0; j < seniorInspectorMenu.menu.length; j++) {
                        var itemO = seniorInspectorMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 1) {
                    for (var j = 0; j < adminMenu.menu.length; j++) {
                        var itemO = adminMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 695) {
                    for (var j = 0; j < InspectorMenu.menu.length; j++) {
                        var itemO = InspectorMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 701) {
                    for (var j = 0; j < newRegistrations.menu.length; j++) {
                        var itemO = newRegistrations.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 24369) {
                    for (var j = 0; j < labTechnicianMenu.menu.length; j++) {
                        var itemO = labTechnicianMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 19100) {
                    for (var j = 0; j < agentMenu.menu.length; j++) {
                        var itemO = agentMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 23385) {
                    for (var j = 0; j < authorizingOfficerMenu.menu.length; j++) {
                        var itemO = authorizingOfficerMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 23380) {
                    for (var j = 0; j < printerOfficerMenu.menu.length; j++) {
                        var itemO = printerOfficerMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                } else if (itemO.role_id == 7879) {
                    for (var j = 0; j < exporterImporterMenu.menu.length; j++) {
                        var itemO = exporterImporterMenu.menu[j];
                        for (var k = 0; k < itemO["child"].length; k++) {
                            try {
                                tmpAccessArr.push(itemO["child"][k]["url"]);
                            } catch (e) {}
                        }
                    }
                }
            }
            localStorage.setItem("accessibleWindows", JSON.stringify(tmpAccessArr));
        },
        loadUserMultipleAccess: function(roleSelected) {
            localStorage.removeItem("accessibleWindows");
            var tmpAccessArr = ["app/dashboard", "app/notifications"];
            if (roleSelected == 697) {
                for (var j = 0; j < importerMenu.menu.length; j++) {
                    var itemO = importerMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 699) {
                for (var j = 0; j < exporterMenu.menu.length; j++) {
                    var itemO = exporterMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 703) {
                for (var j = 0; j < contentManagerMenu.menu.length; j++) {
                    var itemO = contentManagerMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 691) {
                for (var j = 0; j < regionalManagerMenu.menu.length; j++) {
                    var itemO = regionalManagerMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 24282) {
                for (var j = 0; j < accountantMenu.menu.length; j++) {
                    var itemO = accountantMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 693) {
                for (var j = 0; j < seniorInspectorMenu.menu.length; j++) {
                    var itemO = seniorInspectorMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 1) {
                for (var j = 0; j < adminMenu.menu.length; j++) {
                    var itemO = adminMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 695) {
                for (var j = 0; j < InspectorMenu.menu.length; j++) {
                    var itemO = InspectorMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 701) {
                for (var j = 0; j < newRegistrations.menu.length; j++) {
                    var itemO = newRegistrations.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 24369) {
                for (var j = 0; j < labTechnicianMenu.menu.length; j++) {
                    var itemO = labTechnicianMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 19100) {
                for (var j = 0; j < agentMenu.menu.length; j++) {
                    var itemO = agentMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 23385) {
                for (var j = 0; j < authorizingOfficerMenu.menu.length; j++) {
                    var itemO = authorizingOfficerMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 23380) {
                for (var j = 0; j < printerOfficerMenu.menu.length; j++) {
                    var itemO = printerOfficerMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            } else if (roleSelected == 7879) {
                for (var j = 0; j < exporterImporterMenu.menu.length; j++) {
                    var itemO = exporterImporterMenu.menu[j];
                    for (var k = 0; k < itemO["child"].length; k++) {
                        try {
                            tmpAccessArr.push(itemO["child"][k]["url"]);
                        } catch (e) {}
                    }
                }
            }
            localStorage.setItem("accessibleWindows", JSON.stringify(tmpAccessArr));
        },

        loadMenuOnRoleChange: function(roleSelected, selectText) {
            console.log("roleSelected roleSelected", roleSelected)

            controller.loadUserMultipleAccess(roleSelected);
            selectText = "app";
            window.location = "./#app/dashboard";
            var option = "";
            var style_item = "";
            var userDetails_sidebar = "";
            var company = "";
            try {
                company = userObj.company.name;
            } catch (e) {}
            if (userObj.company == null) {
                try {
                    company = userObj.email;
                } catch (error) {
                    company = userObj.email;
                }
            } else {
                company = userObj.company.name;
            }
            userDetails_sidebar += '<li class="nav-heading login-section">' +
                '<span data-localize="sidebar.heading.HEADER"> ' +
                'Welcome, <br>' + company + '' +
                '<br> ' + userObj.username + '' +
                '</span>' +
                '</li><input type="text" id="userInput" onkeyup="serchMenuFunction()" style="width: 99%;margin-bottom: 20px;" placeholder="Search..">' +
                '<button class="refreshCrudTablesLoad_page" onclick="controller.refreshCrudTablesLoad_page()">Dashboard</button>' +
                '<li class="treeview">' +
                '<a class="waves-effect waves-dark" href="/#app/dashboard">' +
                ' <i class="icon-home"></i><span>Home Page</span>' +
                '  </a> ' +
                ' </li>';


            if (roleSelected == 7879) {

                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < exporterImporterMenu.menu.length; j++) {
                    var menuItem = exporterImporterMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 693) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < seniorInspectorMenu.menu.length; j++) {
                    var menuItem = seniorInspectorMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 695) {
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < InspectorMenu.menu.length; j++) {
                    var menuItem = InspectorMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 23380) {
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < printerOfficerMenu.menu.length; j++) {
                    var menuItem = printerOfficerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 24282) {


                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < accountantMenu.menu.length; j++) {
                    var menuItem = accountantMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 1) {
                //new registrations

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < adminMenu.menu.length; j++) {
                    var menuItem = adminMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 697) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < importerMenu.menu.length; j++) {
                    var menuItem = importerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 701) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < newRegistrations.menu.length; j++) {
                    var menuItem = newRegistrations.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 691) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < regionalManagerMenu.menu.length; j++) {
                    var menuItem = regionalManagerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 699) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < exporterMenu.menu.length; j++) {
                    var menuItem = exporterMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 703) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < contentManagerMenu.menu.length; j++) {
                    var menuItem = contentManagerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 19100) {
                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < agentMenu.menu.length; j++) {
                    var menuItem = agentMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 24369) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < labTechnicianMenu.menu.length; j++) {
                    var menuItem = labTechnicianMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else {
                var url = serverURL + "menuRoles/menuRolesByRole?pageNo=0&pageSize=1000&role_id=" + roleSelected;
                controller.requestWithToken(url, function(data, status) {

                    for (var j = 0; j < data.length; j++) {
                        var menuItem = data[j].menu;
                        option += '<li class="mainheader">' +
                            '<a href="#menu_' + menuItem['menu_id'] + '" data-toggle="collapse" aria-expanded="false" class="collapsed">' +
                            menuItem['name'] +
                            '<span class="chevron-icon"><i class="fa fa-chevron-down"></i></span>' +
                            '</a>' +
                            '<ul id="menu_' + menuItem['menu_id'] + '" class="nav sidebar-subnav level3-menu collapse" aria-expanded="false">';

                        for (var i = 0; i < menuItem['formTypes'].length; i++) {
                            var windowMenu = menuItem['formTypes'][i];
                            option += '<li>' +
                                '<a class="menurolesmenuclick" href="#app/' + windowMenu['url'] + '">' +
                                '<em class="icon-note"></em> ' + windowMenu['name'] +
                                '</a>' +
                                '</li>';
                        }

                        option += '</ul></li>';
                    }

                    $('#userDetails_sidebar').html(userDetails_sidebar);
                    $('#menu-ul').html(option);

                    // Initialize collapse for submenus
                    $('.nav.sidebar-subnav.level3-menu').collapse({
                        toggle: false // Do not toggle automatically
                    });

                    // Handle click event for main menu items
                    $('.mainheader > a[data-toggle="collapse"]').on('click', function(event) {
                        event.preventDefault(); // Prevent default anchor behavior

                        var $target = $($(this).attr('href'));
                        var isExpanded = $target.hasClass('show');

                        // Close all other open submenus
                        $('.nav.sidebar-subnav.level3-menu').not($target).collapse('hide');

                        // Toggle the current submenu
                        $target.collapse(isExpanded ? 'hide' : 'show');

                        // Update aria-expanded attribute
                        $(this).attr('aria-expanded', !isExpanded);
                    });
                });
            }

        },


        loadInitialMenuOnRoleChange: function(roleSelected, selectText) {



            console.log("roleSelected roleSelected", roleSelected)

            var option = '';
            selectText = "app";
            var company = userObj.company ? userObj.company.name : userObj.email;
            var userDetails_sidebar = '<li class="nav-heading login-section">' +
                '<span data-localize="sidebar.heading.HEADER"> ' +
                'Welcome, <br>' + company + '<br>' + userObj.username +
                '</span>' +
                '</li>' +
                '<input type="text" id="userInput" onkeyup="serchMenuFunction()" style="width: 100%; margin-top: 2px;margin-bottom: 2px; margin-left: 2px; margin-right: 2px; border-radius: 6px; height: 40px;" placeholder="Search..">' +
                '<button class="refreshCrudTablesLoad_page" onclick="controller.refreshCrudTablesLoad_page()">Dashboard</button>' +
                '<li class="treeview">' +
                '<a class="waves-effect waves-dark" href="/#app/dashboard">' +
                ' <i class="icon-home"></i><span>Home Page</span>' +
                '  </a> ' +
                ' </li>';


            if (roleSelected == 7879) {

                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < exporterImporterMenu.menu.length; j++) {
                    var menuItem = exporterImporterMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 693) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < seniorInspectorMenu.menu.length; j++) {
                    var menuItem = seniorInspectorMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 695) {
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < InspectorMenu.menu.length; j++) {
                    var menuItem = InspectorMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 23380) {
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < printerOfficerMenu.menu.length; j++) {
                    var menuItem = printerOfficerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 24282) {


                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < accountantMenu.menu.length; j++) {
                    var menuItem = accountantMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 1) {
                //new registrations

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < adminMenu.menu.length; j++) {
                    var menuItem = adminMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 697) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < importerMenu.menu.length; j++) {
                    var menuItem = importerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 703) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < contentManagerMenu.menu.length; j++) {
                    var menuItem = contentManagerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 701) {

                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < newRegistrations.menu.length; j++) {
                    var menuItem = newRegistrations.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }
                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 691) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < regionalManagerMenu.menu.length; j++) {
                    var menuItem = regionalManagerMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else if (roleSelected == 24369) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < labTechnicianMenu.menu.length; j++) {
                    var menuItem = labTechnicianMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            }

            // else if (roleSelected == 699) {
            //     for (var j = 0; j < exporterMenu.menu.length; j++) {
            //         var menuItem = exporterMenu.menu[j];
            //         option += '<li class="treeview">' +

            //             '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark" >' +
            //             '<i class="icon-briefcase"></i><span>'+menuItem['parent']+'</span>' +
            //             '<i class="icon-arrow-down"></i>' +
            //             '</a>' +

            //             '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

            //         for (var i = 0; i < menuItem['child'].length; i++) {
            //             var windowMenu = menuItem['child'][i];
            //             option += '<li>' +
            //                      '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '"><i class="icon-arrow-right"></i>'+ windowMenu['title'] +'</a>'+          
            //                      '</li>';
            //         }

            //         option += '</ul></li>';
            //     }
            //     $('#userDetails_sidebar').html(userDetails_sidebar);
            //     $('#sidebarmenu').html(option);

            // } 
            else if (roleSelected == 699) {
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < exporterMenu.menu.length; j++) {
                    var menuItem = exporterMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            }


            // if (roleSelected == 699) {
            //     var option = '';

            //     // Loop through main menu items
            //     for (var j = 0; j < exporterMenu.menu.length; j++) {
            //         var menuItem = exporterMenu.menu[j];

            //         option += '<li class="treeview">' +
            //                     '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
            //                     '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
            //                     '<i class="icon-arrow-down"></i>' +
            //                     '</a>' +
            //                     '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

            //         // Loop through child items
            //         for (var i = 0; i < menuItem['child'].length; i++) {
            //             var windowMenu = menuItem['child'][i];

            //             option += '<li>';

            //             // Main child item link
            //             option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '"><i class="icon-arrow-right"></i>' + windowMenu['title'] + '</a>';

            //             // Check if subchild exists and render them
            //             if (windowMenu['subchild']) {
            //                 option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

            //                 for (var k = 0; k < windowMenu['subchild'].length; k++) {
            //                     var subMenuItem = windowMenu['subchild'][k];

            //                     option += '<li>' +
            //                                 '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
            //                                 '<i class="icon-arrow-right"></i>' + subMenuItem['title'] +
            //                                 '</a>' +
            //                               '</li>';
            //                 }

            //                 option += '</ul>'; // Close subchild menu
            //             }

            //             option += '</li>';
            //         }

            //         option += '</ul></li>'; // Close main child menu
            //     }

            //     // Inject the generated menu HTML into the sidebar
            //     $('#userDetails_sidebar').html(userDetails_sidebar);
            //     $('#sidebarmenu').html(option);
            // }
            else if (roleSelected == 19100) {
                //new registrations
                //new registrations
                var option = '';

                // Loop through main menu items
                for (var j = 0; j < agentMenu.menu.length; j++) {
                    var menuItem = agentMenu.menu[j];

                    option += '<li class="treeview">' +
                        '<a href="#menu_' + menuItem['id'] + '" class="waves-effect waves-dark">' +
                        '<i class="icon-briefcase"></i><span>' + menuItem['parent'] + '</span>' +
                        '<i class="icon-arrow-down"></i>' +
                        '</a>' +
                        '<ul id="menu_' + menuItem['id'] + '" class="treeview-menu">';

                    // Loop through child items
                    for (var i = 0; i < menuItem['child'].length; i++) {
                        var windowMenu = menuItem['child'][i];

                        // Check if the child has subchildren and set the icon accordingly
                        var childIcon = windowMenu['subchild'] ? 'icon-briefcase' : 'icon-note';

                        var chevronicon = windowMenu['subchild'] ? '<i class="icon-arrow-down"></i>' : '';
                        option += '<li>';

                        // Main child item link with dynamic icon
                        option += '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + windowMenu['url'] + '">' +
                            '<i class="' + childIcon + '"></i>' + windowMenu['title'] +
                            '' + chevronicon + '' +
                            '</a>';

                        // Check if subchild exists and render them
                        if (windowMenu['subchild']) {
                            option += '<ul class="treeview-menu subchild-menu">'; // Additional sub-menu for subchildren

                            for (var k = 0; k < windowMenu['subchild'].length; k++) {
                                var subMenuItem = windowMenu['subchild'][k];

                                option += '<li>' +
                                    '<a class="waves-effect waves-dark menurolesmenuclick" href="#' + subMenuItem['url'] + '">' +
                                    '<i class="icon-note"></i>' + subMenuItem['title'] +
                                    '</a>' +
                                    '</li>';
                            }

                            option += '</ul>'; // Close subchild menu
                        }

                        option += '</li>';
                    }

                    option += '</ul></li>'; // Close main child menu
                }

                // Inject the generated menu HTML into the sidebar
                $('#userDetails_sidebar').html(userDetails_sidebar);
                $('#sidebarmenu').html(option);
            } else {
                var url = serverURL + "menuRoles/menuRolesByRole?pageNo=0&pageSize=1000&role_id=" + roleSelected;
                controller.requestWithToken(url, function(data, status) {

                    for (var j = 0; j < data.length; j++) {
                        var menuItem = data[j].menu;
                        option += '<li class="mainheader">' +
                            '<a href="#menu_' + menuItem['menu_id'] + '" data-toggle="collapse" aria-expanded="false" class="collapsed">' +
                            menuItem['name'] +
                            '<span class="chevron-icon"><i class="fa fa-chevron-down"></i></span>' +
                            '</a>' +
                            '<ul id="menu_' + menuItem['menu_id'] + '" class="nav sidebar-subnav level3-menu collapse" aria-expanded="false">';

                        for (var i = 0; i < menuItem['formTypes'].length; i++) {
                            var windowMenu = menuItem['formTypes'][i];
                            option += '<li>' +
                                '<a class="menurolesmenuclick" href="#app/' + windowMenu['url'] + '">' +
                                '<em class="icon-note"></em> ' + windowMenu['name'] +
                                '</a>' +
                                '</li>';
                        }

                        option += '</ul></li>';
                    }

                    $('#userDetails_sidebar').html(userDetails_sidebar);
                    $('#menu-ul').html(option);

                    // Initialize collapse for submenus
                    $('.nav.sidebar-subnav.level3-menu').collapse({
                        toggle: false // Do not toggle automatically
                    });

                    // Handle click event for main menu items
                    $('.mainheader > a[data-toggle="collapse"]').on('click', function(event) {
                        event.preventDefault(); // Prevent default anchor behavior

                        var $target = $($(this).attr('href'));
                        var isExpanded = $target.hasClass('show');

                        // Close all other open submenus
                        $('.nav.sidebar-subnav.level3-menu').not($target).collapse('hide');

                        // Toggle the current submenu
                        $target.collapse(isExpanded ? 'hide' : 'show');

                        // Update aria-expanded attribute
                        $(this).attr('aria-expanded', !isExpanded);
                    });
                });
            }
        },


        preloadmenu: function() {
            var selectVal = document.getElementById("selectRoleVal").value;
            var selectText = document.getElementById("selectRoleVal").innerText;
            controller.loadInitialMenuOnRoleChange(selectVal, selectText);
        },
        loadSelect: function(selectArr, id, name, selectedVal) {
            try {
                selectArr.sort((a, b) => {
                    try {
                        let fa = a.name.toLowerCase(),
                            fb = b.name.toLowerCase();
                        if (fa < fb) {
                            return -1;
                        }
                        if (fa > fb) {
                            return 1;
                        }
                        return 0;
                    } catch (error) {
                        let fa = a.username.toLowerCase(),
                            fb = b.username.toLowerCase();
                        if (fa < fb) {
                            return -1;
                        }
                        if (fa > fb) {
                            return 1;
                        }
                        return 0;
                    }
                });
                var option = "";
                for (var j = 0; j < selectArr.length; j++) {
                    var itemO = selectArr[j];
                    if (selectedVal == itemO[id]) {
                        option +=
                            "<option selected value=" +
                            itemO[id] +
                            ">" +
                            itemO[name] +
                            "</option>";
                    } else {
                        option +=
                            "<option value=" + itemO[id] + ">" + itemO[name] + "</option>";
                    }
                }
                return option;
            } catch (error) {}
        },
        loadActivities: function() {
            var listUrl =
                serverURL +
                "workflowActivity/getWorkFlowActivityByUser?user_id=" +
                userObj.id;
            $.ajax({
                url: listUrl,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    var jsonData = data;
                    var counterActivities = jsonData.length;
                    if (counterActivities != null && counterActivities != "null") {
                        var alertHtml =
                            "<span class='alertNoMsg'>" + counterActivities + "</span>";
                        $(".alertNo").html(alertHtml);
                    }
                    localStorage.setItem("alertNo", counterActivities);
                },
                fail: function() {
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#blinder").hide();
                },
            });
        },
        UrlExists: function(url) {
            var http = new XMLHttpRequest();
            http.open("HEAD", url, false);
            http.send();
            return http.status != 404;
        },
        about: function(ctx) {},
        error: function(ctx) {
            window.location = "index.html";
        },
        contact: function(ctx) {},
        getSecondPart: function(str) {
            hashArray = str.split("#");
            str = hashArray[1];
            if (str != undefined) {
                var res = str.split("/");
                return res[0];
            } else {
                return false;
            }
        },
        getThirdPart: function(str) {
            str = str.split("#")[1];
            var res = str.split("/");
            return res[1];
        },
        getFourthPart: function(str) {
            str = str.split("#")[2];
            var res = str.split("/");
            return res[2];
        },
        loadToolBarMenu: function(accessArr, org) {
            var toolBarMenu = "";
            var sideMenu = "";
            var count = 0;
            toolBarMenu +=
                "<div class='column' style='width:33%!important;'><h4 class='ui header'>Section</h4><div class='ui link list'>";
            for (key in accessArr) {
                count++;
                if (count == 9) {
                    count = 0;
                    toolBarMenu +=
                        "</div></div><div class='column' style='width:33%!important;'><h4 class='ui header'>Section</h4><div class='ui link list'>";
                }
                if (org == "Admin") {
                    toolBarMenu +=
                        "<a style='color:#333!important;word-wrap: break-word;white-space: initial' class='item' href='./#" +
                        org +
                        "/" +
                        accessArr[key].identifier +
                        "'></i>" +
                        accessArr[key].windowName +
                        "</a>";
                } else {
                    toolBarMenu +=
                        "<a style='color:#333!important;word-wrap: break-word;white-space: initial' class='item' href='./#" +
                        org +
                        "/" +
                        accessArr[key].identifier +
                        "-listing'></i>" +
                        accessArr[key].windowName +
                        "</a>";
                }
            }
            $(".menu-dropdown").html(toolBarMenu);
        },
        testEditRow() {
            var arrObj = {
                exporterID: 442,
                isOwnFarmExporter: true,
                isExportCosolidator: false,
                isDryCommodityExporter: true,
                isResearcher: false,
                documentNumber: "Application for Certificate of Competency - Exporter/441/2021",
                docType: {
                    docType_id: 52,
                    code: "default",
                    name: "Default",
                    prefix: "txt",
                    sequence: 0,
                    suffix: "txt",
                    description: "doc typ",
                    createdAt: "Oct 21, 2020 11:34:40 AM",
                    updatedAt: "Oct 22, 2020 12:39:06 PM",
                    isActive: true,
                    isforapproval: false,
                    processing: false,
                    processed: false,
                    isapproved: false,
                    isRejected: false,
                    isAmmend: false,
                    createdBy: 46,
                    updatedBy: 46,
                },
                company: {
                    company_id: 4802,
                    code: "C920932",
                    name: "COMPANY TEST ONE",
                    email: "pchieni25@mailinator.com",
                    description: "company reg",
                    registrationDate: "Jan 1, 2020 12:00:00 AM",
                    entityType: {
                        entityType_id: 22,
                        code: "c1",
                        name: "Parastatal",
                        createdAt: "Oct 14, 2020 9:01:45 AM",
                        updatedAt: "Oct 15, 2020 8:32:10 AM",
                        isActive: true,
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 46,
                        updatedBy: 46,
                    },
                    companyRegistratioNo: "C920932",
                    PIN: "P346634831A",
                    createdAt: "Nov 8, 2021 7:32:16 AM",
                    updatedAt: "Nov 8, 2021 7:32:16 AM",
                    isActive: true,
                    approvalStage: "Applicant Stage",
                    isforapproval: false,
                    processing: false,
                    processed: false,
                    isapproved: false,
                    isRejected: false,
                    isAmmend: false,
                },
                address: {
                    address_id: 266,
                    email: "pchieni25@mailinator.com",
                    company: {
                        company_id: 4802,
                        code: "C920932",
                        name: "COMPANY TEST ONE",
                        email: "pchieni25@mailinator.com",
                        description: "company reg",
                        registrationDate: "Jan 1, 2020 12:00:00 AM",
                        entityType: {
                            entityType_id: 22,
                            code: "c1",
                            name: "Parastatal",
                            createdAt: "Oct 14, 2020 9:01:45 AM",
                            updatedAt: "Oct 15, 2020 8:32:10 AM",
                            isActive: true,
                            isforapproval: false,
                            processing: false,
                            processed: false,
                            isapproved: false,
                            isRejected: false,
                            isAmmend: false,
                            createdBy: 46,
                            updatedBy: 46,
                        },
                        companyRegistratioNo: "C920932",
                        PIN: "P346634831A",
                        createdAt: "Nov 8, 2021 7:32:16 AM",
                        updatedAt: "Nov 8, 2021 7:32:16 AM",
                        isActive: true,
                        approvalStage: "Applicant Stage",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                    },
                    postalAddress: "P.O Box 7373",
                    postalCode: "00515",
                    buildingName: "",
                    streetName: "SN001",
                    plotNo: "",
                    Province: {
                        county_id: 235,
                        code: "BUNGOMA",
                        name: "BUNGOMA",
                        createdAt: "Jan 25, 2021 10:52:31 AM",
                        updatedAt: "Jan 25, 2021 10:52:31 AM",
                        isActive: true,
                        approvalStage: "Applicant Stage",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 46,
                        updatedBy: 46,
                    },
                    subCounty: {
                        subcounty_id: 501,
                        code: "BUMULA",
                        name: "BUMULA",
                        Province: {
                            county_id: 235,
                            code: "BUNGOMA",
                            name: "BUNGOMA",
                            createdAt: "Jan 25, 2021 10:52:31 AM",
                            updatedAt: "Jan 25, 2021 10:52:31 AM",
                            isActive: true,
                            approvalStage: "Applicant Stage",
                            isforapproval: false,
                            processing: false,
                            processed: false,
                            isapproved: false,
                            isRejected: false,
                            isAmmend: false,
                            createdBy: 46,
                            updatedBy: 46,
                        },
                        createdAt: "Jan 25, 2021 10:52:59 AM",
                        updatedAt: "Jan 25, 2021 10:52:59 AM",
                        isActive: true,
                        approvalStage: "Applicant Stage",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 46,
                        updatedBy: 46,
                    },
                    ward: {
                        ward_id: 807,
                        code: "KABULA",
                        name: "KABULA",
                        subCounty: {
                            subcounty_id: 501,
                            code: "BUMULA",
                            name: "BUMULA",
                            Province: {
                                county_id: 235,
                                code: "BUNGOMA",
                                name: "BUNGOMA",
                                createdAt: "Jan 25, 2021 10:52:31 AM",
                                updatedAt: "Jan 25, 2021 10:52:31 AM",
                                isActive: true,
                                approvalStage: "Applicant Stage",
                                isforapproval: false,
                                processing: false,
                                processed: false,
                                isapproved: false,
                                isRejected: false,
                                isAmmend: false,
                                createdBy: 46,
                                updatedBy: 46,
                            },
                            createdAt: "Jan 25, 2021 10:52:59 AM",
                            updatedAt: "Jan 25, 2021 10:52:59 AM",
                            isActive: true,
                            approvalStage: "Applicant Stage",
                            isforapproval: false,
                            processing: false,
                            processed: false,
                            isapproved: false,
                            isRejected: false,
                            isAmmend: false,
                            createdBy: 46,
                            updatedBy: 46,
                        },
                        createdAt: "Jan 25, 2021 10:53:45 AM",
                        updatedAt: "Jan 25, 2021 10:53:45 AM",
                        isActive: true,
                        approvalStage: "Applicant Stage",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 46,
                        updatedBy: 46,
                    },
                    city: "Nairobi",
                    location: "",
                    subLocation: "",
                    village: "",
                    createdAt: "Nov 8, 2021 7:32:17 AM",
                    updatedAt: "Nov 8, 2021 7:32:17 AM",
                    isActive: true,
                    approvalStage: "Applicant Stage",
                    isforapproval: false,
                    processing: false,
                    processed: false,
                    isapproved: false,
                    isRejected: false,
                    isAmmend: false,
                },
                user: {
                    users_id: 31168,
                    firstName: "John",
                    username: "chieni",
                    otherNames: "Doe",
                    lastName: "S",
                    password: "$2a$10$WVjRyainm53jKgVjP8WeWeQYjL22C0Cc5eekXYmKmMJ/MKh5sPbkK",
                    email: "pchieni25@mailinator.com",
                    phoneNo: "0721212121",
                    emailVerifyDate: "Nov 8, 2021 7:40:10 AM",
                    isLocked: false,
                    failedLoginCount: 0,
                    dateLastLogin: "Nov 8, 2021 7:40:10 AM",
                    isNoPasswordReset: false,
                    isExpired: false,
                    isSubAdmin: true,
                    securityQuestion: "Questions",
                    answer: "test",
                    department: {
                        department_id: 1,
                        code: "01",
                        name: "Default",
                        country: {
                            country_id: 1,
                            code: "KE",
                            name: "Kenya",
                            nationality: "Kenyan",
                            createdAt: "Jan 10, 2020 12:01:23 PM",
                            updatedAt: "Nov 26, 2020 1:54:26 PM",
                            isActive: true,
                            isforapproval: false,
                            processing: false,
                            processed: false,
                            isapproved: false,
                            isRejected: false,
                            isAmmend: false,
                            updatedBy: 46,
                        },
                        createdAt: "Oct 2, 2020 12:00:00 AM",
                        updatedAt: "Oct 2, 2020 12:00:00 AM",
                        isActive: true,
                        approvalStage: "Approval",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 0,
                        updatedBy: 0,
                    },
                    company: {
                        company_id: 4802,
                        code: "C920932",
                        name: "COMPANY TEST ONE",
                        email: "pchieni25@mailinator.com",
                        description: "company reg",
                        registrationDate: "Jan 1, 2020 12:00:00 AM",
                        entityType: {
                            entityType_id: 22,
                            code: "c1",
                            name: "Parastatal",
                            createdAt: "Oct 14, 2020 9:01:45 AM",
                            updatedAt: "Oct 15, 2020 8:32:10 AM",
                            isActive: true,
                            isforapproval: false,
                            processing: false,
                            processed: false,
                            isapproved: false,
                            isRejected: false,
                            isAmmend: false,
                            createdBy: 46,
                            updatedBy: 46,
                        },
                        companyRegistratioNo: "C920932",
                        PIN: "P346634831A",
                        createdAt: "Nov 8, 2021 7:32:16 AM",
                        updatedAt: "Nov 8, 2021 7:32:16 AM",
                        isActive: true,
                        approvalStage: "Applicant Stage",
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                    },
                    nationalIDNo: "23232323",
                    roles: [{
                        role_id: 701,
                        name: "New Registration",
                        roleName: "new_registration",
                        description: "New Registration",
                        code: "new_registration",
                        isInternal: true,
                        createdAt: "Dec 7, 2020 12:26:25 PM",
                        updatedAt: "Dec 7, 2020 12:26:25 PM",
                        isActive: true,
                        isforapproval: false,
                        processing: false,
                        processed: false,
                        isapproved: false,
                        isRejected: false,
                        isAmmend: false,
                        createdBy: 46,
                        updatedBy: 46,
                    }, ],
                    otp: "0",
                    createdAt: "Nov 8, 2021 7:32:16 AM",
                    updatedAt: "Nov 8, 2021 7:40:10 AM",
                    isActive: true,
                    approvalStage: "Applicant Stage",
                    isforapproval: false,
                    processing: false,
                    processed: false,
                    isapproved: false,
                    isRejected: false,
                    isAmmend: false,
                    updatedBy: 31168,
                },
                docStatus: {
                    docStatus_id: 47,
                    code: "DR",
                    name: "DRAFT",
                    createdAt: "Nov 30, 2020 12:00:00 AM",
                    updatedAt: "Nov 30, 2020 12:00:00 AM",
                    isActive: true,
                    approvalStage: "Applicant",
                    isforapproval: false,
                    processing: false,
                    processed: false,
                    isapproved: true,
                    isRejected: false,
                    isAmmend: false,
                    createdBy: 46,
                    updatedBy: 46,
                },
                createdAt: "Nov 8, 2021 12:06:51 PM",
                updatedAt: "Nov 8, 2021 12:06:51 PM",
                isActive: true,
                approvalStage: "Applicant Stage",
                isforapproval: false,
                processing: false,
                processed: false,
                isapproved: false,
                isRejected: false,
                isAmmend: false,
                createdBy: 31168,
                updatedBy: 31168,
            };
            controller.editRow(arrObj, this, "exporter");
        },

        renderCheckboxbuttonview: function(data, cell, row, formName) {
            var row = cell.getRow();
            var data = row.getData();
            buttonHolder = document.createElement("div");
            buttviewReceipt = document.createElement("input");
            buttviewReceipt.classList.add("btncheckbox");
            buttviewReceipt.classList.add("checkbox");
            buttviewReceipt.setAttribute("id", "checkboxbtn");

            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttviewReceipt.setAttribute("form-name", listFormName);
            buttviewReceipt.setAttribute("type", "checkbox");
            buttviewReceipt.addEventListener(
                "change",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        // SelectedData.push(data);
                        // viewReceiptattached(data);
                    }
                },
                false
            );

            var crudViewReceipt = true;
            try {
                crudViewReceipt = currentObj.crudViewReceipt;
                if (crudViewReceipt == undefined || crudViewReceipt == "undefined") {
                    crudViewReceipt = true;
                }
            } catch (e) {}

            if (crudViewReceipt) {
                buttonHolder.appendChild(buttviewReceipt);
            }

            var rnd = Math.random();
            var btn =
                '<button class="btn btn-default dropdown-toggle action-select"' +
                'type="button" id="dropdownMenu1' +
                rnd +
                '" data-toggle="dropdown"' +
                'aria-haspopup="true" aria-expanded="true"><span class="selectable-dots">...</span>' +
                '</button> <ul class = "dropdown-menu" aria-labelledby = "dropdownMenu1' +
                rnd +
                '" >' +
                '<li > < a href = "#" > Small < /a></li >' +
                '<li > < a href = "#" > Medium medium medium < /a></li >' +
                "<li > " +
                buttonHolder +
                "</li >" +
                '<li > < a href = "#" > Large large large large large large large large large < /a></li ></ul>';
            buttonSectionHolder = document.createElement("div");
            buttonDropDownBtn = document.createElement("button");
            buttonDropDownBtn.innerHTML = "<span class='selectable-dots'>...</span>";
            buttonDropDownBtn.classList.add("btn-default");
            buttonDropDownBtn.classList.add("btn");
            buttonDropDownBtn.classList.add("dropdown-toggle");
            buttonDropDownBtn.classList.add("action-list");
            buttonDropDownBtn.setAttribute("type", "button");
            buttonDropDownBtn.setAttribute("id", "dropdownMenu1" + rnd);
            buttonDropDownBtn.setAttribute("data-toggle", "dropdown");
            buttonDropDownBtn.setAttribute("aria-haspopup", "true");
            buttonDropDownBtn.setAttribute("aria-expanded", "false");
            dropDownParentList = document.createElement("ul");
            dropDownParentList.setAttribute("aria-labelledby", "dropdownMenu1" + rnd);
            dropDownParentList.classList.add("dropdown-menu");
            dropDownList = document.createElement("li");
            dropDownList.appendChild(buttonHolder);
            dropDownParentList.appendChild(dropDownList);
            buttonSectionHolder.appendChild(buttonDropDownBtn);
            buttonSectionHolder.appendChild(dropDownParentList);
            buttonDropDownBtn.addEventListener("click", function(event) {}, true);
            return buttonHolder;
        },

        renderAccountantApprovalButtons: function(data, cell, row, formName) {
            var row = cell.getRow();
            var data = row.getData();
            buttonHolder = document.createElement("div");
            buttviewReceipt = document.createElement("button");
            buttviewReceipt.innerHTML = "<i class='fa fa-eye''></i>View Payments";
            buttviewReceipt.classList.add("xcrud-action");
            buttviewReceipt.classList.add("btn");
            buttviewReceipt.classList.add("btn-info");
            buttviewReceipt.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttviewReceipt.setAttribute("form-name", listFormName);
            buttviewReceipt.setAttribute("type", "button");
            buttviewReceipt.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        allFormObj["highestAccessedTab"] = 0;
                        viewReceiptattached(data);
                    }
                },
                false
            );

            var crudViewReceipt = true;
            try {
                crudViewReceipt = currentObj.crudViewReceipt;
                if (crudViewReceipt == undefined || crudViewReceipt == "undefined") {
                    crudViewReceipt = true;
                }
            } catch (e) {}

            if (crudViewReceipt) {
                buttonHolder.appendChild(buttviewReceipt);
            }

            var rnd = Math.random();
            var btn =
                '<button class="btn btn-default dropdown-toggle action-select"' +
                'type="button" id="dropdownMenu1' +
                rnd +
                '" data-toggle="dropdown"' +
                'aria-haspopup="true" aria-expanded="true"><span class="selectable-dots">...</span>' +
                '</button> <ul class = "dropdown-menu" aria-labelledby = "dropdownMenu1' +
                rnd +
                '" >' +
                '<li > < a href = "#" > Small < /a></li >' +
                '<li > < a href = "#" > Medium medium medium < /a></li >' +
                "<li > " +
                buttonHolder +
                "</li >" +
                '<li > < a href = "#" > Large large large large large large large large large < /a></li ></ul>';
            buttonSectionHolder = document.createElement("div");
            buttonDropDownBtn = document.createElement("button");
            buttonDropDownBtn.innerHTML = "<span class='selectable-dots'>...</span>";
            buttonDropDownBtn.classList.add("btn-default");
            buttonDropDownBtn.classList.add("btn");
            buttonDropDownBtn.classList.add("dropdown-toggle");
            buttonDropDownBtn.classList.add("action-list");
            buttonDropDownBtn.setAttribute("type", "button");
            buttonDropDownBtn.setAttribute("id", "dropdownMenu1" + rnd);
            buttonDropDownBtn.setAttribute("data-toggle", "dropdown");
            buttonDropDownBtn.setAttribute("aria-haspopup", "true");
            buttonDropDownBtn.setAttribute("aria-expanded", "false");
            dropDownParentList = document.createElement("ul");
            dropDownParentList.setAttribute("aria-labelledby", "dropdownMenu1" + rnd);
            dropDownParentList.classList.add("dropdown-menu");
            dropDownList = document.createElement("li");
            dropDownList.appendChild(buttonHolder);
            dropDownParentList.appendChild(dropDownList);
            buttonSectionHolder.appendChild(buttonDropDownBtn);
            buttonSectionHolder.appendChild(dropDownParentList);
            buttonDropDownBtn.addEventListener("click", function(event) {}, true);
            return buttonHolder;
        },

        renderListButtons: function(data, cell, row, formName) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            if (btnType == "edit") {
                btnTitle = "Edit";
            } else if (btnType == "delete") {
                btnTitle = "Delete";
            } else if (btnType == "activate") {
                btnTitle = "Activate";
            }
            buttonHolder = document.createElement("div");
            buttonEdit = document.createElement("button");
            buttonEdit.innerHTML = "<i class='fa fa-edit'></i>Edit";
            buttonEdit.classList.add("xcrud-action");
            buttonEdit.classList.add("btn-edit");
            buttonEdit.classList.add("btn");
            buttonEdit.classList.add("btn-warning");
            buttonEdit.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonEdit.setAttribute("form-name", listFormName);
            buttonEdit.setAttribute("type", "button");
            buttonEdit.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    controller.editRow(data, this);

                    // editRecord(data, this);
                },
                false
            );

            custombuttonEdit = document.createElement("button");
            custombuttonEdit.innerHTML = "<i class='fa fa-edit'></i>Edit";
            custombuttonEdit.classList.add("xcrud-action");
            custombuttonEdit.classList.add("btn-edit");
            custombuttonEdit.classList.add("btn");
            custombuttonEdit.classList.add("btn-warning");
            custombuttonEdit.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            custombuttonEdit.setAttribute("form-name", listFormName);
            custombuttonEdit.setAttribute("type", "button");
            custombuttonEdit.addEventListener(
                "click",
                function() {
                    // controller.editRow(data, this);
                    editRecord(data, this);
                    isEditOnly = true;
                    $(".crud_section_lines").hide();
                },
                false
            );

            custombuttonEdit_2 = document.createElement("button");
            custombuttonEdit_2.innerHTML = "<i class='fa fa-edit'></i>Edit";
            custombuttonEdit_2.classList.add("xcrud-action");
            custombuttonEdit_2.classList.add("btn-edit");
            custombuttonEdit_2.classList.add("btn");
            custombuttonEdit_2.classList.add("btn-warning");
            custombuttonEdit_2.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            custombuttonEdit_2.setAttribute("form-name", listFormName);
            custombuttonEdit_2.setAttribute("type", "button");
            custombuttonEdit_2.addEventListener(
                "click",
                function() {
                    // controller.editRow(data, this);
                    editRecord_section_2(data, listFormName);
                    isEditOnly = true;
                    try {
                        setTimeout(function() {
                            $(".crud_section_lines").hide();
                        }, 100);
                    } catch (error) {}
                },
                false
            );

            buttonviewLabReason = document.createElement("button");
            buttonviewLabReason.innerHTML = "<i class='fa fa-eye''></i> View Reason";
            buttonviewLabReason.classList.add("xcrud-action");
            buttonviewLabReason.classList.add("btn");
            buttonviewLabReason.classList.add("btn-info");
            buttonviewLabReason.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewLabReason.setAttribute("form-name", listFormName);
            buttonviewLabReason.setAttribute("type", "button");
            buttonviewLabReason.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        $(".modal.fade.crudlabreason").modal("show");
                        document.getElementById("labreasonrremarks").value = data.reason;
                        $("#crudlabreasonbtn").click(function(event) {
                            $(".modal.fade.crudlabreason").modal("hide");
                        });
                    }
                },
                false
            );

            buttonvoidApplication = document.createElement("button");
            buttonvoidApplication.innerHTML =
                "<i class='fa fa-edit''></i> Void Application";
            buttonvoidApplication.classList.add("xcrud-action");
            buttonvoidApplication.classList.add("btn");
            buttonvoidApplication.classList.add("btn-danger");
            buttonvoidApplication.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonvoidApplication.setAttribute("form-name", listFormName);
            buttonvoidApplication.setAttribute("type", "button");
            buttonvoidApplication.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        voidApplicationRecord(data);
                    }
                },
                false
            );

            buttonNegotiateApplication = document.createElement("button");
            buttonNegotiateApplication.innerHTML =
                "<i class='fa fa-edit''></i>Activate";
            buttonNegotiateApplication.classList.add("xcrud-action");
            buttonNegotiateApplication.classList.add("btn");
            buttonNegotiateApplication.classList.add("btn-success");
            buttonNegotiateApplication.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonNegotiateApplication.setAttribute("form-name", listFormName);
            buttonNegotiateApplication.setAttribute("type", "button");
            buttonNegotiateApplication.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        createNegotiated(data);
                    }
                },
                false
            );

            buttonremoveNegotiateApplication = document.createElement("button");
            buttonremoveNegotiateApplication.innerHTML =
                "<i class='fa fa-edit''></i>Deactivate";
            buttonremoveNegotiateApplication.classList.add("xcrud-action");
            buttonremoveNegotiateApplication.classList.add("btn");
            buttonremoveNegotiateApplication.classList.add("btn-danger");
            buttonremoveNegotiateApplication.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonremoveNegotiateApplication.setAttribute("form-name", listFormName);
            buttonremoveNegotiateApplication.setAttribute("type", "button");
            buttonremoveNegotiateApplication.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        removecreateNegotiated(data);
                    }
                },
                false
            );

            buttonUpdateDate = document.createElement("button");
            buttonUpdateDate.innerHTML =
                "<i class='fa fa-edit''></i>Update Validity Date";
            buttonUpdateDate.classList.add("xcrud-action");
            buttonUpdateDate.classList.add("btn");
            buttonUpdateDate.classList.add("btn-success");
            buttonUpdateDate.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonUpdateDate.setAttribute("form-name", listFormName);
            buttonUpdateDate.setAttribute("type", "button");
            buttonUpdateDate.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (!event.detail || event.detail == 1) {
                            viewRowData(data, listFormName);

                            // if (booleanView == true) {
                            //     $(".crudheader_section").show();
                            // } else {
                            //     if (data.status == "INSPECTED AND PASSED") {
                            //         $(".crudheader_section").show();
                            //     } else if (data.status == "PENDING") {
                            //         $(".crudheader_section").show();
                            //     } else {
                            //         $(".crudheader_section").show();
                            //     }
                            // }
                            // $(".backbtn").show();
                            // inspectionrecords.push(data);
                            // var formObj = allFormObj.lines;
                            // formObj.listUrl = serverURL + "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" + data.inspectionHeaderID;
                            // controller.renderCRUDForm("crudsection_view_inspections", formObj, function() {

                            // });
                        }
                    }
                },
                false
            );

            buttonView = document.createElement("button");
            buttonView.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonView.classList.add("xcrud-action");
            buttonView.classList.add("btn");
            buttonView.classList.add("btn-info");
            buttonView.classList.add("btn-sm");
            buttonView.setAttribute("id", "buttonView");

            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonView.setAttribute("form-name", listFormName);
            buttonView.setAttribute("type", "button");
            buttonView.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    controller.viewRow(data, this);
                },
                false
            );

            buttonCopyRecord = document.createElement("button");
            buttonCopyRecord.innerHTML = "<i class='fa fa-view'></i> Clone";
            buttonCopyRecord.classList.add("xcrud-action");
            buttonCopyRecord.classList.add("btn");
            buttonCopyRecord.classList.add("btn-info");
            buttonCopyRecord.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonCopyRecord.setAttribute("form-name", listFormName);
            buttonCopyRecord.setAttribute("type", "button");
            buttonCopyRecord.addEventListener(
                "click",
                function() {
                    controller.copyRecord(data);
                },
                false
            );

            buttonSubmitPipApplicatiinRequest = document.createElement("button");
            buttonSubmitPipApplicatiinRequest.innerHTML =
                "<i class='fa fa-view'></i>Generate PIP";
            buttonSubmitPipApplicatiinRequest.classList.add("xcrud-action");
            buttonSubmitPipApplicatiinRequest.classList.add("btn");
            buttonSubmitPipApplicatiinRequest.classList.add("btn-success");
            buttonSubmitPipApplicatiinRequest.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonSubmitPipApplicatiinRequest.setAttribute("form-name", listFormName);
            buttonSubmitPipApplicatiinRequest.setAttribute("type", "button");
            buttonSubmitPipApplicatiinRequest.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.submitPipApplicationRecord(data);
                    }
                },
                false
            );
            buttonDelete = document.createElement("button");
            buttonDelete.innerHTML = "<i class='fa fa-trash'></i> Delete";
            buttonDelete.classList.add("xcrud-action");
            buttonDelete.classList.add("btn");
            buttonDelete.classList.add("btn-danger");
            buttonDelete.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDelete.setAttribute("form-name", listFormName);
            buttonDelete.setAttribute("type", "button");
            buttonDelete.addEventListener(
                "click",
                function() {
                    $("#myModal").modal("show");
                    $("#confirmdelete").click(function(event) {
                        event.stopImmediatePropagation();
                        event.stopPropagation();
                        event.preventDefault();
                        $("#myModal").modal("hide");
                        controller.deleteRecord(data);
                    });
                },
                false
            );

            buttonRecordDeactivate = document.createElement("button");
            buttonRecordDeactivate.innerHTML =
                "<i class='fa fa-window-close-o'></i> Deactivate";
            buttonRecordDeactivate.classList.add("xcrud-action");
            buttonRecordDeactivate.classList.add("btn");
            buttonRecordDeactivate.classList.add("btn-danger");
            buttonRecordDeactivate.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonRecordDeactivate.setAttribute("form-name", listFormName);
            buttonRecordDeactivate.setAttribute("type", "button");
            buttonRecordDeactivate.addEventListener(
                "click",
                function() {
                    $("#myModal").modal("show");
                    $("#confirmdelete").click(function(event) {
                        event.stopImmediatePropagation();
                        event.stopPropagation();
                        event.preventDefault();
                        $("#myModal").modal("hide");
                        controller.deleteRecord(data);
                    });
                },
                false
            );

            buttonDeleteformobj2 = document.createElement("button");
            buttonDeleteformobj2.innerHTML = "<i class='fa fa-trash'></i> Delete";
            buttonDeleteformobj2.classList.add("xcrud-action");
            buttonDeleteformobj2.classList.add("btn");
            buttonDeleteformobj2.classList.add("btn-danger");
            buttonDeleteformobj2.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDeleteformobj2.setAttribute("form-name", listFormName);
            buttonDeleteformobj2.setAttribute("type", "button");
            buttonDeleteformobj2.addEventListener(
                "click",
                function() {
                    $("#myModal").modal("show");
                    $("#confirmdelete").click(function(event) {
                        event.stopImmediatePropagation();
                        event.stopPropagation();
                        event.preventDefault();
                        $("#myModal").modal("hide");
                        controller.deleteRecordFormObj2(data);
                    });
                },
                false
            );

            buttonDeleteRecords = document.createElement("button");
            buttonDeleteRecords.innerHTML = "<i class='fa fa-trash'></i> Deactivate";
            buttonDeleteRecords.classList.add("xcrud-action");
            buttonDeleteRecords.classList.add("btn");
            buttonDeleteRecords.classList.add("btn-danger");
            buttonDeleteRecords.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDeleteRecords.setAttribute("form-name", listFormName);
            buttonDeleteRecords.setAttribute("type", "button");
            buttonDeleteRecords.addEventListener(
                "click",
                function() {
                    $("#myModal").modal("show");
                    $("#confirmdelete").click(function(event) {
                        event.stopImmediatePropagation();
                        event.stopPropagation();
                        event.preventDefault();
                        $("#myModal").modal("hide");
                        deleteRecordByID(data, listFormName);
                    });
                },
                false
            );

            buttonRejectionView = document.createElement("button");
            buttonRejectionView.innerHTML = "<i class='fa fa-view'></i> Reason";
            buttonRejectionView.classList.add("xcrud-action");
            buttonRejectionView.classList.add("btn");
            buttonRejectionView.classList.add("btn-info");
            buttonRejectionView.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonRejectionView.setAttribute("form-name", listFormName);
            buttonRejectionView.setAttribute("type", "button");
            buttonRejectionView.addEventListener(
                "click",
                function() {
                    $("#rejectionreason").modal("show");
                    try {
                        if (data.exporterConsignmentID) {
                            var url =
                                serverURL +
                                "workflowActivity/findActiveByTableAndRecordID?recordID=" +
                                data.exporterConsignmentID +
                                "&tableID=154";
                            workflow.getActivity(url, "", function(output) {
                                for (let i = 0; i < output.length; i++) {
                                    $("#rejectionReason").val(output[i].previousRemarks);
                                }
                            });
                            $("#rejectionreasonbtn").click(function(event) {
                                $("#rejectionreason").modal("hide");
                            });
                        } else if (data.pipApplicationID) {
                            var url =
                                serverURL +
                                "workflowActivity/findActiveByTableAndRecordID?recordID=" +
                                data.pipApplicationID +
                                "&tableID=91";
                            workflow.getActivity(url, "", function(output) {
                                for (let i = 0; i < output.length; i++) {
                                    $("#rejectionReason").val(output[i].previousRemarks);
                                }
                            });
                            $("#rejectionreasonbtn").click(function(event) {
                                $("#rejectionreason").modal("hide");
                            });
                        } else if (data.consignmentInspectionRequestID) {
                            var url =
                                serverURL +
                                "workflowActivity/findActiveByTableAndRecordID?recordID=" +
                                data.consignmentInspectionRequestID +
                                "&tableID=185";
                            workflow.getActivity(url, "", function(output) {
                                for (let i = 0; i < output.length; i++) {
                                    $("#rejectionReason").val(output[i].previousRemarks);
                                }
                            });
                            $("#rejectionreasonbtn").click(function(event) {
                                $("#rejectionreason").modal("hide");
                            });
                        } else if (data.users_id) {
                            $("#rejectionReason").val(data.blockedReason);
                            $("#rejectionreasonbtn").click(function(event) {
                                $("#rejectionreason").modal("hide");
                            });
                        }
                    } catch (error) {}
                },
                false
            );

            buttonMenuDelete = document.createElement("button");
            buttonMenuDelete.innerHTML = "<i class='fa fa-trash></i> Delete Menu";
            buttonMenuDelete.classList.add("xcrud-action");
            buttonMenuDelete.classList.add("btn");
            buttonMenuDelete.classList.add("btn-danger");
            buttonMenuDelete.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonMenuDelete.setAttribute("form-name", listFormName);
            buttonMenuDelete.setAttribute("type", "button");
            buttonMenuDelete.addEventListener(
                "click",
                function() {
                    $("#myModal").modal("show");
                    $("#confirmdelete").click(function(event) {
                        event.stopImmediatePropagation();
                        event.stopPropagation();
                        event.preventDefault();
                        $("#myModal").modal("hide");
                        deletemenurecord(data);
                    });
                },
                false
            );

            buttonDeactivateRequirement = document.createElement("button");
            buttonDeactivateRequirement.innerHTML =
                "<i class='fa fa-window-close-o'></i> Deactivate";
            buttonDeactivateRequirement.classList.add("xcrud-action");
            buttonDeactivateRequirement.classList.add("btn");
            buttonDeactivateRequirement.classList.add("btn-danger");
            buttonDeactivateRequirement.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDeactivateRequirement.setAttribute("form-name", listFormName);
            buttonDeactivateRequirement.setAttribute("type", "button");
            buttonDeactivateRequirement.addEventListener(
                "click",
                function() {
                    controller.deactivateRecords(data);
                },
                false
            );
            buttonaddPhytoProducts = document.createElement("button");
            buttonaddPhytoProducts.innerHTML =
                "Add Commodity<i class='icon-arrow-right'></i>";
            buttonaddPhytoProducts.classList.add("xcrud-action");
            buttonaddPhytoProducts.classList.add("btn");
            buttonaddPhytoProducts.classList.add("btn-danger");
            buttonaddPhytoProducts.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonaddPhytoProducts.setAttribute("form-name", listFormName);
            buttonaddPhytoProducts.setAttribute("type", "button");
            buttonaddPhytoProducts.addEventListener("click", function() {}, false);
            buttonDraftPhyto = document.createElement("button");
            buttonDraftPhyto.innerHTML = "Print Draft";
            buttonDraftPhyto.classList.add("xcrud-action");
            buttonDraftPhyto.classList.add("btn");
            buttonDraftPhyto.classList.add("btn-warning");
            buttonDraftPhyto.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDraftPhyto.setAttribute("form-name", listFormName);
            buttonDraftPhyto.setAttribute("type", "button");
            buttonDraftPhyto.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.signPrintDraft("samplePhyto", data, 1);
                    }
                },
                false
            );
            buttonDraftPrintpip = document.createElement("button");
            buttonDraftPrintpip.innerHTML = "Print PIP Replacement";
            buttonDraftPrintpip.classList.add("xcrud-action");
            buttonDraftPrintpip.classList.add("btn");
            buttonDraftPrintpip.classList.add("btn-success");
            buttonDraftPrintpip.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDraftPrintpip.setAttribute("form-name", listFormName);
            buttonDraftPrintpip.setAttribute("type", "button");
            buttonDraftPrintpip.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.assignedPrinting("pip");
                    }
                },
                false
            );
            buttonDraftPIP = document.createElement("button");
            buttonDraftPIP.innerHTML = "Print Draft";
            buttonDraftPIP.classList.add("xcrud-action");
            buttonDraftPIP.classList.add("btn");
            buttonDraftPIP.classList.add("btn-warning");
            buttonDraftPIP.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDraftPIP.setAttribute("form-name", listFormName);
            buttonDraftPIP.setAttribute("type", "button");
            buttonDraftPIP.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.signPiPPrintDraft("pipPreview", data, 1);
                    }
                },
                false
            );
            buttonPrintInterception = document.createElement("button");
            buttonPrintInterception.innerHTML = "Print Report";
            buttonPrintInterception.classList.add("xcrud-action");
            buttonPrintInterception.classList.add("btn");
            buttonPrintInterception.classList.add("btn-warning");
            buttonPrintInterception.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonPrintInterception.setAttribute("form-name", listFormName);
            buttonPrintInterception.setAttribute("type", "button");
            buttonPrintInterception.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        controller.printInterceptionReport("interceptionReport", data, 1);
                    }
                },
                false
            );
            buttonDeactivate = document.createElement("button");
            buttonDeactivate.innerHTML = "<i class='fa fa-edit'></i> Block";
            buttonDeactivate.classList.add("xcrud-action");
            buttonDeactivate.classList.add("btn");
            buttonDeactivate.classList.add("btn-info");
            buttonDeactivate.classList.add("btn-sm");
            buttonDeactivate.classList.add("deactivate");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDeactivate.setAttribute("form-name", listFormName);
            buttonDeactivate.setAttribute("type", "button");
            buttonDeactivate.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        document.getElementById("deactivatedUser").innerHTML = data.firstName;
                        $(".modal.fade.deactivateConfirm").modal("show");
                        $("#deactivateConfirmBtn").click(function() {
                            var admreason = document.getElementById("admreason").value;
                            $(".modal.fade.deactivateConfirm").modal("hide");
                            controller.deactivate(data, admreason);
                        });
                        $("#modal-btn-no").click(function() {
                            $(".modal.fade.deactivateConfirm").modal("hide");
                        });
                    }
                },
                false
            );
            buttonRequiresLab = document.createElement("button");
            buttonRequiresLab.innerHTML =
                "Requires Lab<i class='icon-arrow-right'></i>";
            buttonRequiresLab.classList.add("xcrud-action");
            buttonRequiresLab.classList.add("btn");
            buttonRequiresLab.classList.add("btn-success");
            buttonRequiresLab.classList.add("btn-sm");
            buttonRequiresLab.classList.add("addregion");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonRequiresLab.setAttribute("form-name", listFormName);
            buttonRequiresLab.setAttribute("type", "button");
            buttonRequiresLab.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.getofficeLocation();
                        $(".modal.fade.requiresLab").modal("show");
                        try {
                            var expoexporterconsinmentid =
                                allFormObj["parent_selected"]["consignmentInspectionRequestID"];
                        } catch (error) {}
                        var exporterConID = localStorage.setItem(
                            "exporterConsignmentID",
                            expoexporterconsinmentid
                        );
                        $("#requiresSamplingbtn").click(function(event) {
                            event.stopImmediatePropagation();
                            event.stopPropagation();
                            event.preventDefault();
                            var expoexporterconsinmentid = 206;
                            var office_location_id =
                                document.getElementById("office_location_ID").value;
                            var labreason = document.getElementById("labreason").value;
                            if (labreason == null || labreason == "") {
                                controller.showToastMsg("Fill all Fields to Proceed", "#ff6666");
                            } else {
                                $(".modal.fade.requiresLab").modal("hide");
                                controller.createLabData(
                                    data,
                                    expoexporterconsinmentid,
                                    office_location_id,
                                    labreason
                                );
                            }
                        });
                    }
                },
                false
            );
            buttonRequiresSampling = document.createElement("button");
            buttonRequiresSampling.innerHTML =
                "Requires Sampling<i class='icon-arrow-right'></i>";
            buttonRequiresSampling.classList.add("xcrud-action");
            buttonRequiresSampling.classList.add("btn");
            buttonRequiresSampling.classList.add("btn-warning");
            buttonRequiresSampling.classList.add("btn-sm");
            buttonRequiresSampling.classList.add("addregion");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonRequiresSampling.setAttribute("form-name", listFormName);
            buttonRequiresSampling.setAttribute("type", "button");
            buttonRequiresSampling.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        $(".modal.fade.requirequiressampling").modal("show");
                        $("#samplingsubmitbtn").click(function(event) {
                            event.stopImmediatePropagation();
                            event.stopPropagation();
                            event.preventDefault();
                            var noOfSamples = document.getElementById("noOfSamples").value;
                            var samplingreason =
                                document.getElementById("samplingreason").value;
                            if (
                                noOfSamples == null ||
                                (noOfSamples == "" && samplingreason == null) ||
                                samplingreason == ""
                            ) {
                                controller.showToastMsg("Fill all Fields to Proceed", "#ff6666");
                            } else {
                                $(".modal.fade.requirequiressampling").modal("hide");
                                controller.createsamplingAnalysis(
                                    data,
                                    noOfSamples,
                                    samplingreason
                                );
                            }
                        });
                    }
                },
                false
            );
            buttonSubmitPrint = document.createElement("button");
            buttonSubmitPrint.innerHTML = "<i class='icon-arrow-right'></i>Print";
            buttonSubmitPrint.classList.add("xcrud-action");
            buttonSubmitPrint.classList.add("btn");
            buttonSubmitPrint.setAttribute("type", "button");
            buttonSubmitPrint.classList.add("btn-warning");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonSubmitPrint.setAttribute("form-name", listFormName);
            buttonSubmitPrint.classList.add("btn-sm");
            buttonSubmitPrint.classList.add("submitprint");
            buttonSubmitPrint.addEventListener(
                "click",
                function(event) {
                    controller.submitprint(data, listFormName);
                },
                false
            );

            buttonSubmitDraftPrint = document.createElement("button");
            buttonSubmitDraftPrint.innerHTML =
                "<i class='icon-arrow-right'></i>Print Draft";
            buttonSubmitDraftPrint.classList.add("xcrud-action");
            buttonSubmitDraftPrint.classList.add("btn");
            buttonSubmitDraftPrint.setAttribute("type", "button");
            buttonSubmitDraftPrint.classList.add("btn-warning");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonSubmitDraftPrint.setAttribute("form-name", listFormName);
            buttonSubmitDraftPrint.classList.add("btn-sm");
            buttonSubmitDraftPrint.classList.add("submitprint");
            buttonSubmitDraftPrint.addEventListener(
                "click",
                function(event) {
                    controller.submitDraftprint(data, listFormName);
                },
                false
            );

            buttonActivate = document.createElement("button");
            buttonActivate.innerHTML = "<i class='fa fa-edit'></i> Unblock";
            buttonActivate.classList.add("xcrud-action");
            buttonActivate.classList.add("btn");
            buttonActivate.classList.add("btn-info");
            buttonActivate.classList.add("btn-sm");
            buttonActivate.classList.add("activate");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonActivate.setAttribute("form-name", listFormName);
            buttonActivate.setAttribute("type", "button");
            buttonActivate.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        document.getElementById("deactivatedUser").innerHTML = data.firstName;
                        $(".modal.fade.activateConfirm").modal("show");
                        $("#activateConfirmBtn").click(function() {
                            var admreason = document.getElementById("admreason").value;
                            $(".modal.fade.activateConfirm").modal("hide");
                            controller.activateUser(data);
                        });
                        $("#modal-btn-no").click(function() {
                            $(".modal.fade.activateConfirm").modal("hide");
                        });
                    }
                },
                false
            );
            buttonActivateRequirements = document.createElement("button");
            buttonActivateRequirements.innerHTML =
                "<i class='fa fa-edit'></i> Activate";
            buttonActivateRequirements.classList.add("xcrud-action");
            buttonActivateRequirements.classList.add("btn");
            buttonActivateRequirements.classList.add("btn-info");
            buttonActivateRequirements.classList.add("btn-sm");
            buttonActivateRequirements.classList.add("activate");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonActivateRequirements.setAttribute("form-name", listFormName);
            buttonActivateRequirements.setAttribute("type", "button");
            buttonActivateRequirements.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        if (data.import_requirement_id) {
                            controller.activateImportRequirements(data);
                        } else if (data.regionCounty_id) {
                            controller.activateregionCounty(data);
                        } else if (data.office_location_id) {
                            controller.activateoffice(data);
                        } else if (data.regionID) {
                            controller.activateregion(data);
                        } else if (data.hs_code_id) {
                            controller.activatehscode(data);
                        } else if (data.licensingBodyID) {
                            controller.activatelicencsingbody(data);
                        } else if (data.import_condition_id) {
                            controller.activateImportCondition(data);
                        } else if (data.researchInstituteID) {
                            controller.activateresearchInstitute(data);
                        } else if (data.certificate_type_id) {
                            controller.activatecertificatetype(data);
                        } else if (data.agent_mgt_id) {
                            controller.activateagent(data);
                        } else if (data.consigneeID) {
                            controller.activateconsignee(data);
                        } else if (data.products_id) {
                            activatecommodity(data);
                        } else if (data.wfWorkflow_id) {
                            controller.activateworkflow(data);
                        }
                    }
                },
                false
            );
            buttonpaymentBtn = document.createElement("button");
            buttonpaymentBtn.innerHTML = "<i class='icon-arrow-right'></i> Pay";
            buttonpaymentBtn.classList.add("xcrud-action");
            buttonpaymentBtn.classList.add("btn");
            buttonpaymentBtn.setAttribute("type", "button");
            buttonpaymentBtn.classList.add("btn-success");
            buttonpaymentBtn.classList.add("btn-sm");
            buttonpaymentBtn.classList.add("pay");
            buttonpaymentBtn.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        controller.show_progress();
                        $(".paymentInitiator").modal("show");
                        $("#proceedPay").click(function() {
                            controller.requestWithToken(url, function(data, status) {
                                var formJson = $("#paymentInitiator").serializeObject();
                                var phoneNumber = formJson.phoneNumber;
                                if (phoneNumber == "") {
                                    controller.showToastMsg(
                                        "Kindly enter your payment number",
                                        "#ff6666"
                                    );
                                } else {
                                    var url =
                                        serverURL +
                                        "api/mpesa/STKPush?recordID=" +
                                        recordID +
                                        "&phoneNumber=" +
                                        phoneNumber +
                                        "";
                                    var async_status = true;
                                    controller.request(
                                        url,
                                        "",
                                        async_status,
                                        function(data, status) {
                                            if (!status) {
                                                controller.showToastMsg("Payment failed", "#ff6666");
                                                controller.refreshCrudTables();
                                            } else {
                                                controller.showToastMsg("Payment Successful", "#1a5589");
                                                controller.refreshCrudTables();
                                            }
                                        }
                                    );
                                }
                            });
                        });
                    }
                },
                false
            );
            var forwardTitle = "";
            try {
                forwardTitle = currentObj.forwardTitle;
                if (forwardTitle == undefined || forwardTitle == "undefined") {
                    forwardTitle = "Forward for Approval";
                }
            } catch (e) {}

            buttonForward = document.createElement("button");
            //Checks the form name
            if (this.myFormObj.formName == "lab_analysis") {
                buttonForward.innerHTML =
                    "<i class='icon-arrow-right'></i>Forward to Lab";
            } else if (this.myFormObj.formName == "pestRiskAnalysisRequest") {
                buttonForward.innerHTML =
                    "<i class='icon-arrow-right'></i>Forward to Content Manager";
            } else {
                buttonForward.innerHTML = "<i class='icon-arrow-right'></i>Submit";
            }
            buttonForward.classList.add("xcrud-action");
            buttonForward.classList.add("btn");
            buttonForward.setAttribute("type", "button");
            buttonForward.classList.add("btn-success");
            buttonForward.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonForward.setAttribute("form-name", listFormName);
            buttonForward.classList.add("forward_for_approval");
            buttonForward.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    document
                        .getElementsByClassName("forward_for_approval")[0]
                        .setAttribute("disabled", true);
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        if (!clicked) {
                            clicked = true;
                            controller.startWorkflowEntity(data, formName);
                            setTimeout(function() {
                                clicked = false;
                                $(".forward_for_approval").html("Submit");
                                controller.refreshCrudTables();
                            }, 1000);
                        } else {
                            $(".forward_for_approval").html("Submit");
                        }
                    } else {
                        $(".forward_for_approval").html("Submit");
                    }
                },
                false
            );

            //pip Application Requests
            buttonPipForward = document.createElement("button");
            //Checks the form name
            buttonPipForward.innerHTML = "<i class='icon-arrow-right'></i>Submit";
            buttonPipForward.classList.add("xcrud-action");
            buttonPipForward.classList.add("btn");
            buttonPipForward.setAttribute("type", "button");
            buttonPipForward.classList.add("btn-success");
            buttonPipForward.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonPipForward.setAttribute("form-name", listFormName);
            buttonPipForward.classList.add("forward_for_approval");
            buttonPipForward.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    document
                        .getElementsByClassName("forward_for_approval")[0]
                        .setAttribute("disabled", false);
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        startWorkflowEntity(data, formName);
                        setTimeout(function() {
                            document
                                .getElementsByClassName("forward_for_approval")[0]
                                .setAttribute("disabled", false);
                        }, 2000);
                    } else {}
                },
                false
            );

            btnretract = document.createElement("button");
            btnretract.innerHTML = "<i class='fa fa-eye''></i> Retract";
            btnretract.classList.add("xcrud-action");
            btnretract.classList.add("btn");
            btnretract.classList.add("btn-warning");
            btnretract.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj9.formName;
            } else {
                listFormName = formName;
            }
            btnretract.setAttribute("form-name", listFormName);
            btnretract.setAttribute("type", "button");
            btnretract.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        retractDocument(data);
                    }
                },
                false
            );
            buttonReject = document.createElement("button");
            buttonReject.setAttribute("form-name", listFormName);
            buttonReject.setAttribute("type", "button");
            buttonReject.innerHTML = "<i class='icon-arrow-right'></i> Reject";
            buttonReject.classList.add("xcrud-action");
            buttonReject.classList.add("btn");
            buttonReject.classList.add("btn-warning");
            buttonReject.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonReject.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        SelectedData.push(data);
                        document.getElementsByClassName("reject_forwardMany")[0].id =
                            "reject";
                        $("#requireaudit").hide();
                        if (listFormName == "printout_replacement") {
                            document
                                .getElementsByClassName("reject_forwardMany")[0]
                                .setAttribute("form-name", "assignPhytoReplacement");
                        } else {
                            document
                                .getElementsByClassName("reject_forwardMany")[0]
                                .setAttribute("form-name", listFormName);
                        }
                        if (
                            listFormName == "assignPhytoInspections" ||
                            listFormName == "assignedPhytoInspections"
                        ) {
                            $(".modal.fade.reject_Confirm_Many_form").modal("show");
                            $("#requireaudit").show();
                            $("#proposedInspectionDatediv").hide();
                            $("#requiresfarmaudit").change(function() {
                                var value = $("#requiresfarmaudit :selected").attr("value");
                                if (value == true || value == "true") {
                                    $("#proposedInspectionDatediv").show();
                                } else {
                                    document.getElementById("proposedInspectionDatediv").value = "";
                                    $("#proposedInspectionDatediv").hide();
                                }
                            });
                        } else {
                            $("#requiresfarmauditdiv").hide();
                            if (listFormName == "assignConsignmentInspection") {
                                $(".modal.fade.reject_Confirm_Many_form").modal("show");
                                document.getElementById("interceptionreasonremarks").innerText =
                                    "Reason For Interception";
                            } else {
                                document.getElementById("interceptionreasonremarks").innerText =
                                    "Remarks";
                                $(".modal.fade.reject_Confirm_Many_form").modal("show");
                            }
                        }
                    }
                },
                false
            );
            buttonPostReleaseReject = document.createElement("button");
            buttonPostReleaseReject.setAttribute("form-name", listFormName);
            buttonPostReleaseReject.setAttribute("type", "button");
            buttonPostReleaseReject.innerHTML =
                "<i class='icon-arrow-right'></i> Reject";
            buttonPostReleaseReject.classList.add("xcrud-action");
            buttonPostReleaseReject.classList.add("btn");
            buttonPostReleaseReject.classList.add("btn-warning");
            buttonPostReleaseReject.classList.add("btn-sm");
            buttonPostReleaseReject.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        document.getElementsByClassName("postreleaseform")[0].id = "reject";
                        document
                            .getElementsByClassName("postreleaseform")[0]
                            .setAttribute("form-name", listFormName);
                        $(".modal.fade.approve_post_release_form").modal("show");
                    }
                },
                false
            );
            buttonPostReleaseNextDate = document.createElement("button");
            buttonPostReleaseNextDate.setAttribute("form-name", listFormName);
            buttonPostReleaseNextDate.setAttribute("type", "button");
            buttonPostReleaseNextDate.innerHTML =
                "<i class='icon-arrow-right'></i> Next inspection";
            buttonPostReleaseNextDate.classList.add("xcrud-action");
            buttonPostReleaseNextDate.classList.add("btn");
            buttonPostReleaseNextDate.classList.add("btn-success");
            buttonPostReleaseNextDate.classList.add("btn-sm");
            buttonPostReleaseNextDate.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        $(".modal.fade.validUntil").modal("show");
                        $("#validUntilBtn").click(function() {
                            var formJson = $("#validUntil").serializeObject();
                            var validUntil = formJson.validTo;
                            if (validUntil == null || validUntil == "") {
                                controller.showToastMsg("Validity Date Required", "#ff6666");
                            } else {
                                $(".modal.fade.validUntil").modal("hide");
                                postReleaseFunc("", validUntil);
                            }
                        });
                    }
                },
                false
            );
            buttonAmend = document.createElement("button");
            buttonAmend.setAttribute("form-name", listFormName);
            buttonAmend.setAttribute("type", "button");
            buttonAmend.innerHTML = "<i class='icon-arrow-right'></i> Revert";
            buttonAmend.classList.add("xcrud-action");
            buttonAmend.classList.add("btn");
            buttonAmend.classList.add("btn-success");
            buttonAmend.classList.add("btn-sm");
            buttonAmend.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        document.getElementsByClassName("forwardMany")[0].id = "amend";
                        if (listFormName == "printout_replacement") {
                            document
                                .getElementsByClassName("forwardMany")[0]
                                .setAttribute("form-name", "assignPhytoReplacement");
                        } else if (listFormName == "assigned_printout_replacement") {
                            document
                                .getElementsByClassName("forwardMany")[0]
                                .setAttribute("form-name", "assignedPhytoReplacement");
                        } else {
                            document
                                .getElementsByClassName("forwardMany")[0]
                                .setAttribute("form-name", listFormName);
                        }
                        if (formObj.formName.startsWith("assign")) {
                            $("#previousremarks").hide();
                        }
                        $(".modal.fade.approve_Confirm_Many_form").modal("show");
                    }
                },
                false
            );
            buttonLSave = document.createElement("button");
            buttonLSave.setAttribute("form-name", listFormName);
            buttonLSave.setAttribute("type", "button");
            buttonLSave.innerHTML = "<i class='icon-arrow-right'></i> Save";
            buttonLSave.classList.add("xcrud-action");
            buttonLSave.classList.add("btn");
            buttonLSave.classList.add("btn-success");
            buttonLSave.classList.add("btn-sm");
            buttonLSave.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        LineSave(data);
                    }
                },
                false
            );
            buttonApproveInspection = document.createElement("button");
            buttonApproveInspection.innerHTML = "<i class='fa fa-edit'></i>Approve";
            buttonApproveInspection.classList.add("xcrud-action");
            buttonApproveInspection.classList.add("btn");
            buttonApproveInspection.classList.add("btn-success");
            buttonApproveInspection.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonApproveInspection.setAttribute("form-name", listFormName);
            buttonApproveInspection.setAttribute("type", "button");
            buttonApproveInspection.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (
                            allFormObj.hasOwnProperty("assignedPhytoInspections") ||
                            allFormObj.hasOwnProperty("assignedPIPInspections") ||
                            allFormObj.hasOwnProperty("onetime_import") ||
                            allFormObj.hasOwnProperty("onetime_export")
                        ) {
                            InspectionApprove(data, "");
                        } else {
                            $(".modal.fade.validUntil").modal("show");
                            $("#validUntilBtn").click(function() {
                                var formJson = $("#validUntil").serializeObject();
                                var validUntil = formJson.validTo;
                                if (validUntil == null || validUntil == "") {
                                    // controller.showToastMsg("Validity Date Required" + errorMsg, "#ff6666");
                                } else {
                                    $(".modal.fade.validUntil").modal("hide");
                                    InspectionApprove(data, validUntil);
                                }
                            });
                        }
                    }
                },
                false
            );

            buttonviewInspection = document.createElement("button");
            buttonviewInspection.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspection.classList.add("xcrud-action");
            buttonviewInspection.classList.add("btn");
            buttonviewInspection.classList.add("btn-info");
            buttonviewInspection.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspection.setAttribute("form-name", listFormName);
            buttonviewInspection.setAttribute("type", "button");
            buttonviewInspection.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (booleanView == true) {
                            $(".crudheader_section").hide();
                        } else {
                            if (data.status == "INSPECTED AND PASSED") {
                                $(".crudheader_section").hide();
                            } else if (data.status == "PENDING") {
                                $(".crudheader_section").show();
                            } else if (data.status == "INSPECTED AND FAILED") {
                                $(".crudheader_section").hide();
                            } else {
                                $(".crudheader_section").show();
                            }
                        }
                        $(".backbtn").show();
                        inspectionrecords.push(data);
                        var formObj = allFormObj.lines;
                        formObj.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID;
                        controller.renderCRUDForm(
                            "crudsection_view_inspections",
                            formObj,
                            function() {}
                        );
                    }
                },
                false
            );

            buttonviewInspectiondate = document.createElement("button");
            buttonviewInspectiondate.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspectiondate.classList.add("xcrud-action");
            buttonviewInspectiondate.classList.add("btn");
            buttonviewInspectiondate.classList.add("btn-info");
            buttonviewInspectiondate.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspectiondate.setAttribute("form-name", listFormName);
            buttonviewInspectiondate.setAttribute("type", "button");
            buttonviewInspectiondate.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (booleanView == true) {
                            $(".crudheader_section").show();
                        } else {
                            if (data.status == "INSPECTED AND PASSED") {
                                $(".crudheader_section").show();
                            } else if (data.status == "PENDING") {
                                $(".crudheader_section").show();
                            } else {
                                $(".crudheader_section").show();
                            }
                        }
                        $(".backbtn").show();
                        inspectionrecords.push(data);
                        var formObj = allFormObj.lines;
                        formObj.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID;
                        controller.renderCRUDForm(
                            "crudsection_view_inspections",
                            formObj,
                            function() {}
                        );
                    }
                },
                false
            );

            buttonviewInspection_crud_1 = document.createElement("button");
            buttonviewInspection_crud_1.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspection_crud_1.classList.add("xcrud-action");
            buttonviewInspection_crud_1.classList.add("btn");
            buttonviewInspection_crud_1.classList.add("btn-info");
            buttonviewInspection_crud_1.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspection_crud_1.setAttribute("form-name", listFormName);
            buttonviewInspection_crud_1.setAttribute("type", "button");
            buttonviewInspection_crud_1.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        var formOnjLines = allFormObj["lines"];
                        inspectionrecords.push(data);
                        $(".requirementModal_export").modal("show");
                        $(".crud_section_inspections").html(
                            "Inspection Loading... Please Wait"
                        );
                        var heightInspectionHeader = $("#listings_inspectionHeader").height();
                        heightInspectionHeader = heightInspectionHeader - 60;
                        $(".crud_section_inspections").css({
                            top: heightInspectionHeader + "px",
                        });
                        formOnjLines.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID +
                            "";
                        controller.renderCRUDForm(
                            "crud_section_inspections",
                            formOnjLines,
                            function() {
                                controller.refreshCrudTables(this);
                            }
                        );
                    }
                },
                false
            );

            buttonviewInspection_crud_2 = document.createElement("button");
            buttonviewInspection_crud_2.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspection_crud_2.classList.add("xcrud-action");
            buttonviewInspection_crud_2.classList.add("btn");
            buttonviewInspection_crud_2.classList.add("btn-info");
            buttonviewInspection_crud_2.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspection_crud_2.setAttribute("form-name", listFormName);
            buttonviewInspection_crud_2.setAttribute("type", "button");
            buttonviewInspection_crud_2.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (booleanView == true) {
                            $(".crudheader_section").hide();
                        } else {
                            if (data.status == "INSPECTED AND PASSED") {
                                $(".crudheader_section").hide();
                            } else if (data.status == "PENDING") {
                                $(".crudheader_section").show();
                            }
                        }
                        inspectionrecords.push(data);
                        $(".requirementModal_import").modal("show");

                        var formObj6 = allFormObj.lines;
                        formObj6.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID;
                        controller.renderCRUDForm(
                            "crud_section_lines_checklist_2",
                            formObj6,
                            function() {}
                        );
                    }
                },
                false
            );

            // Quarantine facility inspections approvals
            buttonviewInspection_crud_3 = document.createElement("button");
            buttonviewInspection_crud_3.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspection_crud_3.classList.add("xcrud-action");
            buttonviewInspection_crud_3.classList.add("btn");
            buttonviewInspection_crud_3.classList.add("btn-info");
            buttonviewInspection_crud_3.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspection_crud_3.setAttribute("form-name", listFormName);
            buttonviewInspection_crud_3.setAttribute("type", "button");
            buttonviewInspection_crud_3.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (booleanView == true) {
                            $(".crudheader_section").hide();
                        } else {
                            if (data.status == "INSPECTED AND PASSED") {
                                $(".crudheader_section").hide();
                            } else if (data.status == "PENDING") {
                                $(".crudheader_section").show();
                            } else {
                                $(".crudheader_section").show();
                            }
                        }
                        $(".backbtn").show();
                        inspectionrecords.push(data);
                        var formObj6 = allFormObj.lines;
                        formObj6.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID;
                        controller.renderCRUDForm("crudsection_2", formObj6, function() {});
                    }
                },
                false
            );

            // Quarantine importconsignment inspections approvals
            buttonviewInspection_crud_4 = document.createElement("button");
            buttonviewInspection_crud_4.innerHTML =
                "<i class='fa fa-eye''></i> View Checklist";
            buttonviewInspection_crud_4.classList.add("xcrud-action");
            buttonviewInspection_crud_4.classList.add("btn");
            buttonviewInspection_crud_4.classList.add("btn-info");
            buttonviewInspection_crud_4.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewInspection_crud_4.setAttribute("form-name", listFormName);
            buttonviewInspection_crud_4.setAttribute("type", "button");
            buttonviewInspection_crud_4.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (booleanView == true) {
                            $(".crudheader_section").hide();
                        } else {
                            if (data.status == "INSPECTED AND PASSED") {
                                $(".crudheader_section").hide();
                            } else if (data.status == "PENDING") {
                                $(".crudheader_section").show();
                            } else {
                                $(".crudheader_section").show();
                            }
                        }
                        $(".backbtn").show();
                        inspectionrecords.push(data);
                        var formObj6 = allFormObj.lines;
                        formObj6.listUrl =
                            serverURL +
                            "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
                            data.inspectionHeaderID;
                        controller.renderCRUDForm("crudsection_3", formObj6, function() {});
                    }
                },
                false
            );

            buttonviewCommodities = document.createElement("button");
            buttonviewCommodities.innerHTML =
                "<i class='fa fa-eye''></i> View Commodities";
            buttonviewCommodities.classList.add("xcrud-action");
            buttonviewCommodities.classList.add("btn");
            buttonviewCommodities.classList.add("btn-info");
            buttonviewCommodities.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewCommodities.setAttribute("form-name", listFormName);
            buttonviewCommodities.setAttribute("type", "button");
            buttonviewCommodities.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        controller.populateCommodities(data);
                    }
                },
                false
            );

            buttonviewPIPCommodities = document.createElement("button");
            buttonviewPIPCommodities.innerHTML =
                "<i class='fa fa-eye''></i> View Commodities";
            buttonviewPIPCommodities.classList.add("xcrud-action");
            buttonviewPIPCommodities.classList.add("btn");
            buttonviewPIPCommodities.classList.add("btn-info");
            buttonviewPIPCommodities.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewPIPCommodities.setAttribute("form-name", listFormName);
            buttonviewPIPCommodities.setAttribute("type", "button");
            buttonviewPIPCommodities.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        controller.populatePIPCommodities(data);
                    }
                },
                false
            );

            buttonViewDetails = document.createElement("button");
            buttonViewDetails.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewDetails.classList.add("xcrud-action");
            buttonViewDetails.classList.add("btn");
            buttonViewDetails.classList.add("btn-info");
            buttonViewDetails.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewDetails.setAttribute("form-name", listFormName);
            buttonViewDetails.setAttribute("type", "button");
            buttonViewDetails.addEventListener(
                "click",
                function() {
                    crudviewdatainformation(data);

                    setTimeout(function() {
                        $(".crud_section_2").hide();
                    }, 200);
                },
                false
            );

            buttonglobalView = document.createElement("button");
            buttonglobalView.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonglobalView.classList.add("xcrud-action");
            buttonglobalView.classList.add("btn");
            buttonglobalView.classList.add("btn-info");
            buttonglobalView.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonglobalView.setAttribute("form-name", listFormName);
            buttonglobalView.setAttribute("type", "button");
            buttonglobalView.addEventListener(
                "click",
                function() {
                    viewRowData(data, listFormName);
                    try {
                        setTimeout(function() {
                            $(".crud_section_lines").hide();
                        }, 100);
                    } catch (error) {}
                },
                false
            );

            buttonglobalDownload = document.createElement("button");
            buttonglobalDownload.innerHTML =
                "Download Phyto<i class='icon-arrow-right'></i>";
            buttonglobalDownload.classList.add("xcrud-action");
            buttonglobalDownload.classList.add("btn");
            buttonglobalDownload.classList.add("btn-warning");
            buttonglobalDownload.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonglobalDownload.setAttribute("form-name", listFormName);
            buttonglobalDownload.setAttribute("type", "button");
            buttonglobalDownload.addEventListener(
                "click",
                function() {
                    downloadDocumnt(data);
                },
                false
            );

            buttonViewsection_2 = document.createElement("button");
            buttonViewsection_2.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_2.classList.add("xcrud-action");
            buttonViewsection_2.classList.add("btn");
            buttonViewsection_2.classList.add("btn-info");
            buttonViewsection_2.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_2.setAttribute("form-name", listFormName);
            buttonViewsection_2.setAttribute("type", "button");
            buttonViewsection_2.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_2(data);
                },
                false
            );

            buttonViewsection_3 = document.createElement("button");
            buttonViewsection_3.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_3.classList.add("xcrud-action");
            buttonViewsection_3.classList.add("btn");
            buttonViewsection_3.classList.add("btn-info");
            buttonViewsection_3.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_3.setAttribute("form-name", listFormName);
            buttonViewsection_3.setAttribute("type", "button");
            buttonViewsection_3.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_3(data);
                },
                false
            );

            buttonViewsection_4 = document.createElement("button");
            buttonViewsection_4.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_4.classList.add("xcrud-action");
            buttonViewsection_4.classList.add("btn");
            buttonViewsection_4.classList.add("btn-info");
            buttonViewsection_4.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_4.setAttribute("form-name", listFormName);
            buttonViewsection_4.setAttribute("type", "button");
            buttonViewsection_4.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_4(data);
                },
                false
            );

            buttonViewsection_5 = document.createElement("button");
            buttonViewsection_5.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_5.classList.add("xcrud-action");
            buttonViewsection_5.classList.add("btn");
            buttonViewsection_5.classList.add("btn-info");
            buttonViewsection_5.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_5.setAttribute("form-name", listFormName);
            buttonViewsection_5.setAttribute("type", "button");
            buttonViewsection_5.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_5(data);
                },
                false
            );

            buttonViewsection_6 = document.createElement("button");
            buttonViewsection_6.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_6.classList.add("xcrud-action");
            buttonViewsection_6.classList.add("btn");
            buttonViewsection_6.classList.add("btn-info");
            buttonViewsection_6.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_6.setAttribute("form-name", listFormName);
            buttonViewsection_6.setAttribute("type", "button");
            buttonViewsection_6.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_6(data);
                },
                false
            );

            buttonViewsection_7 = document.createElement("button");
            buttonViewsection_7.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_7.classList.add("xcrud-action");
            buttonViewsection_7.classList.add("btn");
            buttonViewsection_7.classList.add("btn-info");
            buttonViewsection_7.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_7.setAttribute("form-name", listFormName);
            buttonViewsection_7.setAttribute("type", "button");
            buttonViewsection_7.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_7(data);
                },
                false
            );

            buttonViewsection_8 = document.createElement("button");
            buttonViewsection_8.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewsection_8.classList.add("xcrud-action");
            buttonViewsection_8.classList.add("btn");
            buttonViewsection_8.classList.add("btn-info");
            buttonViewsection_8.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewsection_8.setAttribute("form-name", listFormName);
            buttonViewsection_8.setAttribute("type", "button");
            buttonViewsection_8.addEventListener(
                "click",
                function() {
                    allFormObj["highestAccessedTab"] = 0;
                    crudviewdsection_8(data);
                },
                false
            );

            btnViewDetailsvariety = document.createElement("button");
            btnViewDetailsvariety.innerHTML = "View<i class='icon-arrow-right'></i>";
            btnViewDetailsvariety.classList.add("xcrud-action");
            btnViewDetailsvariety.classList.add("btn");
            btnViewDetailsvariety.classList.add("btn-info");
            btnViewDetailsvariety.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            btnViewDetailsvariety.setAttribute("form-name", listFormName);
            btnViewDetailsvariety.setAttribute("type", "button");
            btnViewDetailsvariety.addEventListener(
                "click",
                function() {
                    crudviewvariety(data);
                },
                false
            );

            buttonviewWindows = document.createElement("button");
            buttonviewWindows.innerHTML = "<i class='fa fa-eye''></i> View Windows";
            buttonviewWindows.classList.add("xcrud-action");
            buttonviewWindows.classList.add("btn");
            buttonviewWindows.classList.add("btn-info");
            buttonviewWindows.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonviewWindows.setAttribute("form-name", listFormName);
            buttonviewWindows.setAttribute("type", "button");
            buttonviewWindows.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        localStorage.setItem("menu_id", data.menu_id);
                        $(".requirementModal").modal("show");
                        var heightInspectionHeader = $("#listings_inspectionHeader").height();
                        heightInspectionHeader = heightInspectionHeader - 60;
                        $(".crud_section_lines").css({ top: heightInspectionHeader + "px" });
                        (formObj2.listUrl =
                            serverURL + "menu/getFormTypeByMenuID?menuID=" + data.menu_id + ""),
                        controller.renderCRUDForm(
                            "crud_section_lines_two",
                            formObj2,
                            function() {}
                        );
                    }
                },
                false
            );

            buttonaAddRegionCounties = document.createElement("button");
            buttonaAddRegionCounties.innerHTML =
                "<i class='fa fa-edit''></i>Region County";
            buttonaAddRegionCounties.classList.add("xcrud-action");
            buttonaAddRegionCounties.classList.add("btn");
            buttonaAddRegionCounties.classList.add("btn-success");
            buttonaAddRegionCounties.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonaAddRegionCounties.setAttribute("form-name", listFormName);
            buttonaAddRegionCounties.setAttribute("type", "button");
            buttonaAddRegionCounties.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (allFormObj["region"]) {
                            allFormObj["regionCounty"]["crudAdd"] = true;
                            allFormObj["regionCounty"]["crudEdit"] = true;
                        }
                        $(".requirementModal").modal("show");
                        var heightInspectionHeader = $("#listings_inspectionHeader").height();
                        heightInspectionHeader = heightInspectionHeader - 60;
                        $(".crud_section_lines").css({ top: heightInspectionHeader + "px" });
                        (formObj2.listUrl =
                            serverURL +
                            "regionCounty/getRegionCountyByRegion?regionID=" +
                            data.regionID +
                            ""),
                        controller.renderCRUDForm(
                            "crud_section_lines_two",
                            formObj2,
                            function() {}
                        );
                    }
                },
                false
            );
            buttonaAddcrudeditUserCompany = document.createElement("button");
            buttonaAddcrudeditUserCompany.innerHTML =
                "<i class='fa fa-edit''></i>Edit Info";
            buttonaAddcrudeditUserCompany.classList.add("xcrud-action");
            buttonaAddcrudeditUserCompany.classList.add("btn");
            buttonaAddcrudeditUserCompany.classList.add("btn-success");
            buttonaAddcrudeditUserCompany.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonaAddcrudeditUserCompany.setAttribute("form-name", listFormName);
            buttonaAddcrudeditUserCompany.setAttribute("type", "button");
            buttonaAddcrudeditUserCompany.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        editRecord_section_2(data, formName);
                    }
                },
                false
            );

            buttonaAddStaffprofile = document.createElement("button");
            buttonaAddStaffprofile.innerHTML =
                "<i class='fa fa-edit''></i> Staff Profile";
            buttonaAddStaffprofile.classList.add("xcrud-action");
            buttonaAddStaffprofile.classList.add("btn");
            buttonaAddStaffprofile.classList.add("btn-success");
            buttonaAddStaffprofile.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonaAddStaffprofile.setAttribute("form-name", listFormName);
            buttonaAddStaffprofile.setAttribute("type", "button");
            buttonaAddStaffprofile.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (allFormObj["clients"]) {
                            allFormObj["staffProfile"]["crudAdd"] = false;
                            allFormObj["staffProfile"]["crudEdit"] = false;
                        }

                        staffprofile(data);
                    }
                },
                false
            );

            buttonviewFarmProducts = document.createElement("button");
            buttonviewFarmProducts.innerHTML =
                "<i class='fa fa-eye''></i> View Products";
            buttonviewFarmProducts.classList.add("xcrud-action");
            buttonviewFarmProducts.classList.add("btn");
            buttonviewFarmProducts.classList.add("btn-info");
            buttonviewFarmProducts.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj9.formName;
            } else {
                listFormName = formName;
            }
            buttonviewFarmProducts.setAttribute("form-name", listFormName);
            buttonviewFarmProducts.setAttribute("type", "button");
            buttonviewFarmProducts.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        try {
                            allFormObj["exporterFarmproducts"]["crudAdd"] = false;
                            allFormObj["exporterFarmproducts"]["crudEdit"] = false;
                            allFormObj["exporterFarm"]["crudAddproductsbtn"] = false;
                            allFormObj["exporterFarm"]["crudEdit"] = false;
                            crudAddproductsbtn;
                        } catch (error) {}
                        $(".viewfarmproductsmodal").modal("show");
                        var formObjFarm = allFormObj.exporterFarmproducts;

                        var heightInspectionHeader = $("#listings_inspectionHeader").height();
                        heightInspectionHeader = heightInspectionHeader - 60;
                        $(".crud_section_modal").css({ top: heightInspectionHeader + "px" });
                        controller.requestWithToken(
                            serverURL +
                            "farmProduct/getFarmProductByExporterFarm?exporterFarmID=" +
                            data.exporterFarmID +
                            "",
                            function(data1, status) {
                                if (data) {
                                    (formObjFarm.listUrl =
                                        serverURL +
                                        "farmProduct/getFarmProductByExporterFarm?exporterFarmID=" +
                                        data.exporterFarmID +
                                        ""),
                                    controller.renderCRUDForm(
                                        "crud_section_modal",
                                        formObjFarm,
                                        function() {
                                            try {
                                                controller.renderCRUDTable(this.formObjFarm);
                                                controller.refreshCrudTables(this.formObjFarm);
                                            } catch (error) {}
                                        }
                                    );
                                }
                            }
                        );
                    }
                },
                false
            );

            buttonAddVarieties = document.createElement("button");
            buttonAddVarieties.innerHTML = "Add Billing<i class='fa fa-plus''></i>";
            buttonAddVarieties.classList.add("xcrud-action");
            buttonAddVarieties.classList.add("btn");
            buttonAddVarieties.classList.add("btn-info");
            buttonAddVarieties.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj9.formName;
            } else {
                listFormName = formName;
            }
            buttonAddVarieties.setAttribute("form-name", listFormName);
            buttonAddVarieties.setAttribute("type", "button");
            buttonAddVarieties.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        addSubcategoryBilling(data);
                    }
                },
                false
            );

            buttonviewProducts = document.createElement("button");
            buttonviewProducts.innerHTML = "<i class='fa fa-eye''></i> View Products";
            buttonviewProducts.classList.add("xcrud-action");
            buttonviewProducts.classList.add("btn");
            buttonviewProducts.classList.add("btn-info");
            buttonviewProducts.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonviewProducts.setAttribute("form-name", listFormName);
            buttonviewProducts.setAttribute("type", "button");
            buttonviewProducts.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        $(".requirementModalproductsphyto").modal("show");
                        var formObj3 =
                            allFormObj.exporterConsignmentVarietyDetailsconsignmnet;
                        formObj3.listUrl =
                            serverURL +
                            "exporterConsignmentVarietyDetails/getExporterConsignmentVarietyDetailsByExporterConsignment?exporterConsignmentID=" +
                            data.exporterConsignment.exporterConsignmentID;
                        controller.renderCRUDForm(
                            "crud_section_lines_phyto",
                            formObj3,
                            function() {
                                controller.refreshCrudTables("crud_section_lines_phyto");
                            }
                        );
                    }
                },
                false
            );
            buttonAddFarmProducts = document.createElement("button");
            buttonAddFarmProducts.innerHTML =
                "<i class='fa fa-edit''></i> Farm Products";
            buttonAddFarmProducts.classList.add("xcrud-action");
            buttonAddFarmProducts.classList.add("btn");
            buttonAddFarmProducts.classList.add("btn-success");
            buttonAddFarmProducts.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj3.formName;
            } else {
                listFormName = formName;
            }
            buttonAddFarmProducts.setAttribute("form-name", listFormName);
            buttonAddFarmProducts.setAttribute("type", "button");
            buttonAddFarmProducts.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        addFarmproducts(data, this);
                        // $("#crudheader_section").hide();
                        // var ID = data.exporterFarmID;
                        // $('.requirementModal').modal('show');
                        // var formObj9 = allFormObj.exporterFarmproducts;
                        // formObj9.listUrl = serverURL + "farmProduct/getFarmProductByExporterFarm?exporterFarmID=" + data.exporterFarmID,
                        //     controller.renderCRUDForm("crud_section_lines2", formObj9, function () {
                        //         controller.renderCRUDTable(this.formObj9);

                        //     });
                    }
                },
                false
            );
            buttonRejectInspection = document.createElement("button");
            buttonRejectInspection.innerHTML = "Reject";
            buttonRejectInspection.classList.add("xcrud-action");
            buttonRejectInspection.classList.add("btn");
            buttonRejectInspection.classList.add("btn-warning");
            buttonRejectInspection.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj7.formName;
            } else {
                listFormName = formName;
            }
            buttonRejectInspection.setAttribute("form-name", listFormName);
            buttonRejectInspection.setAttribute("type", "button");
            buttonRejectInspection.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        if (formObj.formName.startsWith("assign")) {
                            $("#previousremarks").hide();
                        }
                        $(".modal.fade.reject_inspection_Many_form").modal("show");
                        $("#rejectbtn_modal").click(function() {
                            var formJson = $("#rejectedWeight").serializeObject();
                            var rejectedWeight = formJson.rejectedWeight;
                            $(".modal.fade.reject_inspection_Many_form").modal("hide");
                            InspectionReject(data, rejectedWeight);
                        });
                    }
                },
                false
            );
            buttonsaveRequirements = document.createElement("button");
            buttonsaveRequirements.innerHTML = "Submit";
            buttonsaveRequirements.classList.add("xcrud-action");
            buttonsaveRequirements.classList.add("btn");
            buttonsaveRequirements.classList.add("btn-warning");
            buttonsaveRequirements.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.formObj8.formName;
            } else {
                listFormName = formName;
            }
            buttonsaveRequirements.setAttribute("form-name", listFormName);
            buttonsaveRequirements.setAttribute("type", "button");
            buttonsaveRequirements.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {}
                },
                false
            );
            buttonCancelPhyto = document.createElement("button");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonCancelPhyto.setAttribute("form-name", listFormName);
            buttonCancelPhyto.setAttribute("type", "button");
            buttonCancelPhyto.innerHTML = "<i class='icon-arrow-right'></i> Cancel";
            buttonCancelPhyto.classList.add("xcrud-action");
            buttonCancelPhyto.classList.add("btn");
            buttonCancelPhyto.classList.add("btn-danger");
            buttonCancelPhyto.classList.add("btn-sm");
            buttonCancelPhyto.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        $(".modal.fade.cancelPhyto").modal("show");
                        $("#confirmCancel").click(function() {
                            var formJson = $("#cancelPhyto").serializeObject();
                            var reason = formJson.reason;
                            $(".modal.fade.cancelPhyto").modal("hide");
                            controller.cancelPhyto(data, reason);
                        });
                    }
                },
                false
            );
            buttonUploadInspectionReport = document.createElement("button");
            buttonUploadInspectionReport.innerHTML =
                "<i class='fa fa-edit'></i> Upload Report";
            buttonUploadInspectionReport.classList.add("xcrud-action");
            buttonUploadInspectionReport.classList.add("btn");
            buttonUploadInspectionReport.classList.add("btn-success");
            buttonUploadInspectionReport.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonUploadInspectionReport.setAttribute("form-name", listFormName);
            buttonUploadInspectionReport.setAttribute("type", "button");
            buttonUploadInspectionReport.addEventListener(
                "click",
                function(event) {
                    if (!event.detail || event.detail == 1) {
                        $(".modal.fade.UploadInspectionReport").modal("show");
                        $("#upload_report").click(function() {
                            var filelist = new Array();
                            var report_files = document.getElementById("report_files");
                            for (var i = 0; i < report_files.files.length; ++i) {
                                filelist[i] = report_files.files.item(i).name;
                            }
                            $(".modal.fade.UploadInspectionReport").modal("hide");
                        });
                    }
                },
                false
            );
            var currentObj = allFormObj[formName];
            var crudUploadReport = false;
            try {
                crudUploadReport = currentObj.crudUploadReport;
                if (crudUploadReport == undefined || crudUploadReport == "undefined") {
                    crudUploadReport = false;
                }
            } catch (e) {}
            var crudDeactivateRequirement = false;
            try {
                crudDeactivateRequirement = currentObj.crudDeactivateRequirement;
                if (
                    crudDeactivateRequirement == undefined ||
                    crudDeactivateRequirement == "undefined"
                ) {
                    crudDeactivateRequirement = false;
                }
            } catch (e) {}
            var crudddPhytoProducts = false;
            try {
                crudddPhytoProducts = currentObj.crudddPhytoProducts;
                if (
                    crudddPhytoProducts == undefined ||
                    crudddPhytoProducts == "undefined"
                ) {
                    crudddPhytoProducts = false;
                }
            } catch (e) {}
            var crudDeleteRecord = false;
            try {
                crudDeleteRecord = currentObj.crudDeleteRecord;
                if (crudDeleteRecord == undefined || crudDeleteRecord == "undefined") {
                    crudDeleteRecord = false;
                }
            } catch (e) {}

            var crudDeactivateRecord = false;
            try {
                crudDeactivateRecord = currentObj.crudDeactivateRecord;
                if (
                    crudDeactivateRecord == undefined ||
                    crudDeactivateRecord == "undefined"
                ) {
                    crudDeactivateRecord = false;
                }
            } catch (e) {}

            var crudDeleteRecordfrmobj2 = false;
            try {
                crudDeleteRecordfrmobj2 = currentObj.crudDeleteRecordfrmobj2;
                if (
                    crudDeleteRecordfrmobj2 == undefined ||
                    crudDeleteRecordfrmobj2 == "undefined"
                ) {
                    crudDeleteRecordfrmobj2 = false;
                }
            } catch (e) {}

            var crudDeleteRecords = false;
            try {
                crudDeleteRecords = currentObj.crudDeleteRecords;
                if (crudDeleteRecords == undefined || crudDeleteRecords == "undefined") {
                    crudDeleteRecords = false;
                }
            } catch (e) {}

            var crudRejectionReasonview = false;
            try {
                crudRejectionReasonview = currentObj.crudRejectionReasonview;
                if (
                    crudRejectionReasonview == undefined ||
                    crudRejectionReasonview == "undefined"
                ) {
                    crudRejectionReasonview = false;
                }
            } catch (e) {}
            var crudDeleteMenuWindowRecord = false;
            try {
                crudDeleteMenuWindowRecord = currentObj.crudDeleteMenuWindowRecord;
                if (
                    crudDeleteMenuWindowRecord == undefined ||
                    crudDeleteMenuWindowRecord == "undefined"
                ) {
                    crudDeleteMenuWindowRecord = false;
                }
            } catch (e) {}
            var crudCopyRecord = false;
            try {
                crudCopyRecord = currentObj.crudCopyRecord;
                if (crudCopyRecord == undefined || crudCopyRecord == "undefined") {
                    crudCopyRecord = false;
                }
            } catch (e) {}
            var crudCancelPhyto = false;
            try {
                crudCancelPhyto = currentObj.crudCancelPhyto;
                if (crudCancelPhyto == undefined || crudCancelPhyto == "undefined") {
                    crudCancelPhyto = false;
                }
            } catch (e) {}
            var crudReject = false;
            try {
                crudReject = currentObj.crudReject;
                if (crudReject == undefined || crudReject == "undefined") {
                    crudReject = false;
                }
            } catch (e) {}
            var crudDraftPhyto = false;
            try {
                crudDraftPhyto = currentObj.crudDraftPhyto;
                if (crudDraftPhyto == undefined || crudDraftPhyto == "undefined") {
                    crudDraftPhyto = false;
                }
            } catch (e) {}
            var crudDraftPIP = false;
            try {
                crudDraftPIP = currentObj.crudDraftPIP;
                if (crudDraftPIP == undefined || crudDraftPIP == "undefined") {
                    crudDraftPIP = false;
                }
            } catch (e) {}
            var crudPipprinting = false;
            try {
                crudPipprinting = currentObj.crudPipprinting;
                if (crudPipprinting == undefined || crudPipprinting == "undefined") {
                    crudPipprinting = false;
                }
            } catch (e) {}
            var crudPrintInterception = false;
            try {
                crudPrintInterception = currentObj.crudPrintInterception;
                if (
                    crudPrintInterception == undefined ||
                    crudPrintInterception == "undefined"
                ) {
                    crudPrintInterception = false;
                }
            } catch (e) {}
            var crudPostReleaseReject = false;
            try {
                crudPostReleaseReject = currentObj.crudPostReleaseReject;
                if (
                    crudPostReleaseReject == undefined ||
                    crudPostReleaseReject == "undefined"
                ) {
                    crudPostReleaseReject = false;
                }
            } catch (e) {}
            var crudPostReleaseNextDate = false;
            try {
                crudPostReleaseNextDate = currentObj.crudPostReleaseNextDate;
                if (
                    crudPostReleaseNextDate == undefined ||
                    crudPostReleaseNextDate == "undefined"
                ) {
                    crudPostReleaseNextDate = false;
                }
            } catch (error) {}
            var paymentbtn = false;
            try {
                paymentbtn = currentObj.paymentbtn;
                if (paymentbtn == undefined || paymentbtn == "undefined") {
                    paymentbtn = false;
                }
            } catch (e) {}

            var crudSubmitPrint = false;
            try {
                crudSubmitPrint = currentObj.crudSubmitPrint;
                if (crudSubmitPrint == undefined || crudSubmitPrint == "undefined") {
                    crudSubmitPrint = false;
                }
            } catch (e) {}

            var crudSubmitDraftPrint = false;
            try {
                crudSubmitDraftPrint = currentObj.crudSubmitDraftPrint;
                if (
                    crudSubmitDraftPrint == undefined ||
                    crudSubmitDraftPrint == "undefined"
                ) {
                    crudSubmitDraftPrint = false;
                }
            } catch (e) {}

            var crudrequiresLab = false;
            try {
                crudrequiresLab = currentObj.crudrequiresLab;
                if (crudrequiresLab == undefined || crudrequiresLab == "undefined") {
                    crudrequiresLab = false;
                }
            } catch (e) {}
            var crudrequiresSampling = false;
            try {
                crudrequiresSampling = currentObj.crudrequiresSampling;
                if (
                    crudrequiresSampling == undefined ||
                    crudrequiresSampling == "undefined"
                ) {
                    crudrequiresSampling = false;
                }
            } catch (e) {}
            var crudLSave = false;
            try {
                crudLSave = currentObj.crudLSave;
                if (crudLSave == undefined || crudLSave == "undefined") {
                    crudLSave = false;
                }
            } catch (e) {}
            var crudAmend = false;
            try {
                crudAmend = currentObj.crudAmend;
                if (crudAmend == undefined || crudAmend == "undefined") {
                    crudAmend = false;
                }
            } catch (e) {}
            var crudEdit = true;
            try {
                crudEdit = currentObj.crudEdit;
                if (crudEdit == undefined || crudEdit == "undefined") {
                    crudEdit = true;
                }
            } catch (e) {}

            var crudCustomEdit = false;
            try {
                crudCustomEdit = currentObj.crudCustomEdit;
                if (crudCustomEdit == undefined || crudCustomEdit == "undefined") {
                    crudCustomEdit = false;
                }
            } catch (e) {}

            var crudCustomEdit_2 = false;
            try {
                crudCustomEdit_2 = currentObj.crudCustomEdit_2;
                if (crudCustomEdit_2 == undefined || crudCustomEdit_2 == "undefined") {
                    crudCustomEdit_2 = false;
                }
            } catch (e) {}

            var crudView = true;
            try {
                crudView = currentObj.crudView;
                if (crudView == undefined || crudView == "undefined") {
                    crudView = true;
                }
            } catch (e) {}
            var crudSubmitPipApplicatiinRequest = false;
            try {
                crudSubmitPipApplicatiinRequest =
                    currentObj.crudSubmitPipApplicatiinRequest;
                if (
                    crudSubmitPipApplicatiinRequest == undefined ||
                    crudSubmitPipApplicatiinRequest == "undefined"
                ) {
                    crudSubmitPipApplicatiinRequest = false;
                }
            } catch (e) {}
            var crudDeactivate = false;
            try {
                crudDeactivate = currentObj.crudDeactivate;
                if (crudDeactivate == undefined || crudDeactivate == "undefined") {
                    crudDeactivate = false;
                }
            } catch (e) {}
            var crudActivate = false;
            try {
                crudActivate = currentObj.crudActivate;
                if (crudActivate == undefined || crudActivate == "undefined") {
                    crudActivate = false;
                }
            } catch (e) {}
            var crudActivateRequirement = false;
            try {
                crudActivateRequirement = currentObj.crudActivateRequirement;
                if (
                    crudActivateRequirement == undefined ||
                    crudActivateRequirement == "undefined"
                ) {
                    crudActivateRequirement = false;
                }
            } catch (e) {}
            var crudRetractDocument = false;
            try {
                crudRetractDocument = currentObj.crudRetractDocument;
                if (
                    crudRetractDocument == undefined ||
                    crudRetractDocument == "undefined"
                ) {
                    crudRetractDocument = false;
                }
            } catch (e) {}

            var crudStartWorkflow = false;
            var rolesID = localStorage.getItem("currentRole");
            if (rolesID == 693) {
                if (
                    formName == "products" ||
                    formName == "product" ||
                    formName == "product_class" ||
                    formName == "product_category" ||
                    formName == "commodityfamily" ||
                    formName == "product_form" ||
                    formName == "product_variety" ||
                    formName == "import_condition" ||
                    formName == "import_requirement" ||
                    formName == "inspectionRequirement" ||
                    formName == "inspectionLocation" ||
                    formName == "ban_list" ||
                    formName == "subcounty" ||
                    formName == "ward"
                ) {
                    try {
                        crudStartWorkflow = currentObj.crudStartWorkflow;
                        if (
                            crudStartWorkflow == undefined ||
                            crudStartWorkflow == "undefined"
                        ) {
                            crudStartWorkflow = true;
                        }
                    } catch (e) {}
                } else {
                    try {
                        crudStartWorkflow = currentObj.crudStartWorkflow;
                        if (
                            crudStartWorkflow == undefined ||
                            crudStartWorkflow == "undefined"
                        ) {
                            crudStartWorkflow = false;
                        }
                    } catch (e) {}
                }
            } else {
                try {
                    crudStartWorkflow = currentObj.crudStartWorkflow;
                    if (
                        crudStartWorkflow == undefined ||
                        crudStartWorkflow == "undefined"
                    ) {
                        crudStartWorkflow = false;
                    }
                } catch (e) {}
            }

            var crudApproveInspection = false;
            try {
                crudApproveInspection = currentObj.crudApproveInspection;
                if (
                    crudApproveInspection == undefined ||
                    crudApproveInspection == "undefined"
                ) {
                    crudApproveInspection = false;
                }
            } catch (e) {}

            var crudStartPipWorkflow = false;
            try {
                crudStartPipWorkflow = currentObj.crudStartPipWorkflow;
                if (
                    crudStartPipWorkflow == undefined ||
                    crudStartPipWorkflow == "undefined"
                ) {
                    crudStartPipWorkflow = false;
                }
            } catch (e) {}

            var crudviewInspection = false;
            try {
                crudviewInspection = currentObj.crudviewInspection;
                if (
                    crudviewInspection == undefined ||
                    crudviewInspection == "undefined"
                ) {
                    crudviewInspection = false;
                }
            } catch (e) {}

            var crudviewUpdatedateInspection = false;
            try {
                crudviewUpdatedateInspection = currentObj.crudviewUpdatedateInspection;
                if (
                    crudviewUpdatedateInspection == undefined ||
                    crudviewUpdatedateInspection == "undefined"
                ) {
                    crudviewUpdatedateInspection = false;
                }
            } catch (e) {}

            var crudview_Inspection_1 = false;
            try {
                crudview_Inspection_1 = currentObj.crudview_Inspection_1;
                if (
                    crudview_Inspection_1 == undefined ||
                    crudview_Inspection_1 == "undefined"
                ) {
                    crudview_Inspection_1 = false;
                }
            } catch (e) {}

            var crudview_Inspection_2 = false;
            try {
                crudview_Inspection_2 = currentObj.crudview_Inspection_2;
                if (
                    crudview_Inspection_2 == undefined ||
                    crudview_Inspection_2 == "undefined"
                ) {
                    crudview_Inspection_2 = false;
                }
            } catch (e) {}

            var crudview_Inspection_3 = false;
            try {
                crudview_Inspection_3 = currentObj.crudview_Inspection_3;
                if (
                    crudview_Inspection_3 == undefined ||
                    crudview_Inspection_3 == "undefined"
                ) {
                    crudview_Inspection_3 = false;
                }
            } catch (e) {}

            var crudview_Inspection_4 = false;
            try {
                crudview_Inspection_4 = currentObj.crudview_Inspection_4;
                if (
                    crudview_Inspection_4 == undefined ||
                    crudview_Inspection_4 == "undefined"
                ) {
                    crudview_Inspection_4 = false;
                }
            } catch (e) {}

            var crudviewCommodities = false;
            try {
                crudviewCommodities = currentObj.crudviewCommodities;
                if (
                    crudviewCommodities == undefined ||
                    crudviewCommodities == "undefined"
                ) {
                    crudviewCommodities = false;
                }
            } catch (e) {}

            var crudviewPIPCommodities = false;
            try {
                crudviewPIPCommodities = currentObj.crudviewPIPCommodities;
                if (
                    crudviewPIPCommodities == undefined ||
                    crudviewPIPCommodities == "undefined"
                ) {
                    crudviewPIPCommodities = false;
                }
            } catch (e) {}

            var crudviewLabReason = false;
            try {
                crudviewLabReason = currentObj.crudviewLabReason;
                if (crudviewLabReason == undefined || crudviewLabReason == "undefined") {
                    crudviewLabReason = false;
                }
            } catch (e) {}

            var crudviewVoidApplication = false;
            try {
                crudviewVoidApplication = currentObj.crudviewVoidApplication;
                if (
                    crudviewVoidApplication == undefined ||
                    crudviewVoidApplication == "undefined"
                ) {
                    crudviewVoidApplication = false;
                }
            } catch (e) {}

            var crudviewNegotiatedApplication = false;
            try {
                crudviewNegotiatedApplication = currentObj.crudviewNegotiatedApplication;
                if (
                    crudviewNegotiatedApplication == undefined ||
                    crudviewNegotiatedApplication == "undefined"
                ) {
                    crudviewNegotiatedApplication = false;
                }
            } catch (e) {}

            var crudviewremoveNegotiatedApplication = false;
            try {
                crudviewremoveNegotiatedApplication =
                    currentObj.crudviewremoveNegotiatedApplication;
                if (
                    crudviewremoveNegotiatedApplication == undefined ||
                    crudviewremoveNegotiatedApplication == "undefined"
                ) {
                    crudviewremoveNegotiatedApplication = false;
                }
            } catch (e) {}

            var crudviewEditDate = false;
            try {
                crudviewEditDate = currentObj.crudviewEditDate;
                if (crudviewEditDate == undefined || crudviewEditDate == "undefined") {
                    crudviewEditDate = false;
                }
            } catch (e) {}

            var crudviewViewWindows = false;
            try {
                crudviewViewWindows = currentObj.crudviewViewWindows;
                if (
                    crudviewViewWindows == undefined ||
                    crudviewViewWindows == "undefined"
                ) {
                    crudviewViewWindows = false;
                }
            } catch (e) {}
            var crudAddregionCounties = false;
            try {
                crudAddregionCounties = currentObj.crudAddregionCounties;
                if (
                    crudAddregionCounties == undefined ||
                    crudAddregionCounties == "undefined"
                ) {
                    crudAddregionCounties = false;
                }
            } catch (e) {}
            var crudeditUserCompany = false;
            try {
                crudeditUserCompany = currentObj.crudeditUserCompany;
                if (
                    crudeditUserCompany == undefined ||
                    crudeditUserCompany == "undefined"
                ) {
                    crudeditUserCompany = false;
                }
            } catch (e) {}
            var crudAddStaffProfile = false;
            try {
                crudAddStaffProfile = currentObj.crudAddStaffProfile;
                if (
                    crudAddStaffProfile == undefined ||
                    crudAddStaffProfile == "undefined"
                ) {
                    crudAddStaffProfile = false;
                }
            } catch (e) {}
            var crudviewProducts = false;
            try {
                crudviewProducts = currentObj.crudviewProducts;
                if (crudviewProducts == undefined || crudviewProducts == "undefined") {
                    crudviewProducts = false;
                }
            } catch (e) {}

            var crudAddVarieties = false;
            try {
                crudAddVarieties = currentObj.crudAddVarieties;
                if (crudAddVarieties == undefined || crudAddVarieties == "undefined") {
                    crudAddVarieties = false;
                }
            } catch (e) {}

            var globalView = false;
            try {
                globalView = currentObj.globalView;
                if (globalView == undefined || globalView == "undefined") {
                    globalView = false;
                }
            } catch (e) {}

            var globalDownload = false;
            try {
                globalDownload = currentObj.globalDownload;
                if (globalDownload == undefined || globalDownload == "undefined") {
                    globalDownload = false;
                }
            } catch (e) {}

            var crudViewDetails = false;
            try {
                crudViewDetails = currentObj.crudViewDetails;
                if (crudViewDetails == undefined || crudViewDetails == "undefined") {
                    crudViewDetails = false;
                }
            } catch (e) {}

            var crudInspectbutton = false;
            try {
                crudInspectbutton = currentObj.crudInspectbutton;
                if (crudInspectbutton == undefined || crudInspectbutton == "undefined") {
                    crudInspectbutton = false;
                }
            } catch (e) {}

            var crudbtnConfirmPayments = false;
            try {
                crudbtnConfirmPayments = currentObj.crudbtnConfirmPayments;
                if (
                    crudbtnConfirmPayments == undefined ||
                    crudbtnConfirmPayments == "undefined"
                ) {
                    crudbtnConfirmPayments = false;
                }
            } catch (e) {}

            var crudViewDetails_section_2 = false;
            try {
                crudViewDetails_section_2 = currentObj.crudViewDetails_section_2;
                if (
                    crudViewDetails_section_2 == undefined ||
                    crudViewDetails_section_2 == "undefined"
                ) {
                    crudViewDetails_section_2 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_3 = false;
            try {
                crudViewDetails_section_3 = currentObj.crudViewDetails_section_3;
                if (
                    crudViewDetails_section_3 == undefined ||
                    crudViewDetails_section_3 == "undefined"
                ) {
                    crudViewDetails_section_3 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_4 = false;
            try {
                crudViewDetails_section_4 = currentObj.crudViewDetails_section_4;
                if (
                    crudViewDetails_section_4 == undefined ||
                    crudViewDetails_section_4 == "undefined"
                ) {
                    crudViewDetails_section_4 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_5 = false;
            try {
                crudViewDetails_section_5 = currentObj.crudViewDetails_section_5;
                if (
                    crudViewDetails_section_5 == undefined ||
                    crudViewDetails_section_5 == "undefined"
                ) {
                    crudViewDetails_section_5 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_6 = false;
            try {
                crudViewDetails_section_6 = currentObj.crudViewDetails_section_6;
                if (
                    crudViewDetails_section_6 == undefined ||
                    crudViewDetails_section_6 == "undefined"
                ) {
                    crudViewDetails_section_6 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_7 = false;
            try {
                crudViewDetails_section_7 = currentObj.crudViewDetails_section_7;
                if (
                    crudViewDetails_section_7 == undefined ||
                    crudViewDetails_section_7 == "undefined"
                ) {
                    crudViewDetails_section_7 = false;
                }
            } catch (e) {}

            var crudViewDetails_section_8 = false;
            try {
                crudViewDetails_section_8 = currentObj.crudViewDetails_section_8;
                if (
                    crudViewDetails_section_8 == undefined ||
                    crudViewDetails_section_8 == "undefined"
                ) {
                    crudViewDetails_section_8 = false;
                }
            } catch (e) {}

            var crudViewDetailsvariety = false;
            try {
                crudViewDetailsvariety = currentObj.crudViewDetailsvariety;
                if (
                    crudViewDetailsvariety == undefined ||
                    crudViewDetailsvariety == "undefined"
                ) {
                    crudViewDetailsvariety = false;
                }
            } catch (e) {}

            var crudviewConsignmentProducts = false;
            try {
                crudviewConsignmentProducts = currentObj.crudviewConsignmentProducts;
                if (
                    crudviewConsignmentProducts == undefined ||
                    crudviewConsignmentProducts == "undefined"
                ) {
                    crudviewConsignmentProducts = false;
                }
            } catch (e) {}
            var crudAddproductsbtn = false;
            try {
                crudAddproductsbtn = currentObj.crudAddproductsbtn;
                if (
                    crudAddproductsbtn == undefined ||
                    crudAddproductsbtn == "undefined"
                ) {
                    crudAddproductsbtn = false;
                }
            } catch (e) {}
            var crudRejectInpsection = false;
            try {
                crudRejectInpsection = currentObj.crudRejectInpsection;
                if (
                    crudRejectInpsection == undefined ||
                    crudRejectInpsection == "undefined"
                ) {
                    crudRejectInpsection = false;
                }
            } catch (e) {}
            var crudsaveLines = false;
            try {
                crudsaveLines = currentObj.crudsaveLines;
                if (crudsaveLines == undefined || crudsaveLines == "undefined") {
                    crudsaveLines = false;
                }
            } catch (e) {}
            var crudOnetimeExportImportLineeSave = false;
            try {
                crudOnetimeExportImportLineeSave =
                    currentObj.crudOnetimeExportImportLineeSave;
                if (
                    crudOnetimeExportImportLineeSave == undefined ||
                    crudOnetimeExportImportLineeSave == "undefined"
                ) {
                    crudOnetimeExportImportLineeSave = false;
                }
            } catch (e) {}
            var crudexportLineSave = true;
            try {
                crudexportLineSave = thisObj.crudexportLineSave;
                if (
                    crudexportLineSave == undefined ||
                    crudexportLineSave == "undefined"
                ) {
                    crudexportLineSave = true;
                }
            } catch (e) {}
            if (crudView) {
                buttonHolder.appendChild(buttonView);
            }
            if (crudViewDetails) {
                buttonHolder.appendChild(buttonViewDetails);
            }

            if (crudInspectbutton) {
                buttonHolder.appendChild(buttonViewInspect);
            }

            if (globalView) {
                buttonHolder.appendChild(buttonglobalView);
            }

            if (globalDownload) {
                buttonHolder.appendChild(buttonglobalDownload);
            }

            if (crudViewDetails_section_2) {
                buttonHolder.appendChild(buttonViewsection_2);
            }

            if (crudViewDetails_section_3) {
                buttonHolder.appendChild(buttonViewsection_3);
            }
            if (crudViewDetails_section_4) {
                buttonHolder.appendChild(buttonViewsection_4);
            }
            if (crudViewDetails_section_5) {
                buttonHolder.appendChild(buttonViewsection_5);
            }
            if (crudViewDetails_section_6) {
                buttonHolder.appendChild(buttonViewsection_6);
            }
            if (crudViewDetails_section_7) {
                buttonHolder.appendChild(buttonViewsection_7);
            }
            if (crudViewDetails_section_8) {
                buttonHolder.appendChild(buttonViewsection_8);
            }
            if (crudViewDetailsvariety) {
                buttonHolder.appendChild(btnViewDetailsvariety);
            }

            if (crudCopyRecord) {
                buttonHolder.appendChild(buttonCopyRecord);
            }
            if (crudSubmitPipApplicatiinRequest) {
                buttonHolder.appendChild(buttonSubmitPipApplicatiinRequest);
            }
            if (crudUploadReport) {
                buttonHolder.appendChild(buttonUploadInspectionReport);
            }
            if (crudEdit) {
                buttonHolder.appendChild(buttonEdit);
            }
            if (crudCustomEdit) {
                buttonHolder.appendChild(custombuttonEdit);
            }

            if (crudCustomEdit_2) {
                buttonHolder.appendChild(custombuttonEdit_2);
            }
            if (crudDeleteRecord) {
                buttonHolder.appendChild(buttonDelete);
            }
            if (crudDeactivateRecord) {
                buttonHolder.appendChild(buttonRecordDeactivate);
            }

            if (crudDeleteRecordfrmobj2) {
                buttonHolder.appendChild(buttonDeleteformobj2);
            }

            if (crudDeleteRecords) {
                buttonHolder.appendChild(buttonDeleteRecords);
            }
            if (crudRejectionReasonview) {
                buttonHolder.appendChild(buttonRejectionView);
            }
            if (crudDeleteMenuWindowRecord) {
                buttonHolder.appendChild(buttonMenuDelete);
                return buttonHolder;
            }
            if (crudDeactivateRequirement) {
                buttonHolder.appendChild(buttonDeactivateRequirement);
            }
            if (crudddPhytoProducts) {
                buttonHolder.appendChild(buttonaddPhytoProducts);
            }
            if (paymentbtn) {
                buttonHolder.appendChild(buttonpaymentBtn);
            }
            if (crudSubmitPrint) {
                buttonHolder.appendChild(buttonSubmitPrint);
            }

            if (crudSubmitDraftPrint) {
                buttonHolder.appendChild(buttonSubmitDraftPrint);
            }
            if (crudDeactivate) {
                buttonHolder.appendChild(buttonDeactivate);
            }
            if (crudrequiresLab) {
                buttonHolder.appendChild(buttonRequiresLab);
            }
            if (crudrequiresSampling) {
                buttonHolder.appendChild(buttonRequiresSampling);
            }
            if (crudActivate) {
                buttonHolder.appendChild(buttonActivate);
            }
            if (crudActivateRequirement) {
                buttonHolder.appendChild(buttonActivateRequirements);
            }

            if (crudStartWorkflow) {
                buttonHolder.appendChild(buttonForward);
            }

            if (crudStartPipWorkflow) {
                buttonHolder.appendChild(buttonPipForward);
            }

            if (crudRetractDocument) {
                buttonHolder.appendChild(btnretract);
            }
            if (crudReject) {
                buttonHolder.appendChild(buttonReject);
            }
            if (crudPostReleaseNextDate) {
                buttonHolder.appendChild(buttonPostReleaseNextDate);
            }
            if (crudDraftPhyto) {
                buttonHolder.appendChild(buttonDraftPhyto);
            }
            if (crudPipprinting) {
                buttonHolder.appendChild(buttonDraftPrintpip);
            }
            if (crudDraftPIP) {
                buttonHolder.appendChild(buttonDraftPIP);
            }
            if (crudPrintInterception) {
                buttonHolder.appendChild(buttonPrintInterception);
            }
            if (crudPostReleaseReject) {
                buttonHolder.appendChild(buttonPostReleaseReject);
            }
            if (crudAmend) {
                buttonHolder.appendChild(buttonAmend);
            }
            if (crudLSave) {
                buttonHolder.appendChild(buttonLSave);
            }
            if (crudApproveInspection) {
                buttonHolder.appendChild(buttonApproveInspection);
            }
            if (crudviewInspection) {
                buttonHolder.appendChild(buttonviewInspection);
                return buttonHolder;
            }

            if (crudviewUpdatedateInspection) {
                buttonHolder.appendChild(buttonviewInspectiondate);
                return buttonHolder;
            }

            if (crudview_Inspection_1) {
                buttonHolder.appendChild(buttonviewInspection_crud_1);
                return buttonHolder;
            }

            if (crudview_Inspection_2) {
                buttonHolder.appendChild(buttonviewInspection_crud_2);
                return buttonHolder;
            }

            if (crudview_Inspection_3) {
                buttonHolder.appendChild(buttonviewInspection_crud_3);
                return buttonHolder;
            }

            if (crudview_Inspection_4) {
                buttonHolder.appendChild(buttonviewInspection_crud_4);
                return buttonHolder;
            }

            if (crudviewCommodities) {
                buttonHolder.appendChild(buttonviewCommodities);
                return buttonHolder;
            }
            if (crudviewPIPCommodities) {
                buttonHolder.appendChild(buttonviewPIPCommodities);
                return buttonHolder;
            }
            if (crudviewLabReason) {
                buttonHolder.appendChild(buttonviewLabReason);
                return buttonHolder;
            }

            if (crudviewVoidApplication) {
                buttonHolder.appendChild(buttonvoidApplication);
                return buttonHolder;
            }

            if (crudviewNegotiatedApplication) {
                buttonHolder.appendChild(buttonNegotiateApplication);
                return buttonHolder;
            }

            if (crudviewremoveNegotiatedApplication) {
                buttonHolder.appendChild(buttonremoveNegotiateApplication);
                return buttonHolder;
            }

            if (crudviewEditDate) {
                buttonHolder.appendChild(buttonUpdateDate);
                return buttonHolder;
            }

            if (crudviewViewWindows) {
                buttonHolder.appendChild(buttonviewWindows);
            }
            if (crudAddregionCounties) {
                buttonHolder.appendChild(buttonaAddRegionCounties);
            }
            if (crudeditUserCompany) {
                buttonHolder.appendChild(buttonaAddcrudeditUserCompany);
            }
            if (crudAddStaffProfile) {
                buttonHolder.appendChild(buttonaAddStaffprofile);
            }
            if (crudviewProducts) {
                buttonHolder.appendChild(buttonviewFarmProducts);
            }

            if (crudAddVarieties) {
                buttonHolder.appendChild(buttonAddVarieties);
            }
            if (crudviewConsignmentProducts) {
                buttonHolder.appendChild(buttonviewProducts);
            }
            if (crudRejectInpsection) {
                buttonHolder.appendChild(buttonRejectInspection);
            }
            // if (crudAddproductsbtn) {
            //     buttonHolder.appendChild(buttonAddFarmProducts);
            // }
            if (crudCancelPhyto) {
                buttonHolder.appendChild(buttonCancelPhyto);
            }
            var rnd = Math.random();
            var btn =
                '<button class="btn btn-default dropdown-toggle action-select"' +
                'type="button" id="dropdownMenu1' +
                rnd +
                '" data-toggle="dropdown"' +
                'aria-haspopup="true" aria-expanded="true"><span class="selectable-dots">...</span>' +
                '</button> <ul class = "dropdown-menu" aria-labelledby = "dropdownMenu1' +
                rnd +
                '" >' +
                '<li > < a href = "#" > Small < /a></li >' +
                '<li > < a href = "#" > Medium medium medium < /a></li >' +
                "<li > " +
                buttonHolder +
                "</li >" +
                '<li > < a href = "#" > Large large large large large large large large large < /a></li ></ul>';
            buttonSectionHolder = document.createElement("div");
            buttonDropDownBtn = document.createElement("button");
            buttonDropDownBtn.innerHTML = "<span class='selectable-dots'>...</span>";
            buttonDropDownBtn.classList.add("btn-default");
            buttonDropDownBtn.classList.add("btn");
            buttonDropDownBtn.classList.add("dropdown-toggle");
            buttonDropDownBtn.classList.add("action-list");
            buttonDropDownBtn.setAttribute("type", "button");
            buttonDropDownBtn.setAttribute("id", "dropdownMenu1" + rnd);
            buttonDropDownBtn.setAttribute("data-toggle", "dropdown");
            buttonDropDownBtn.setAttribute("aria-haspopup", "true");
            buttonDropDownBtn.setAttribute("aria-expanded", "false");
            dropDownParentList = document.createElement("ul");
            dropDownParentList.setAttribute("aria-labelledby", "dropdownMenu1" + rnd);
            dropDownParentList.classList.add("dropdown-menu");
            dropDownList = document.createElement("li");
            dropDownList.appendChild(buttonHolder);
            dropDownParentList.appendChild(dropDownList);
            buttonSectionHolder.appendChild(buttonDropDownBtn);
            buttonSectionHolder.appendChild(dropDownParentList);
            buttonDropDownBtn.addEventListener("click", function(event) {}, true);
            return buttonHolder;
        },

        cancelPhyto: function(data, reason) {
            var exporterConsignmentID = data.exporterConsignmentID;
            var url =
                serverURL +
                "exporterConsignment/cancelPhyoCertificate?exporterConsignmentID=" +
                exporterConsignmentID +
                "&reason=" +
                reason;
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                type: "post",
                success: function(data) {
                    controller.showToastMsg("Phyto Canceled", "#1a5589");
                    controller.refreshCrudTables("cancelPhyto");
                },
                fail: function(e) {
                    controller.showToastMsg("Cancellation Failed", "#ff6666");
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    controller.showToastMsg("Cancellation Failed", "#ff6666");
                },
            });
        },
        submitPipApplicationRecord: function(data) {
            if (data.pipApplicationRequestID) {
                var url =
                    serverURL +
                    "pipApplicationRequest/submitPipApplicationRequest?pipApplicationRequestID=" +
                    data.pipApplicationRequestID +
                    "";
                controller.allsubmitPipAppplication(url, "", true, function(data) {});
            }
        },

        steppersubmitPipApplicationRecord: function(recordID) {
            var url =
                serverURL +
                "pipApplicationRequest/submitPipApplicationRequest?pipApplicationRequestID=" +
                recordID +
                "";
            controller.allsubmitPipAppplication(url, "", true, function(data) {});
        },

        copyRecord: function(data) {
            if (data.exporterConsignmentID) {
                var url =
                    serverURL +
                    "exporterConsignment/copyExporterConsignment?exporterConsignmentID=" +
                    data.exporterConsignmentID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.pipApplicationID) {
                var url =
                    serverURL +
                    "pipApplication/copyPipApplication?pipApplicationID=" +
                    data.pipApplicationID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.pip_application_id) {
                var url =
                    serverURL +
                    "pipApplication/copyPipApplication?pip_application_id=" +
                    data.pip_application_id +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.consignmentInspectionRequestID) {
                var url =
                    serverURL +
                    "consignmentInspectionRequest/copyConsignmentInspectionRequest?consignmentInspectionRequestID=" +
                    data.consignmentInspectionRequestID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.pipApplicationRequestID) {
                var url =
                    serverURL +
                    "pipApplicationRequest/copyPipApplicationRequest?pipApplicationRequestID=" +
                    data.pipApplicationRequestID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.quarantineFacilityID) {
                var url =
                    serverURL +
                    "quarantineFacility/copyQuarantineFacility?quarantineFacilityTypeID=" +
                    data.quarantineFacilityID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.exporterFarmID) {
                var url =
                    serverURL +
                    "exporterFarm/copyExporterFarm?exporterFarmID=" +
                    data.exporterFarmID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.exporterFirmID) {
                var url =
                    serverURL +
                    "exporterFirm/copyExporterFirm?exporterFirmID=" +
                    data.exporterFirmID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.quarantine_facility_product_request_id) {
                var url =
                    serverURL +
                    "quarantineFacilityProductRequest/copyQuarantineFacilityProductRequest?quarantine_facility_product_request_id=" +
                    data.quarantine_facility_product_request_id +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.exportLowRiskCommodityID) {
                var url =
                    serverURL +
                    "exporterLowRiskCommodity/copyExporterLowRiskCommodity?exporterLowRiskCommodityID=" +
                    data.exportLowRiskCommodityID +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            } else if (data.pestRiskAnalysisRequest_id) {
                var url =
                    serverURL +
                    "pestRiskAnalysisRequestList/copyPestRiskAnalysisRequestList?petRiskAnalysisRequest_id=" +
                    data.pestRiskAnalysisRequest_id +
                    "";
                controller.allCopyPostRequest(url, "", true, function() {});
            }
        },
        deactivateRecords: function(data) {
            if (data.import_requirement_id) {
                var url =
                    serverURL +
                    "importRequirement/deleteImportRequirement?importRequirement_id=" +
                    data.import_requirement_id +
                    "";
                var formData = {
                    importRequirement_id: data.wFTransition_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            }
            if (data.export_requirement_id) {
                var url =
                    serverURL +
                    "exportRequirement/deleteExportRequirement?exportRequirement_id=" +
                    data.export_requirement_id +
                    "";

                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            }
            if (data.menuRoles_id) {
                var url =
                    serverURL +
                    "menuRoles/deleteMenuRoles?menuRole_id=" +
                    data.menuRoles_id +
                    "";
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            }
            if (data.menuRoles_id) {
                var url =
                    serverURL +
                    "menuRoles/deleteMenuRoles?menuRole_id=" +
                    data.menuRoles_id +
                    "";
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.certificate_type_id) {
                var url =
                    serverURL +
                    "certificateType/deleteCertificateType?certificateTypeID=" +
                    data.certificate_type_id +
                    "";
                var formData = {
                    certificateTypeID: data.certificate_type_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.consigneeID) {
                var url =
                    serverURL +
                    "consignee/deleteConsignee?consigneeID=" +
                    data.consigneeID +
                    "";
                var formData = {
                    consigneeID: data.consigneeID,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.researchInstituteID) {
                var url =
                    serverURL +
                    "researchInstitute/deleteResearchInstitute?researchInstitute_id=" +
                    data.researchInstituteID +
                    "";
                var formData = {
                    researchInstitute_id: data.researchInstituteID,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.import_condition_id) {
                var url =
                    serverURL +
                    "importcondition/deleteImportCondition?gender_id=" +
                    data.import_condition_id +
                    "";
                var formData = {
                    gender_id: data.import_condition_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.agents_id) {
                var url =
                    serverURL + "agentManagement/deleteAgent?id=" + data.agent.agents_id;
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.agent_mgt_id) {
                var url =
                    serverURL + "agentManagement/deleteAgent?id=" + data.agent_mgt_id;
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.licensingBodyID) {
                var url =
                    serverURL +
                    "licensingBody/deleteLicensingBody?licensingBodyID=" +
                    data.licensingBodyID +
                    "";
                var formData = {
                    licensingBodyID: data.licensingBodyID,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.hs_code_id) {
                var url =
                    serverURL + "hscode/deleteHsCode?country_id=" + data.hs_code_id + "";
                var formData = {
                    country_id: data.hs_code_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.regionCounty_id) {
                var url =
                    serverURL +
                    "regionCounty/deleteRegionCounty?regionCounty_id=" +
                    data.regionCounty_id +
                    "";
                var formData = {
                    regionCounty_id: data.regionCounty_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.office_location_id) {
                var url =
                    serverURL +
                    "officeLocation/deleteOfficeLocation?officeLocation_id=" +
                    data.office_location_id +
                    "";
                var formData = {
                    officeLocation_id: data.office_location_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            } else if (data.regionID) {
                var url =
                    serverURL + "region/deleteRegion?region_id=" + data.regionID + "";
                var formData = {
                    region_id: data.regionID,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            }
            if (data.wfWorkflow_id) {
                var url =
                    serverURL +
                    "wfWorkFlow/deleteWFWorkFlow?wfWorkFlow_id=" +
                    data.wfWorkflow_id +
                    "";
                var formData = {
                    wfWorkFlow_id: data.wfWorkflow_id,
                };
                var async_status = true;
                controller.allPostDeactivateRequest(
                    url,
                    formData,
                    async_status,
                    function(datam, status) {}
                );
            }
        },
        deleteRecord: function(data) {
            try {
                var url = formObj.deleteUrl + data[formObj.primaryID];
                var async_status = true;
                controller.allPostDeleteRequest(
                    url,
                    "",
                    async_status,
                    function(datam, status) {}
                );
            } catch (error) {}
        },
        deleteRecordFormObj2: function(data) {
            try {
                var url = formObj2.deleteUrl + data[formObj2.primaryID];
                var async_status = true;
                controller.allPostDeleteRequest(
                    url,
                    "",
                    async_status,
                    function(data, status) {
                        if (data) {
                            controller.refreshCrudTables("facilitycommodities");
                        } else {}
                    }
                );
            } catch (error) {}
        },
        submitprint: function(data, listFormName) {
            if (listFormName == "onetime_export") {
                var url =
                    serverURL +
                    "oneTimeExport/submitOnetimeExport?oneTimeExportID=" +
                    data.onetime_export_id +
                    "";
            } else {
                var url =
                    serverURL +
                    "onetimeImport/submitOnetimeImport?oneTimeImportID=" +
                    data.onetime_import_id +
                    "";
            }
            $.ajax({
                url: url,
                async: true,
                type: "post",
                contentType: true,
                processData: false,
                encoding: null,
                contentType: "application/json",
                beforeSend: function(request) {
                    request.overrideMimeType("text/plain; charset=x-user-defined");
                },
                responseType: "arraybuffer",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data, textStatus, xhr) {
                    var binary = "";
                    var responseTextLen = data.length;
                    for (i = 0; i < responseTextLen; i++) {
                        binary += String.fromCharCode(data.charCodeAt(i) & 255);
                    }

                    /**
                     * Display a base64 URL inside an iframe in another window.
                     */
                    function debugBase64(base64URL) {
                        var win = window.open();
                        win.document.write(
                            '<iframe src="' +
                            base64URL +
                            '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>'
                        );
                    }
                    var a = document.createElement("a");
                    a.href = "data:application/pdf;base64," + btoa(binary);
                    a.target = "_blank";
                    debugBase64(a.href);
                },
                fail: function(xhr, textStatus) {
                    // co/ntroller.showToastMsg(xhr.responseJSON.data, "#ff6666");
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                    try {
                        controller.showToastMsg(xhr.responseJSON.data, "#ff6666");
                    } catch (error) {
                        resp = JSON.parse(xhr.responseText);
                        controller.showToastMsg(resp.data, "#ff6666");
                    }
                },
            });
        },

        submitDraftprint: function(data, listFormName) {
            if (listFormName == "onetime_export") {
                var url =
                    serverURL +
                    "oneTimeExport/submitOnetimeExportDraft?oneTimeExportID=" +
                    data.onetime_export_id +
                    "";
            } else {
                var url =
                    serverURL +
                    "onetimeImport/submitDraftOnetimeImport?oneTimeImportID=" +
                    data.onetime_import_id +
                    "";
            }

            $.ajax({
                url: url,
                async: true,
                type: "post",
                contentType: true,
                processData: false,
                encoding: null,
                contentType: "application/json",
                beforeSend: function(request) {
                    request.overrideMimeType("text/plain; charset=x-user-defined");
                },
                responseType: "arraybuffer",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data, textStatus, xhr) {
                    var binary = "";
                    var responseTextLen = data.length;
                    for (i = 0; i < responseTextLen; i++) {
                        binary += String.fromCharCode(data.charCodeAt(i) & 255);
                    }

                    /**
                     * Display a base64 URL inside an iframe in another window.
                     */
                    function debugBase64(base64URL) {
                        var win = window.open();
                        win.document.write(
                            '<iframe src="' +
                            base64URL +
                            '" frameborder="0" style="border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;" allowfullscreen></iframe>'
                        );
                    }
                    var a = document.createElement("a");
                    a.href = "data:application/pdf;base64," + btoa(binary);
                    a.target = "_blank";
                    debugBase64(a.href);
                },
                fail: function(xhr, textStatus) {
                    // co/ntroller.showToastMsg(xhr.responseJSON.data, "#ff6666");
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                    try {
                        controller.showToastMsg(xhr.responseJSON.data, "#ff6666");
                    } catch (error) {
                        resp = JSON.parse(xhr.responseText);
                        controller.showToastMsg(resp.data, "#ff6666");
                    }
                },
            });
        },

        renderInspectionButtons: function(data, cell, row, formName, reportType) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            buttonHolder = document.createElement("div");
            buttonViewInspect = document.createElement("button");
            console.log("formNameformName", formName);
            if (formName == "exporterProduct") {
                buttonViewInspect.innerHTML = "View<i class='icon-arrow-right'></i>";
            } else {
                buttonViewInspect.innerHTML = "Inspect<i class='icon-arrow-right'></i>";
            }
            buttonViewInspect.classList.add("xcrud-action");
            buttonViewInspect.classList.add("btn");
            buttonViewInspect.classList.add("btn-info");
            buttonViewInspect.classList.add("btn-sm");
            var listFormName = "";

            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewInspect.setAttribute("form-name", listFormName);
            buttonViewInspect.setAttribute("type", "button");
            buttonViewInspect.addEventListener(
                "click",
                function() {
                    viewRowData(data, listFormName);
                    setTimeout(function() {
                        $(".crud_section_2").hide();
                    }, 200);
                },
                false
            );

            buttonHolder.appendChild(buttonViewInspect);

            return buttonHolder;
        },

        renderInspectionButtonsLab: function(data, cell, row, formName, reportType) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            buttonHolder = document.createElement("div");
            buttonViewInspect = document.createElement("button");
            console.log("formNameformName", formName);
            if (formName == "exporterProduct") {
                buttonViewInspect.innerHTML = "View<i class='icon-arrow-right'></i>";
            } else {
                buttonViewInspect.innerHTML = "Inspect<i class='icon-arrow-right'></i>";
            }
            buttonViewInspect.classList.add("xcrud-action");
            buttonViewInspect.classList.add("btn");
            buttonViewInspect.classList.add("btn-info");
            buttonViewInspect.classList.add("btn-sm");
            var listFormName = "";

            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewInspect.setAttribute("form-name", listFormName);
            buttonViewInspect.setAttribute("type", "button");
            buttonViewInspect.addEventListener(
                "click",
                function() {
                    viewRowData(data, listFormName);
                    setTimeout(function() {
                        $(".crud_section_2").hide();
                    }, 200);
                },
                false
            );

            buttonRequiresLab = document.createElement("button");
            buttonRequiresLab.innerHTML =
                "Requires Lab<i class='icon-arrow-right'></i>";
            buttonRequiresLab.classList.add("xcrud-action");
            buttonRequiresLab.classList.add("btn");
            buttonRequiresLab.classList.add("btn-success");
            buttonRequiresLab.classList.add("btn-sm");
            buttonRequiresLab.classList.add("addregion");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonRequiresLab.setAttribute("form-name", listFormName);
            buttonRequiresLab.setAttribute("type", "button");
            buttonRequiresLab.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.getofficeLocation();
                        $(".modal.fade.requiresLab").modal("show");
                        try {
                            var expoexporterconsinmentid =
                                allFormObj["parent_selected"]["consignmentInspectionRequestID"];
                        } catch (error) {}
                        var exporterConID = localStorage.setItem(
                            "exporterConsignmentID",
                            expoexporterconsinmentid
                        );
                        $("#requiresSamplingbtn").click(function(event) {
                            event.stopImmediatePropagation();
                            event.stopPropagation();
                            event.preventDefault();
                            var expoexporterconsinmentid = 206;
                            var office_location_id =
                                document.getElementById("office_location_ID").value;
                            var labreason = document.getElementById("labreason").value;
                            if (labreason == null || labreason == "") {
                                controller.showToastMsg("Fill all Fields to Proceed", "#ff6666");
                            } else {
                                $(".modal.fade.requiresLab").modal("hide");
                                controller.createLabData(
                                    data,
                                    expoexporterconsinmentid,
                                    office_location_id,
                                    labreason
                                );
                            }
                        });
                    }
                },
                false
            );

            buttonHolder.appendChild(buttonViewInspect);
            buttonHolder.appendChild(buttonRequiresLab);

            return buttonHolder;
        },

        renderConfirmPaymentsButtons: function(
            data,
            cell,
            row,
            formName,
            reportType
        ) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            buttonHolder = document.createElement("div");
            buttonViewConfirmPayments = document.createElement("button");
            console.log("formNameformName", formName);
            if (
                formName == "exporterConsignmentVarietyDetailssection" ||
                formName == "exporterFirm" ||
                formName == "exporterLowRiskCommodity" ||
                formName == "exporterFarm" ||
                formName == "exporterProduct" ||
                formName == "exporterFarmproducts"
            ) {
                buttonViewConfirmPayments.innerHTML =
                    "View<i class='icon-arrow-right'></i>";
            } else {
                buttonViewConfirmPayments.innerHTML =
                    "Confirm Payments<i class='icon-arrow-right'></i>";
            }
            buttonViewConfirmPayments.classList.add("xcrud-action");
            buttonViewConfirmPayments.classList.add("btn");
            buttonViewConfirmPayments.classList.add("btn-info");
            buttonViewConfirmPayments.classList.add("btn-sm");
            var listFormName = "";

            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewConfirmPayments.setAttribute("form-name", listFormName);
            buttonViewConfirmPayments.setAttribute("type", "button");
            buttonViewConfirmPayments.addEventListener(
                "click",
                function() {
                    viewRowData(data, listFormName);
                    setTimeout(function() {
                        $(".crud_section_2").hide();
                    }, 200);
                },
                false
            );

            buttonHolder.appendChild(buttonViewConfirmPayments);
            return buttonHolder;
        },
        renderPhytoListButtons: function(data, cell, row, formName, reportType) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            buttonHolder = document.createElement("div");
            buttonDraftPhyto = document.createElement("button");
            buttonDraftPhyto.innerHTML = "Print Draft Phyto";
            buttonDraftPhyto.classList.add("xcrud-action");
            buttonDraftPhyto.classList.add("btn");
            buttonDraftPhyto.classList.add("btn-warning");
            buttonDraftPhyto.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonDraftPhyto.setAttribute("form-name", listFormName);
            buttonDraftPhyto.setAttribute("type", "button");
            buttonDraftPhyto.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.signPrintDraft("samplePhyto", data, reportType);
                    }
                },
                false
            );

            buttonViewDetails = document.createElement("button");
            buttonViewDetails.innerHTML = "View<i class='icon-arrow-right'></i>";
            buttonViewDetails.classList.add("xcrud-action");
            buttonViewDetails.classList.add("btn");
            buttonViewDetails.classList.add("btn-info");
            buttonViewDetails.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonViewDetails.setAttribute("form-name", listFormName);
            buttonViewDetails.setAttribute("type", "button");
            buttonViewDetails.addEventListener(
                "click",
                function() {
                    crudviewdatainformation(data);

                    setTimeout(function() {
                        $(".crud_section_2").hide();
                    }, 200);
                },
                false
            );

            buttonHolder.appendChild(buttonViewDetails);
            buttonHolder.appendChild(buttonDraftPhyto);

            return buttonHolder;
        },
        renderImportInterceptionListButtons: function(
            data,
            cell,
            row,
            formName,
            reportType
        ) {
            var btnType = "edit";
            var btnText = "Edit";
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            buttonHolder = document.createElement("div");
            buttonPrintInterception = document.createElement("button");
            buttonPrintInterception.innerHTML = "Print Report";
            buttonPrintInterception.classList.add("xcrud-action");
            buttonPrintInterception.classList.add("btn");
            buttonPrintInterception.classList.add("btn-warning");
            buttonPrintInterception.classList.add("btn-sm");
            var listFormName = "";
            if (formName == "") {
                listFormName = this.myFormObj.formName;
            } else {
                listFormName = formName;
            }
            buttonPrintInterception.setAttribute("form-name", listFormName);
            buttonPrintInterception.setAttribute("type", "button");
            buttonPrintInterception.addEventListener(
                "click",
                function(event) {
                    event.stopImmediatePropagation();
                    event.stopPropagation();
                    event.preventDefault();
                    if (!event.detail || event.detail == 1) {
                        controller.printInterceptionReport(
                            "interceptionReport",
                            data,
                            reportType
                        );
                    }
                },
                false
            );
            buttonHolder.appendChild(buttonPrintInterception);
            return buttonHolder;
        },
        renderListButton: function(data, cell, row, btnText, btnType, classArr) {
            var row = cell.getRow();
            var data = row.getData();
            var element = row.getElement();
            var btnTitle = "";
            if (btnType == "edit") {
                btnTitle = "Edit";
            } else if (btnType == "delete") {
                btnTitle = "Delete";
            } else if (btnType == "activate") {
                btnTitle = "Activate";
            }
            buttonEdit = document.createElement("button");
            buttonEdit.innerHTML = btnText;
            buttonEdit.classList.add("xcrud-action");
            buttonEdit.classList.add("btn");
            buttonEdit.classList.add("btn-warning");
            buttonEdit.classList.add("btn-sm");
            buttonEdit.addEventListener(
                "click",
                function() {
                    if (btnType == "edit") {
                        controller.editRow(data, this);
                    } else if (btnType == "delete") {
                        controller.deleteRow(data, this);
                    } else if (btnType == "activate") {
                        controller.activateRow(data, this);
                    }
                },
                false
            );
            return buttonEdit;
        },
        loadSideMenu: function(page, callbackF) {
            var sideMenu = "<div class='ui accordion'>";
            org = window.org;
            if (org == "Admin") {
                accessArr = window.windowAccessAdmin;
                var isOpen = "";
                var tmpTopMenu = "";
                var tmpSideMenu = "";
                var tmpMenu = "";
                var parentCnt = 0;
                var childCnt = 0;
                var t = 0;
                for (key in accessArr) {
                    t++;
                    if (accessArr[key].identifier == "main_menu") {
                        if (parentCnt > 0) {
                            var tmpTopMenu =
                                "<div class='title " +
                                isOpen +
                                "'><i class='dropdown icon'></i>" +
                                tmpMenu +
                                "</div><div class='content " +
                                isOpen +
                                "'>";
                            sideMenu += tmpTopMenu + tmpSideMenu + "</div>";
                            tmpMenu = accessArr[key].windowName;
                            tmpSideMenu = "";
                        } else {
                            tmpMenu = accessArr[key].windowName;
                        }
                        parentCnt++;
                        isOpen = "";
                    } else if (accessArr[key].identifier == page) {
                        if (accessArr[key].identifier == "activity") {
                            tmpSideMenu +=
                                "<a class='item active mission-arrival-notice-menu ' href='./#" +
                                org +
                                "/" +
                                accessArr[key].identifier +
                                "'><i class='" +
                                accessArr[key].icon +
                                "'></i><span class='alertNo'></span>" +
                                accessArr[key].windowName +
                                "</a>";
                        } else {
                            tmpSideMenu +=
                                "<a class='item active mission-arrival-notice-menu' href='./#" +
                                org +
                                "/" +
                                accessArr[key].identifier +
                                "'><i class='" +
                                accessArr[key].icon +
                                "'></i>" +
                                accessArr[key].windowName +
                                "</a>";
                            isOpen = "active";
                        }
                    } else {
                        if (accessArr[key].identifier == "activity") {
                            tmpSideMenu +=
                                "<a class='item mission-arrival-notice-menu' href='./#" +
                                org +
                                "/" +
                                accessArr[key].identifier +
                                "'><i class='" +
                                accessArr[key].icon +
                                "'></i><span class='alertNo'></span>" +
                                accessArr[key].windowName +
                                "</a>";
                        } else {
                            tmpSideMenu +=
                                "<a class='item mission-arrival-notice-menu' href='./#" +
                                org +
                                "/" +
                                accessArr[key].identifier +
                                "'><i class='" +
                                accessArr[key].icon +
                                "'></i>" +
                                accessArr[key].windowName +
                                "</a>";
                        }
                    }
                }
            } else {
                var isOpen = "active";
                var tmpTopMenu = "";
                var tmpSideMenu = "";
                var tmpMenu = "";
                accessArr = window.windowAccess;
                var parentCnt = 0;
                var childCnt = 0;
                var t = 0;
                var x = 0;
                for (key in accessArr) {
                    t++;
                    if (accessArr[key].identifier == "main_menu") {
                        if (parentCnt > 0) {
                            x++;
                            if (x == 1) {}
                            var tmpTopMenu =
                                "<div class='title " +
                                isOpen +
                                "'><i class='dropdown icon'></i>" +
                                tmpMenu +
                                "</div><div class='content " +
                                isOpen +
                                "'>";
                            sideMenu += tmpTopMenu + tmpSideMenu + "</div>";
                            tmpMenu = accessArr[key].windowName;
                            tmpSideMenu = "";
                        } else {
                            tmpMenu = accessArr[key].windowName;
                        }
                        parentCnt++;
                        isOpen = "";
                    } else if (accessArr[key].identifier + "-listing" == page) {
                        if (accessArr[key].identifier == "activity") {
                            if (
                                org == accessArr[key].rights ||
                                accessArr[key].rights == "all"
                            ) {
                                tmpSideMenu +=
                                    "<a class='item active mission-arrival-notice-menu' href='./#" +
                                    org +
                                    "/" +
                                    accessArr[key].identifier +
                                    "-listing'><i class='" +
                                    accessArr[key].icon +
                                    "'></i><span class='alertNo'></span>" +
                                    accessArr[key].windowName +
                                    "</a>";
                            }
                        } else {
                            if (
                                org == accessArr[key].rights ||
                                accessArr[key].rights == "all"
                            ) {
                                tmpSideMenu +=
                                    "<a class='item active mission-arrival-notice-menu' href='./#" +
                                    org +
                                    "/" +
                                    accessArr[key].identifier +
                                    "-listing'><i class='" +
                                    accessArr[key].icon +
                                    "'></i>" +
                                    accessArr[key].windowName +
                                    "</a>";
                            }
                        }
                        isOpen = "active";
                    } else {
                        if (accessArr[key].identifier == "activity") {
                            if (
                                org == accessArr[key].rights ||
                                accessArr[key].rights == "all"
                            ) {
                                tmpSideMenu +=
                                    "<a class='item mission-arrival-notice-menu' href='./#" +
                                    org +
                                    "/" +
                                    accessArr[key].identifier +
                                    "-listing'><i class='" +
                                    accessArr[key].icon +
                                    "'></i><span class='alertNo'></span>" +
                                    accessArr[key].windowName +
                                    "</a>";
                            }
                        } else {
                            if (
                                org == accessArr[key].rights ||
                                accessArr[key].rights == "all"
                            ) {
                                tmpSideMenu +=
                                    "<a class='item mission-arrival-notice-menu' href='./#" +
                                    org +
                                    "/" +
                                    accessArr[key].identifier +
                                    "-listing'><i class='" +
                                    accessArr[key].icon +
                                    "'></i>" +
                                    accessArr[key].windowName +
                                    "</a>";
                            }
                        }
                    }
                }
            }
            sideMenu += "</div>";
            $(".sidemenu").html(sideMenu);
            callbackF();
        },
        setMenu: function(page, page2) {
            if (page != "Admin") {
                $(".dashboardmenu").html(
                    "<a href='./#" +
                    page +
                    "/dashboard' class='header'> <i class='dashboard icon'></i> Dashboard </a>"
                );
                $(".sharedLinks").html(
                    "<a class='item profileLink' href='./#" +
                    page +
                    "/profile'><i class='user icon'></i>Profile</a>" +
                    "<a class='item changePassLink' href='javascript:controller.showMyPassForm();'><i class='edit icon'></i>Change Password</a>" +
                    "<div class='divider'></div>" +
                    "<a class='item' href='javascript:controller.logout();'><i class='sign out icon'></i>Logout</a>"
                );
                controller.loadSideMenu(page2, function() {
                    $(".ui.accordion").accordion();
                });
            } else if (page == "Admin") {
                $(".dashboardmenu").html(
                    "<a href='./#Admin/dashboard' class='header'> <i class='dashboard icon'></i> Dashboard </a>"
                );
                $(".sharedLinks").html(
                    "<a class='item profileLink' href='./#" +
                    page +
                    "/profile'><i class='user icon'></i>Profile</a>" +
                    "<a class='item changePassLink' href='javascript:controller.showMyPassForm();'><i class='edit icon'></i>Change Password</a>" +
                    "<div class='divider'></div>" +
                    "<a class='item' href='javascript:controller.logout();'><i class='sign out icon'></i>Logout</a>"
                );
                controller.loadSideMenu(page2, function() {
                    $(".ui.accordion").accordion();
                });
            }
            if (
                localStorage.getItem("alertNo") != "" ||
                localStorage.getItem("alertNo") != undefined ||
                localStorage.getItem("alertNo") != null ||
                localStorage.getItem("alertNo") != "null"
            ) {
                var alertHtml =
                    "<span class='alertNoMsg'>" +
                    localStorage.getItem("alertNo") +
                    "</span>";
                $(".alertNo").html(alertHtml);
            }
        },
        logout: function() {
            var logoutURL = serverURL + "api/auth/oauth/token";
            $.ajax({
                url: logoutURL,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                method: "delete",
                async: true,
                success: function(data) {},
                fail: function() {
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#blinder").hide();
                },
            });
            localStorage.setItem("userObj", "");
            localStorage.setItem("companyDetails", "");
            window.location = "login.html";
        },
        hasAdminRights: function() {
            rolesArr = userObj.roles;
            var count = 0;
            for (var j = 0; j < rolesArr.length; j++) {
                var itemO = rolesArr[j];
                if (itemO.name == "ROLE_ADMIN") {
                    count++;
                }
            }
            return count;
        },
        hasUserRights: function() {},
        hasModeratorRights: function() {
            rolesArr = userObj.roles;
            var count = 0;
            for (var j = 0; j < rolesArr.length; j++) {
                var itemO = rolesArr[j];
                if (itemO.name == "ROLE_MODERATOR") {
                    count++;
                }
            }
            return count;
        },
        formatDateFilter: function(date) {
            var d = new Date(date),
                month = "" + (d.getMonth() + 1),
                day = "" + d.getDate(),
                year = d.getFullYear();
            if (month.length < 2) month = "0" + month;
            if (day.length < 2) day = "0" + day;
            return [year, month, day].join("-");
        },
        savePasswordEntity: function() {
            var url = "";
            var formJson = $("#password-form-setup").serializeObject();
            if (formJson.passwordForm_users_id == "") {
                alert("Cannot Edit. User not identified");
                return false;
            } else {
                url = editPasswordUrl;
                formJson["users_id"] = $("#passwordForm_users_id").val();
                delete formJson.passwordForm_users_id;
                formJson["email"] = $("#passwordForm_Email").val();
                delete formJson.passwordForm_Email;
                formJson["oldPassword"] = $("#passwordForm_oldPassword").val();
                delete formJson.passwordForm_oldPassword;
                formJson["newPassword"] = $("#passwordForm_newPassword").val();
                delete formJson.passwordForm_newPassword;
            }
            var formData = JSON.stringify(formJson);
            crud.saveFormDetails(formData, url, function(output) {
                $(".ui.basic.modal.change_password").modal("hide");
            });
        },
        showPassForm: function() {
            var uId = $("#users_id").val();
            var uEmail = $("#email").val();
            if (uId != "" && uEmail != "") {
                $("#passwordForm_users_id").val(uId);
                $("#passwordForm_Email").val(uEmail);
                $(".ui.basic.modal.change_password").modal("show");
            } else {
                alert("Select a User and/or ensure email is available to proceed");
            }
        },
        showMyPassForm: function() {
            var uEmail = userObj.email;
            var uId = userObj.id;
            if (uId != "" && uEmail != "") {
                $("#passwordForm_users_id").val(uId);
                $("#passwordForm_Email").val(uEmail);
                $(".ui.basic.modal.change_password").modal("show");
            } else {
                alert("Select a User and/or ensure email is available to proceed");
            }
        },
        getTitle: function(menuId1, menuId2) {
            if (menuId1 != "Admin") {
                if (menuId1 == "shared") {
                    menuId1 = "User Profile";
                }
                var menu = menuId2;
                var sideMenu = "";
                accessArr = window.windowAccess;
                org = window.org;
                for (key in accessArr) {
                    if (accessArr[key].identifier == menu) {
                        return accessArr[key].windowName;
                    }
                    if (accessArr[key].identifier + "-form" == menu) {
                        return "New " + accessArr[key].windowName + " Application";
                    }
                    if (accessArr[key].identifier + "-listing" == menu) {
                        return accessArr[key].windowName + " Listings";
                    }
                }
            } else if (menuId1 == "Admin") {
                var menu = menuId2;
                var sideMenu = "";
                accessArr = window.windowAccessAdmin;
                org = window.org;
                for (key in accessArr) {
                    if (accessArr[key].identifier == menu) {
                        return accessArr[key].windowName;
                    }
                }
            }
        },
        getRequest: function(url, async_status, callBack) {
            $.ajax({
                url: url,
                type: "GET",
                async: async_status,
                success: function(data, textStatus, xhr) {
                    controller.hide_progress();
                    callBack(data, true);
                },
                fail: function(xhr, textStatus) {
                    controller.hide_progress();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        var errorArr = obj.errors;
                        var errorMsg = "";
                        for (var i in errorArr) {
                            errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
                        }
                        callBack(errorMsg, false);
                        controller.showToastMsg(
                            "Error! Fields are empty" + errorMsg,
                            "#ff6666"
                        );
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus) {
                    controller.hide_progress();
                    callBack(xhr, false);
                },
            });
        },
        getAuthRequest: function(url, async_status, handleData) {
            $.ajax({
                url: url,
                type: "GET",
                async: async_status,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data) {
                    handleData(data, true);
                    controller.hide_progress();
                },
                fail: function(xhr) {
                    handleData(xhr, false);
                    controller.hide_progress();
                },
                error: function(xhr, textStatus) {
                    handleData(xhr, false);
                    controller.hide_progress();
                },
            });
        },
        getPOSTAuthRequest: function(url, async_status, handleData) {
            $.ajax({
                url: url,
                type: "POST",
                async: async_status,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data) {
                    handleData(data, true);
                    controller.hide_progress();
                },
                fail: function(xhr) {
                    handleData(xhr, false);
                    controller.hide_progress();

                },
                error: function(xhr, textStatus) {
                    handleData(xhr, false);
                    controller.hide_progress();
                },
            });
        },
        getImorterExportAuthRequest: function(url, async_status, handleData) {
            $.ajax({
                url: url,
                type: "GET",
                async: async_status,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data) {
                    handleData(data, true);
                },
                fail: function(xhr) {
                    handleData(xhr, false);
                },
                error: function(xhr, textStatus) {
                    handleData(xhr, false);
                },
            });
        },
        getAFAAuthRequest: function(url, async_status, handleData) {
            controller.show_progress();
            $.ajax({
                url: url,
                type: "GET",
                async: async_status,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                success: function(data) {
                    handleData(data, true);
                    if (
                        data.licenseno == null ||
                        (data.licenseno == "null" && data.file == "null") ||
                        data.file == null
                    ) {
                        controller.hide_progress();
                        controller.showToastMsg("AFA Licence Certicate No Found", "#ff6666");
                    } else {
                        controller.hide_progress();
                        $(".viewCertBtn_holder").show();
                        $("#exporterLicenseNo").val(data.licenseno);
                        $("#import_license_no").val(data.licenseno);
                        controller.showToastMsg(
                            "Successfully Retrieved...Kindly Click On The Button To View AFA Licence",
                            "#1a5589"
                        );
                    }
                },
                fail: function(xhr) {
                    handleData(xhr, false);
                    controller.hide_progress();
                    controller.showToastMsg("AFA Licence Certicate No Found", "#ff6666");
                    $(".viewCertBtn_holder").hide();
                },
                error: function(xhr, textStatus) {
                    handleData(xhr, false);
                    controller.hide_progress();
                    controller.showToastMsg("AFA Licence Certicate No Found", "#ff6666");
                    $(".viewCertBtn_holder").hide();
                },
            });
        },
        assignPrintingFunc: function(url, formData, async_status, handleData) {
            var allActivities = JSON.stringify(formData);
            var url = serverURL + "assignAuthorisation/assignAuthorisation";
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: allActivities,
                contentType: "application/json",
                success: function(data) {
                    var jsonData = data;
                    controller.showToastMsg(
                        "Successfully Authorized for printing",
                        "#1a5589"
                    );
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    handleData(e);
                    controller.showToastMsg(
                        "Record not forwarded. kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    controller.showToastMsg(
                        "Record not forwarded.kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
            });
        },
        authorizePhytoPrintingFunc: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var allActivities = JSON.stringify(formData);
            var url = serverURL + "assignAuthorisation/assignAuthorisation";
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: allActivities,
                contentType: "application/json",
                success: function(data) {
                    var jsonData = data;
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    handleData(e);
                    controller.showToastMsg(
                        "Record not forwarded. kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    controller.showToastMsg(
                        "Record not forwarded.kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
            });
        },
        findExporterConsignmentReportBydocstatus: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var docstatusid = document.getElementById("docstatus").value;
            var url = serverURL + " " + docstatusid + "";
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: allActivities,
                contentType: "application/json",
                success: function(data) {
                    var jsonData = data;
                    controller.showToastMsg(
                        "Successfully Authorized for printing",
                        "#1a5589"
                    );
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    handleData(e);
                    controller.showToastMsg(
                        "Record not forwarded. kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    controller.showToastMsg(
                        "Record not forwarded.kindly select the record and try again. If error persists kindly contact EAA Admin",
                        "#ff6666"
                    );
                    controller.refreshCrudTables();
                },
            });
        },
        allPostgetRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {},
                fail: function(e) {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        allPostgetproductRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    handleData(data);
                },
                fail: function(e) {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        allPostgetproductviewRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    if (
                        data.requiresLicensingBody == true ||
                        data.requiresLicensingBody == "true"
                    ) {
                        $(".exporterLicenseNo_holder").show();
                        $(".licensingBodyID_holder").show();
                        $(".licensingBody_id_holder").show();
                    } else if (
                        data.requiresLicensingBody == false ||
                        data.requiresLicensingBody == "false"
                    ) {
                        $(".licensingBody_id_holder").hide();
                        $(".exporterLicenseNo_holder").hide();
                        $(".licensingBodyID_holder").hide();
                        $("#licensingBodyID").attr("value", "");
                        var option = "";
                        option += '<option selected value="" ></option>';
                        $("#licensingBodyID").html(option);
                    }
                },
                fail: function(e) {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        exporterPostRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg("Saved Successfully", "#1a5589");
                    controller.refreshExportersData();
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    $("#blinder").hide();
                },
            });
        },
        inspectionChecklistPostRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    try {
                        $(".requirementModal").modal("hide");
                        $(".requirementModal_export").modal("hide");
                        $(".requirementModal_import").modal("hide");
                        $(".requirementModal_quarantine").modal("hide");
                    } catch (error) {}
                    controller.showToastMsg("Inspected And Passed", "#1a5589");
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                },
            });
        },
        inspectionChecklistRejectPostRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    $(".requirementModal").modal("hide");
                    $(".requirementModal_export").modal("hide");
                    $(".requirementModal_import").modal("hide");
                    $(".requirementModal_quarantine").modal("hide");

                    controller.showToastMsg("Inspected And Failed", "#1a5589");
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                },
            });
        },
        updateExporterPostRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                type: "post",
                data: formData,
                success: function(data) {
                    handleData(data);
                },
                fail: function(e) {},
                error: function(xhr, textStatus, errorThrown) {},
            });
        },

        allPostRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            console.log("userObj.accessToken")
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
                    "Content-Type": "application/json",
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    try {
                        $("#consigneeform")[0].reset();
                    } catch (error) {}
                    controller.showToastMsg("Saved Successfully", "#1a5589");
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },


          allPostRequestDevice: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            console.log("userObj.accessToken")
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
                    "Content-Type": "application/json",
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    try {
                        $("#consigneeform")[0].reset();
                    } catch (error) {}
                    // controller.showToastMsg("Saved Successfully", "#1a5589");
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },

        allPutRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            console.log("userObj.accessToken")
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
                    "Content-Type": "application/json",
                },
                async: async_status,
                type: "put",
                data: formData,
                success: function(data) {
                    try {
                        $("#consigneeform")[0].reset();
                    } catch (error) {}
                    controller.showToastMsg("Saved Successfully", "#1a5589");
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },

        voidApplicationRequest: function(url, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg("Application Voided Successfully !", "#1a5589");
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },

        negotiateApplicationRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg("Negotion Created Successfully !", "#1a5589");
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },

        removenegotiateApplicationRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg(
                        "Negotiation Deactivated Successfully !",
                        "#1a5589"
                    );
                    handleData(data);
                    controller.refreshCrudTables();
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");
                    }
                },
            });
        },

        uploadOtherDocuments: function(
            formData,
            name,
            description,
            recordID,
            tableregisterID
        ) {
            var url =
                serverURL +
                "globalDocument/addGlobalDocument?recordId=" +
                recordID +
                "&name=" +
                name +
                "&tableRegisterId=" +
                tableregisterID +
                "&description=" +
                description +
                "&documentUploadType_id=0";
            var async_status = true;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                type: "post",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        $.trim($("#name_value").val(""));
                        $.trim($("#description_value").val(""));
                        $.trim($("#filename").val(""));

                        $(".reportAttachmentUpload").modal("hide");
                        $("#confirmUploadBtn").html("Confirm Upload");
                        $("#confirmUploadBtn").prop("disabled", false); //true|disabled will work on all
                        controller.showToastMsg("Document Uploaded Successfully", "#1a5589");
                        loadotherdocuments(recordID);
                    }
                },
                fail: function(xhr, textStatus) {
                    controller.showToastMsg("Document Upload Failed, Try again", "#ff6666");
                    $("#confirmUploadBtn").html("Confirm Upload");
                    $("#confirmUploadBtn").prop("disabled", false); //true|disabled will work on all
                },
                error: function(xhr, textStatus) {
                    controller.showToastMsg("Document Upload Failed, Try again", "#ff6666");
                    $("#confirmUploadBtn").html("Confirm Upload");
                    $("#confirmUploadBtn").prop("disabled", false); //true|disabled will work on all
                },
            });
        },

        uploadPaymnetAdvise: function(
            reponseObj,
            pipApplicationID,
            recordID,
            paymentRefNo,
            othermodesValue,
            formData,
            facility_id
        ) {
            var url =
                serverURL +
                "payment/updateAndUploadPayment?paymentId=" +
                recordID +
                "&paymentRefNo=" +
                paymentRefNo +
                "&paymodeId=" +
                othermodesValue +
                "";
            var async_status = true;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                type: "post",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data, textStatus, xhr) {
                    $.trim($("#paymentRefNo").val(""));
                    $("#file").val("");
                    if (xhr.status == 200) {
                        $(".paymentInitiator").modal("hide");
                        $(".paymentInitiatorAttachment").modal("hide");
                        $(".paymentInitiatorAttachmentPayForm").modal("hide");
                        $(".selectMode").modal("hide");
                        $("#confirmPay").html("Confirm Upload");
                        $("#confirmPay").prop("disabled", false);
                        controller.showToastMsg("Document Uploaded Successfully", "#1a5589");
                        // setTimeout(function() {
                        //     window.location.reload();
                        // }, 1000);
                        forwardPIP(reponseObj, pipApplicationID, facility_id);
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    }
                },
                fail: function(xhr, textStatus) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                    $("#confirmPay").html("Confirm Upload");
                    $("#confirmPay").prop("disabled", false);
                    $(".paymentInitiator").modal("hide");
                    $(".paymentInitiatorAttachment").modal("hide");
                    $(".paymentInitiatorAttachmentPayForm").modal("hide");
                    $(".selectMode").modal("hide");
                },
                error: function(xhr, textStatus) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                    $("#confirmPay").html("Confirm Upload");
                    $("#confirmPay").prop("disabled", false);
                    $(".paymentInitiator").modal("hide");
                    $(".paymentInitiatorAttachment").modal("hide");
                    $(".paymentInitiatorAttachmentPayForm").modal("hide");
                    $(".selectMode").modal("hide");
                },
            });
        },



        stepperformAllPostRequestPayments: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        controller.showToastMsg("Payment Created Successfully", "#1a5589");
                        $("#addnewProduct_form").form("reset");
                        $("#addnewProduct").modal("hide");
                        handleData(data);
                        setTimeout(function() {
                            // window.location.reload();
                            $('.modal.fade.viewinspectionsCheclistmodal').modal('hide');

                        }, 1000);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Saving Failed", "#ff6666");
                        handleData(data);
                    }
                    handleData(data);
                },
                fail: function(e) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        // var errorMsg = xhr.responseJSON.message;
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");

                        // try {
                        //     var error = errorMsg.substring(1, 9);
                        //     if (errorMsg == "could not") {
                        //         controller.showToastMsg("Error! Check if Commodity Form and Commdity Selected exits in Payment Matrix" + errorMsg, "#ff6666");
                        //     } else {
                        //         controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                        //     }
                        // } catch (e) {
                        // }
                    }
                },
            });
        },












        stepperformAllPostRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        controller.showToastMsg("Saved Successfully", "#1a5589");
                        $("#addnewProduct_form").form("reset");
                        $("#addnewProduct").modal("hide");
                        handleData(data);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Saving Failed", "#ff6666");
                        handleData(data);
                    }
                    handleData(data);
                },
                fail: function(e) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        // var errorMsg = xhr.responseJSON.message;
                        var errorMsg = xhr.responseText;
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.message, "#ff6666");

                        // try {
                        //     var error = errorMsg.substring(1, 9);
                        //     if (errorMsg == "could not") {
                        //         controller.showToastMsg("Error! Check if Commodity Form and Commdity Selected exits in Payment Matrix" + errorMsg, "#ff6666");
                        //     } else {
                        //         controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                        //     }
                        // } catch (e) {
                        // }
                    }
                },
            });
        },

        stepperformAllPostRequest_2: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    handleData(data);
                },
                fail: function(e) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    $("#loader").css({
                        display: "none",
                    });
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                },
            });
        },
        allPostInspectionsRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    handleData(data);
                },
                fail: function(e, textStatus, xhr) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    handleData(e);
                    $("#blinder").hide();
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                        setTimeout(function() {
                            window.location.reload();
                        }, 1000);
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                        setTimeout(function() {
                            window.location.reload();
                        }, 1000);
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    }
                },
            });
        },


        allPostinspectionLinesRequestDispose: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    // $(".requirementModal").modal("hide");
                    handleData(data);
                    // controller.clearCache();
                    // controller.resetForm();
                },
                fail: function(e) {
                    controller.showToastMsg("Saving Lines Failed", "#ff6666");
                    controller.clearCache();
                    controller.resetForm();
                },
                error: function(xhr, textStatus, errorThrown) {
                    controller.clearCache();
                    controller.resetForm();
                    controller.showToastMsg("Saving Lines Failed", "#ff6666");
                },
            });
        },




        allPostinspectionLinesRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    $(".requirementModal").modal("hide");
                    handleData(data);
                    controller.clearCache();
                    controller.resetForm();
                },
                fail: function(e) {
                    controller.showToastMsg("Saving Lines Failed", "#ff6666");
                    controller.clearCache();
                    controller.resetForm();
                },
                error: function(xhr, textStatus, errorThrown) {
                    controller.clearCache();
                    controller.resetForm();
                    controller.showToastMsg("Saving Lines Failed", "#ff6666");
                },
            });
        },
        clearCache: function() {
            if (window.history.replaceState) {
                window.history.replaceState(null, null, window.location.href);
            }

            // Clear the cache in the background
            if ("caches" in window) {
                caches
                    .open("my-cache")
                    .then((cache) => {
                        return cache.keys().then((keys) => {
                            keys.forEach((key) => {
                                cache.delete(key);
                            });
                        });
                    })
                    .then(() => {})
                    .catch((error) => {});
            }
        },
        activatedeactivateUserPostrequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg("Successfully Activated", "#1a5589");
                    controller.refreshCrudTables();
                    handleData(data);
                    controller.hide_progress();
                },
                fail: function(e) {
                    if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.refreshCrudTables();
                    controller.hide_progress();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if (XMLHttpRequest.status == 400) {
                        var t = XMLHttpRequest.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    }
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                    controller.refreshCrudTables();
                    controller.hide_progress();
                },
            });
        },
        deactivateUserPostrequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    controller.showToastMsg("Successfully Deactivated", "#1a5589");
                    controller.refreshCrudTables();
                    handleData(data);
                    controller.hide_progress();
                },
                fail: function(e) {
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg("Failed Activating", "#ff6666");
                    controller.refreshCrudTables();
                    controller.hide_progress();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                    controller.showToastMsg("Failed Activating", "#ff6666");
                    controller.refreshCrudTables();
                    controller.hide_progress();
                },
            });
        },
        allPostreadnotificationsRequest: function(
            url,
            formData,
            async_status,
            handleData
        ) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    $("#consigneeform")[0].reset();
                    controller.showToastMsg("Message Read", "#1a5589");
                    controller.refreshCrudTables();
                    handleData(data);
                },
                fail: function(e) {
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    controller.refreshCrudTables();
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    controller.showToastMsg("Error Saving data", "#ff6666");
                    controller.refreshCrudTables();
                    $("#blinder").hide();
                },
            });
        },
        getProductPostRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    $("#consigneeform")[0].reset();
                    handleData(data);
                },
                fail: function(e) {
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        allsubmitPipAppplication: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    setTimeout(function() {
                        window.location.reload();
                        localStorage.removeItem("pipApplicationRequestID");
                    }, 1500);
                    if (data) {
                        controller.showToastMsg(data.body.data, "#1a5589");
                        controller.refreshCrudTables();
                    } else {
                        controller.showToastMsg("Failed, Kindly Try Again", "#ff6666");
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Failed, Kindly Try Again", "#ff6666");
                        controller.refreshCrudTables();
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg("Failed, Kindly Try Again", "#ff6666");
                    controller.refreshCrudTables();
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    controller.showToastMsg(
                        "Kindly check if you have added variey details",
                        "#ff6666"
                    );
                    handleData(xhr);
                    $("#blinder").hide();
                    controller.refreshCrudTables();
                },
            });
        },
        allCopyPostRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data) {
                    if (data) {
                        controller.showToastMsg("Record Successfully Copied", "#1a5589");
                        controller.refreshCrudTables();
                    } else {
                        controller.showToastMsg("Copy Failed, Kindly Try Again", "#ff6666");
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Copy Failed, Kindly Try Again", "#ff6666");
                        controller.refreshCrudTables();
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg("Copy Failed, Kindly Try Again", "#ff6666");
                    controller.refreshCrudTables();
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Copy Failed, Kindly Try Again", "#ff6666");
                        controller.refreshCrudTables();
                        handleData(e);
                    }
                    controller.showToastMsg("Copy Failed, Kindly Try Again", "#ff6666");
                    handleData(xhr);
                    $("#blinder").hide();
                    controller.refreshCrudTables();
                },
            });
        },
        allPostDeactivateRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {
                        controller.showToastMsg("Deactivated Successfully", "#1a5589");
                        controller.refreshCrudTables();
                        handleData(data);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Deactivation Failed", "#ff6666");
                        controller.refreshCrudTables();
                        handleData(data);
                    } else {
                        controller.showToastMsg("Deactivation Failed", "#ff6666");
                        handleData(data);
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Deactivation Failed", "#ff6666");
                    }
                    $("#blinder").hide();
                    controller.showToastMsg("Deactivation Failed", "#ff6666");
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Deactivation Failed", "#ff6666");
                    }
                    controller.showToastMsg("Deactivation Failed", "#ff6666");
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        allPostDeleteRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {
                        controller.showToastMsg("Deleted Successfully", "#1a5589");
                        setTimeout(function() {
                            controller.refreshCrudTables();
                        }, 1000);
                        handleData(data);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(data);
                    } else {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(data);
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg("Deletion Failed", "#ff6666");
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    controller.hide_progress();
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
            });
        },
        allPostDeleteMenuRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    window.location.reload();
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {
                        controller.showToastMsg("Deleted Successfully", "#1a5589");
                        handleData(data);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(data);
                    } else {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(data);
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg("Deletion Failed", "#ff6666");
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg("Deletion Failed", "#ff6666");
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    controller.hide_progress();
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        controller.showToastMsg(obj.data, "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
            });
        },
        checksr14postRequest: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        // $('#consignmentWeight').val(data.weight);
                        controller.showToastMsg(
                            "SeedApplication Validated Successfully",
                            "#1a5589"
                        );
                        handleData(data);
                    } else if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(data);
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg(
                        "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                        "#ff6666"
                    );
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(e);
                    }
                    controller.showToastMsg(
                        "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                        "#ff6666"
                    );
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        checksr14postRequestPIP: function(url, formData, async_status, handleData) {
            var formData = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: "application/json",
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: formData,
                success: function(data, textStatus, xhr) {
                    if (xhr.status == 200) {
                        if (data.resultCode == "01") {
                            controller.showToastMsg(data.message, "#ff6666");
                        } else {
                            handleData(data);
                            controller.showToastMsg(data.message, "#1a5589");
                        }
                    } else if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(data);
                    }
                },
                fail: function(e, textStatus, xhr) {
                    if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(e);
                    }
                    handleData(e);
                    $("#blinder").hide();
                    controller.showToastMsg(
                        "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                        "#ff6666"
                    );
                },
                error: function(xhr, ajaxOptions, thrownErro) {
                    if (xhr.status == 400) {
                        controller.showToastMsg(
                            "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                            "#ff6666"
                        );
                        handleData(e);
                    }
                    controller.showToastMsg(
                        "SeedApplication Validation Failed Kindly check if you entered the Correct SR14 Number",
                        "#ff6666"
                    );
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        allPostRequestPayment: function(url, formData, async_status, handleData) {
            var allActivities = JSON.stringify(formData);
            $.ajax({
                url: url,
                processData: false,
                encoding: null,
                contentType: false,
                enctype: "multipart/form-data",
                contentType: false,
                cache: false,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: allActivities,
                responseType: "arraybuffer",
                success: function(data) {
                    var jsonData = data;
                    handleData(data);
                },
                fail: function(e) {
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        postRequest: function(url, formData, async_status, handleData) {
            var allActivities = JSON.stringify(formData);
            $.ajax({
                url: url,
                contentType: true,
                processData: false,
                encoding: null,
                contentType: "application/json",
                beforeSend: function(request) {
                    request.overrideMimeType("text/plain; charset=x-user-defined");
                },
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                data: allActivities,
                responseType: "arraybuffer",
                success: function(data) {
                    var jsonData = data;
                    handleData(data);
                },
                fail: function(e) {
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },
        formatDate: function(myDate) {
            try {
                var months = Array(
                    "Jan",
                    "Feb",
                    "Mar",
                    "Apr",
                    "May",
                    "Jun",
                    "Jul",
                    "Aug",
                    "Sep",
                    "Oct",
                    "Nov",
                    "Dec"
                );
                var dayMonthYear = myDate.split(",");
                var dayMonth = dayMonthYear[0];
                var year = dayMonthYear[1];
                year = year.substring(1, 5);
                var dayMonthArr = dayMonth.split(" ");
                var month = dayMonthArr[0];
                var monthIndex = months.indexOf(month);
                var formatedMonth = monthIndex + 1;
                if (formatedMonth.toString().length == 1) {
                    formatedMonth = "0" + formatedMonth;
                }
                var day = dayMonthArr[1];
                if (day.toString().length == 1) {
                    day = "0" + day;
                }
                return year + "-" + formatedMonth + "-" + day;
            } catch (e) {
                return myDate;
            }
        },
        formatDateTime: function(myDate) {
            var months = Array(
                "Jan",
                "Feb",
                "Mar",
                "Apr",
                "May",
                "Jun",
                "Jul",
                "Aug",
                "Sep",
                "Oct",
                "Nov",
                "Dec"
            );
            var dayMonthYear = myDate.split(",");
            var dayMonth = dayMonthYear[0];
            var secondPart = dayMonthYear[1];
            var year = secondPart.substring(1, 5);
            var time_ = secondPart.substring(6, 11);
            var dayMonthArr = dayMonth.split(" ");
            var month = dayMonthArr[0];
            var monthIndex = months.indexOf(month);
            var formatedMonth = monthIndex + 1;
            if (formatedMonth.toString().length == 1) {
                formatedMonth = "0" + formatedMonth;
            }
            var day = dayMonthArr[1];
            if (day.toString().length == 1) {
                day = "0" + day;
            }
            return year + "-" + formatedMonth + "-" + day + " " + time_;
        },
        postRequestWithUserObj: function(
            url,
            formData,
            async_status,
            userObj,
            handleData
        ) {
            $.ajax({
                url: url,
                contentType: true,
                encoding: null,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: async_status,
                type: "post",
                contentType: "application/json",
                success: function(data) {
                    handleData(data);
                },
                fail: function(e) {
                    handleData(e);
                    $("#blinder").hide();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    handleData(XMLHttpRequest);
                    $("#blinder").hide();
                },
            });
        },


        loginrequest: function(url, formData, async_status, callBack) {
            controller.show_progress();
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                async: async_status,
                data: formData,
                success: function(data, textStatus, xhr) {
                    controller.hide_progress();
                    callBack(data, true);
                },
                fail: function(xhr, textStatus) {
                    console.log("datadatadata fail", xhr.status)

                    controller.hide_progress();
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        var errorArr = obj.errors;
                        var errorMsg = "";
                        for (var i in errorArr) {
                            errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
                        }
                        callBack(errorMsg, false);
                        controller.showToastMsg(
                            "Error! Fields are empty" + errorMsg,
                            "#ff6666"
                        );
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus) {
                    console.log("datadatadata error", xhr.status)
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(xhr.status, false);
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        var errorArr = obj.errors;
                        var errorMsg = "";
                        for (var i in errorArr) {
                            errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
                        }
                        callBack(xhr.status, false);

                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);


                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);

                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);

                    } else if (xhr.status == 500) {

                    }


                },
            });
        },

        request: function(url, formData, async_status, callBack) {
            controller.show_progress();
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                async: async_status,
                data: formData,
                success: function(data, textStatus, xhr) {
                    controller.hide_progress();
                    callBack(data, true);
                },
                fail: function(xhr, textStatus) {
                    controller.hide_progress();
                    handleData(xhr.responseText);
                    if (xhr.status == 200) {} else if (xhr.status == 201) {
                        callBack(errorMsg, false);
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        var errorArr = obj.errors;
                        var errorMsg = "";
                        for (var i in errorArr) {
                            errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
                        }
                        callBack(errorMsg, false);
                        controller.showToastMsg(
                            "Error! Fields are empty" + errorMsg,
                            "#ff6666"
                        );
                    } else if (xhr.status == 401) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        callBack(xhr.status, false);
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        try {
                            var error = errorMsg.substring(1, 9);
                            callBack(errorMsg, false);
                            if (errorMsg == "could not") {
                                controller.showToastMsg(
                                    "Error! Duplicate record exists" + errorMsg,
                                    "#ff6666"
                                );
                            } else {
                                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                            }
                        } catch (e) {}
                    }
                },
                error: function(xhr, textStatus) {
                    controller.hide_progress();
                    if (xhr.responseText == "Account not activated") {
                        callBack(xhr.responseText, true);
                    } else if (
                        xhr.responseText == "Success. Request accepted for processing"
                    ) {
                        callBack(xhr, true);
                    }
                    callBack(xhr, false);
                    $(".login").removeClass("loading");
                    $(".save").removeClass("loading");
                },
            });
        },


        mpesaRequest: function(url, formData, async_status, callBack) {
            parsedUserObj = JSON.parse(localStorage.getItem("userObj"));
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                headers: {
                    Authorization: parsedUserObj.tokenType + " " + parsedUserObj.accessToken,
                },
                contentType: "application/json",
                async: async_status,
                data: formData,
                success: function(data, textStatus, xhr) {
                    // controller.showToastMsg(data.responseCode, "#1a5589");
                    controller.hide_progress();
                    callBack(data, true);
                    try {
                        $(".paymentInitiator").modal("hide");
                    } catch (error) {}

                    if (data.responseCode == 0) {
                        controller.showToastMsg(data.responseDescription, "#1a5589");
                    } else {
                        controller.showToastMsg(data.responseCode, "#ff6666");
                    }
                },

                fail: function(data, xhr, textStatus) {
                    controller.hide_progress();
                    var errorMSG = "Error";
                    try {
                        errorMSG = JSON.parse(data.responseText).data;
                        controller.showToastMsg(errorMSG, "#ff6666");
                        $(".paymentInitiator").modal("hide");
                    } catch (e) {
                        errorMSG = JSON.parse(data.responseText).data;
                        controller.showToastMsg(errorMSG, "#ff6666");
                    }
                },

                error: function(data, xhr, textStatus) {
                    controller.hide_progress();
                    var errorMSG = "Error";
                    try {
                        errorMSG = JSON.parse(data.responseText).data;
                        controller.showToastMsg(errorMSG, "#ff6666");
                        $(".paymentInitiator").modal("hide");
                    } catch (e) {
                        errorMSG = JSON.parse(data.responseText).data;
                        controller.showToastMsg(errorMSG, "#ff6666");
                    }
                    callBack(xhr, false);
                },
            });
        },
        showToastMsg: function(message, color) {
            Toastify({
                text: message,
                duration: 8000,
                gravity: "bottom",
                position: "right",
                backgroundColor: color,
            }).showToast();
        },
        save: function(e) {
            var url = "";
            var action = $(e).attr("data_task");
            var form = $(e).attr("form-name");
            var form_identifier = form;
            var valid = false;
            var valid_count = 0;
            try {
                $(
                    'form[form_identifier="' + form_identifier + '"] input:not(:button)'
                ).each(function(index, value) {
                    try {
                        valid = $(this).parsley().validate();
                    } catch (e) {}
                    var title = $(value).attr("title");
                    var isVisible = $(value).is(":visible");
                    if (valid != true && isVisible == true) {
                        errorArray.push(title);
                        valid_count++;
                    }
                });
            } catch (e) {}
            if (valid_count > 0) {
                var errorHTML = "";
                for (var propt in errorArray) {
                    errorHTML = errorHTML + "<br>" + errorArray[propt];
                }
                controller.showToastMsg("The following fields are Required", "#ff6666");
                setTimeout(() => {
                    $(".saveRecord").html("Save");
                    $(".saveRecord").prop("disabled", false);
                    $(".saveRecord").attr("disabled", false);
                }, 1000);
                try {
                    errorArray = [];
                    return;
                } catch (error) {}
            }
            var primaryName = form_identifier;
            var valid = false;
            var valid_count = 0;
            try {
                $("#" + form_identifier + "_form :input:not(:button)").each(function(
                    index,
                    value
                ) {
                    valid = $(this).parsley().validate();
                    if (valid != true) {
                        setTimeout(() => {
                            $(".saveRecord").html("Save");
                            $(".saveRecord").prop("disabled", false);
                            $(".saveRecord").attr("disabled", false);
                        }, 500);
                        valid_count++;
                    }
                });
            } catch (e) {}
            if (valid_count > 0) {
                return;
            }
            var primaryName = form_identifier;
            var currentFormObj = allFormObj[form_identifier];
            var idType = currentFormObj.idType;
            if (idType == 2) {
                var identifier = form_identifier + "ID";
            } else if (idType == 3) {
                var identifier = "";
                try {
                    identifier = currentObj.primaryFieldName;
                } catch (e) {}
            } else {
                var identifier = form_identifier + "_id";
            }
            if (form == "consolidatedPhyto") {
                identifier = "exporterConsignmentID";
            }
            if (form == "region") {
                identifier = "region_id";
            }
            if (form == "tradingBlock") {
                identifier = "trading_block_id";
            }
            if (
                form == "quarantineFacilityInspection" ||
                form == "exporterFarmInspection" ||
                form == "exporterFirmInspection" ||
                form == "exporterLowRiskInspection"
            ) {
                identifier = "exporterInspectionRequestID";
            }
            if (form == "exportLowRiskCommodity") {
                identifier = "exporterLowRiskCommodityID";
            }
            var formID = "#" + primaryName + "_form";
            var urlID = currentFormObj.url_id;
            var formJson = $("." + form_identifier).serializeObject();
            for (var key of Object.keys(formJson)) {
                var n = key.includes(".");
                if (n) {
                    delete formJson[key];
                }
            }
            var formJsonOld = $(formID).serializeObject();
            if (form_identifier == "exporterProduct") {
                try {
                    var exportID = allFormObj["parent_selected"]["exporterID"];
                    if (exportID == null || exportID == undefined) {
                        try {
                            formJson["exportID"] =
                                allFormObj["parent_selected"]["exporter"]["exporterID"];
                        } catch (error) {
                            formJson["exportID"] = setupObj["exporter"]["exporterID"];
                        }
                    } else {
                        try {
                            formJson["exportID"] = allFormObj["parent_selected"]["exporterID"];
                        } catch (error) {
                            formJson["exportID"] = setupObj["exporter"]["exporterID"];
                        }
                    }
                } catch (error) {}
            }
            if (
                form_identifier == "exporterFarm" ||
                form_identifier == "exporterConsignment"
            ) {
                if (allFormObj["parent_selected"]) {
                    formJson["exporterID"] = allFormObj["parent_selected"]["exporterID"];
                } else {
                    formJson["exporterID"] = setupObj["exporter"]["exporterID"];
                }
            }
            if (form_identifier == "exporterFirm") {
                if (allFormObj["parent_selected"]) {
                    formJson["exporterID"] = allFormObj["parent_selected"]["exporterID"];
                } else {
                    formJson["exporterID"] = setupObj["exporter"]["exporterID"];
                }
            }
            if (form_identifier == "exporterLowRiskCommodity") {
                if (allFormObj["parent_selected"]) {
                    formJson["exporterID"] = allFormObj["parent_selected"]["exporterID"];
                } else {
                    formJson["exporterID"] = setupObj["exporter"]["exporterID"];
                }
            }
            if (form_identifier == "formType") {
                var url = formJson["url"];
                if (url == null || url == "") {
                    formJson["url"] = formJson["name"];
                } else {}
            }
            if (form_identifier == "exporterConsignmentVarietyDetails") {
                if (
                    formJson.mixedCommodityTypes == "false" &&
                    formJson.numberOfPackages < 1
                ) {
                    controller.showToastMsg(
                        "Number Of Packages Should be 1 0r Greater",
                        "#ff6666"
                    );
                } else {
                    var exporconsignmentID =
                        allFormObj["parent_selected"]["exporterConsignmentID"];
                    if (exporconsignmentID == null || exporconsignmentID == undefined) {
                        try {
                            formJson["exporterConsignmentID"] =
                                allFormObj["parent_selected"]["exporterConsignment"][
                                    "exporterConsignmentID"
                                ];
                        } catch (error) {
                            formJson["exporterConsignmentID"] =
                                allFormObj["parent_selected"]["exporterConsignmentID"];
                        }
                    } else {
                        try {
                            formJson["exporterConsignmentID"] =
                                allFormObj["parent_selected"]["exporterConsignmentID"];
                        } catch (error) {
                            formJson["exporterConsignmentID"] =
                                allFormObj["parent_selected"]["exporterConsignment"][
                                    "exporterConsignmentID"
                                ];
                        }
                    }
                }
            }
            if (form_identifier == "exporterFarmproducts") {
                var exporterFarmId = allFormObj["selected"]["exporterFarmID"];
                if (exporterFarmId == null || exporconsignmentID == undefined) {
                    try {
                        formJson["exporterFarmId"] =
                            allFormObj["parent_selected"]["exporterFarm"]["exporterFarmID"];
                    } catch (error) {
                        try {
                            formJson["exporterFarmId"] =
                                allFormObj["parent_selected"]["exporterFarmID"];
                        } catch (error) {}
                    }
                } else {
                    try {
                        formJson["exporterFarmId"] =
                            allFormObj["parent_selected"]["exporterFarmID"];
                    } catch (error) {
                        formJson["exporterFarmId"] =
                            allFormObj["parent_selected"]["exporterFarm"]["exporterFarmID"];
                    }
                }
            }
            if (form_identifier == "facilitycommodities") {
                var quarantineFacilityID =
                    allFormObj["parent_selected"]["quarantineFacilityID"];
                if (quarantineFacilityID == null || quarantineFacilityID == undefined) {
                    try {
                        formJson["quarantineFacilityId"] =
                            allFormObj["parent_selected"]["quarantineFacility"][
                                "quarantineFacilityID"
                            ];
                    } catch (error) {
                        formJson["quarantineFacilityId"] =
                            setupObj["quarantineFacility"]["quarantineFacilityID"];
                    }
                } else {
                    try {
                        formJson["quarantineFacilityId"] =
                            allFormObj["parent_selected"]["quarantineFacilityID"];
                    } catch (error) {
                        formJson["quarantineFacilityId"] =
                            setupObj["quarantineFacility"]["quarantineFacilityID"];
                    }
                }
            }
            if (form_identifier == "tradingcountry") {
                var tradingcountry = localStorage.getItem("tradingcountry");
                formJson["trading_block_id"] = tradingcountry;
                $("#trading_block_id").val(tradingcountry);
            }
            if (form_identifier == "country") {
                if (formJson.nationality == null || formJson.nationality == "") {
                    formJson.nationality = "N/A";
                }
            }
            if (form_identifier == "importConsignment") {
                formJson["importConsignmentID"] =
                    allFormObj["parent_selected"]["importConsignmentID"];
            }
            if (form_identifier == "quarantineFacilityInspection") {
                formJson["inspectionTypeID"] = 5;
            }
            if (form_identifier == "exporterFarmInspection") {
                formJson["inspectionTypeID"] = 1;
            }
            if (form_identifier == "exporterFarmInspection") {
                formJson["inspectionTypeID"] = 1;
            }
            if (form_identifier == "exporterFirmInspection") {
                formJson["inspectionTypeID"] = 2;
            }
            if (form_identifier == "exporterLowRiskInspection") {
                formJson["inspectionTypeID"] = 3;
            }
            if (form_identifier == "pipApplicationVariety") {
                formJson["pipApplicationID"] =
                    allFormObj["parent_selected"]["pipApplicationID"];
            }
            if (form_identifier == "importer_product") {
                formJson["importer_id"] = allFormObj["parent_selected"]["importerID"];
            }
            if (form_identifier == "onetime_export_variety_details") {
                formJson["oneTimeExportID"] =
                    allFormObj["parent_selected"]["onetime_export_id"];
            }
            if (form_identifier == "onetime_import_variety_details") {
                formJson["onetimeImportID"] =
                    allFormObj["parent_selected"]["onetime_import_id"];
            }
            if (form_identifier == "consolidatedExportConsignmentLines") {
                formJson["exporterConsignmentID"] =
                    allFormObj["parent_selected"]["exporterConsignmentID"];
            }
            if (
                form_identifier == "exporterConsignmentVarietyDetails" &&
                allFormObj["parent_selected"]["split_export_consignment_id"]
            ) {
                formJson["exporterConsignmentID"] =
                    allFormObj["selected"]["exporterConsignmentID"];
            }
            if (
                form_identifier == "exporterConsignmentVarietyDetails" &&
                setupObj["agent_mgt"]
            ) {
                formJson["exporterID"] =
                    allFormObj["parent_selected"]["exporter"]["exporterID"];
            }
            if (form_identifier == "pipApplicationVariety" && setupObj["agent_mgt"]) {
                formJson["importerID"] =
                    allFormObj["parent_selected"]["importer"]["importerID"];
            }
            if (form_identifier == "pipApplicationVarietyRequest") {
                try {
                    var expportervarietyid =
                        allFormObj["selected"]["pipApplicationRequestID"];
                    if (expportervarietyid == undefined) {
                        formJson["pipApplicationRequestID"] =
                            allFormObj["parent_selected"]["pipApplicationRequest"][
                                "pipApplicationRequestID"
                            ];
                    } else {
                        formJson["pipApplicationRequestID"] =
                            allFormObj["selected"]["pipApplicationRequestID"];
                    }
                } catch (error) {}
            }
            if (form_identifier == "facilitycommoditiesrequest") {
                try {
                    var quarantineRequestProductId =
                        allFormObj["selected"]["quarantineRequestProductId"];
                    if (quarantineRequestProductId == undefined) {
                        formJson["quarantineFacilityProductRequestId"] =
                            allFormObj["parent_selected"][
                                "quarantine_facility_product_request_id"
                            ];
                    } else {
                        formJson["quarantineFacilityProductRequestId"] =
                            allFormObj["selected"]["quarantineFacilityProductRequest"][
                                "quarantine_facility_product_request_id"
                            ];
                    }
                } catch (error) {}
            }
            if (form_identifier == "exporterFarmproducts") {
                try {
                    var exporterFarmID =
                        allFormObj["tab_exporterFarm_Products"]["exporterFarmID"];
                    if (exporterFarmID == undefined) {
                        formJson["exporterFarmId"] =
                            allFormObj["parent_selected"]["exporterFarmID"];
                    } else {
                        formJson["exporterFarmId"] =
                            allFormObj["tab_exporterFarm_Products"]["exporterFarmID"];
                    }
                } catch (error) {}
            }
            if (form_identifier == "users") {
                if (
                    formJson["roleName"] == undefined ||
                    formJson["roleName"] == "undefined"
                ) {
                    formJson["roleName"] = [userObj.roles[0]["roleName"]];
                } else {
                    if (!Array.isArray(formJson["roleName"])) {
                        formJson["roleName"] = [formJson["roleName"]];
                    }
                }
            }
            if (form_identifier == "clients") {
                if (
                    formJson["roleName"] == undefined ||
                    formJson["roleName"] == "undefined"
                ) {
                    formJson["roleName"] = [userObj.roles[0]["roleName"]];
                } else {
                    if (!Array.isArray(formJson["roleName"])) {
                        formJson["roleName"] = [formJson["roleName"]];
                    }
                }
            }
            if (form_identifier == "exporterFarm") {
                if (!Array.isArray(formJson["tradingblocks"])) {
                    if (!formJson["tradingblocks"]) {
                        formJson["tradingblocks"] = [];
                    } else {
                        formJson["tradingblocks"] = [formJson["tradingblocks"]];
                    }
                }
                if (!Array.isArray(formJson["products"])) {
                    if (!formJson["products"]) {
                        formJson["products"] = [];
                    } else {
                        formJson["products"] = [formJson["products"]];
                    }
                }
                if (!Array.isArray(formJson["tradingcountries"])) {
                    if (!formJson["tradingcountries"]) {
                        formJson["tradingcountries"] = [];
                    } else {
                        formJson["tradingcountries"] = [formJson["tradingcountries"]];
                    }
                }
            }
            if (
                form_identifier == "exporterFirmInspection" ||
                form_identifier == "exporterFarmInspection" ||
                form_identifier == "exporterLowRiskInspection" ||
                form_identifier == "ExporterQuarantineFacility" ||
                form_identifier == "quarantineFacilityInspection"
            ) {
                if (!Array.isArray(formJson["products"])) {
                    if (!formJson["products"]) {
                        formJson["products"] = [];
                    } else {
                        formJson["products"] = [formJson["products"]];
                    }
                }
            }
            if (form_identifier == "exporterFirm") {
                if (!Array.isArray(formJson["farms"])) {
                    if (!formJson["farms"]) {
                        formJson["farms"] = [];
                    } else {
                        formJson["farms"] = [formJson["farms"]];
                    }
                }
            }
            if (form_identifier == "ban_list") {
                if (!Array.isArray(formJson["country_idList"])) {
                    if (!formJson["country_idList"]) {
                        formJson["country_idList"] = [];
                    } else {
                        formJson["country_idList"] = [formJson["country_id"]];
                    }
                }
            }
            if (
                form_identifier == "import_requirement" ||
                form_identifier == "export_requirement"
            ) {
                if (!Array.isArray(formJson["countryList"])) {
                    if (!formJson["countryList"]) {
                        formJson["countryList"] = [];
                    } else {
                        formJson["countryList"] = [formJson["countryList"]];
                    }
                }
            }
            if (form_identifier == "exporterFarm") {
                if (!Array.isArray(formJson["previousCropsID"])) {
                    if (!formJson["previousCropsID"]) {
                        formJson["previousCropsID"] = [];
                    } else {
                        formJson["previousCropsID"] = [formJson["previousCropsID"]];
                    }
                }
            }
            if (form_identifier == "menu") {
                if (!Array.isArray(formJson["formTypes"])) {
                    if (!formJson["formTypes"]) {
                        formJson["formTypes"] = [];
                    } else {
                        formJson["formTypes"] = [formJson["formTypes"]];
                    }
                }
            }
            if (form_identifier == "menuRoles") {
                if (!Array.isArray(formJson["menus"])) {
                    if (!formJson["menus"]) {
                        formJson["menus"] = [];
                    } else {
                        formJson["menus"] = [formJson["menus"]];
                    }
                }
            }
            if (form_identifier == "onetime_export") {
                var date = formJson["departureDate"];
                var dt = new Date();
                var d = dt.toLocaleDateString();
                var t = dt.toLocaleTimeString();
                t = t.replace(/\u200E/g, "");
                t = t.replace(/^([^\d]*\d{1,2}:\d{1,2}):\d{1,2}([^\d]*)$/, "$1$2");
                var time = t;
                if (date.length < 12) {
                    formJson["departureDate"] = formJson["departureDate"] + " " + time;
                } else {
                    formJson["departureDate"] = formJson["departureDate"];
                }
            }
            if (form_identifier == "exporterConsignmentVarietyDetails") {
                if (!Array.isArray(formJson["farms"])) {
                    if (!formJson["farms"]) {
                        formJson["farms"] = [];
                    } else {
                        formJson["farms"] = [formJson["farms"]];
                    }
                }
                if (!Array.isArray(formJson["firms"])) {
                    if (!formJson["firms"]) {
                        formJson["firms"] = [];
                    } else {
                        formJson["firms"] = [formJson["firms"]];
                    }
                }
            }
            if (form_identifier == "ban_list") {
                if (!Array.isArray(formJson["country_idList"])) {
                    if (!formJson["country_idList"]) {
                        formJson["country_idList"] = [];
                    } else {
                        formJson["country_idList"] = [formJson["country_id"]];
                    }
                }
            }
            if (form_identifier == "exporterFarmInspection") {
                if (!Array.isArray(formJson["products"])) {
                    if (!formJson["products"]) {
                        formJson["products"] = [];
                    } else {
                        formJson["products"] = [formJson["products"]];
                    }
                }
            }
            if (form_identifier == "quarantineFacilityInspection") {
                if (!Array.isArray(formJson["products"])) {
                    if (!formJson["products"]) {
                        formJson["products"] = [];
                    } else {
                        formJson["products"] = [formJson["products"]];
                    }
                }
            }
            if (form_identifier == "exporterLowRiskInspection") {
                if (!Array.isArray(formJson["products"])) {
                    if (!formJson["products"]) {
                        formJson["products"] = [];
                    } else {
                        formJson["products"] = [formJson["products"]];
                    }
                }
            }

            primaryVal = formJson[identifier];

            if (identifier == "productHscodeId_id") {
                primaryVal = formJson["productHscodeId"];
            }

            if (identifier == "clients_id") {
                primaryVal = formJson["users_id"];
            }
            if (identifier == "pip_applicationrequest_id") {
                primaryVal = formJson["pip_applicationRequest_id"];
            }
            if (identifier == "onetime_export_id") {
                primaryVal = formJson["onetime_export_id"];
            }
            if (identifier == "facilitycommodities_id") {
                primaryVal = formJson["quarantineFacilityProductId"];
            }
            if (identifier == "storageLocation_id") {
                primaryVal = formJson["storage_location_id"];
            }
            if (identifier == "commodityfamily_id") {
                primaryVal = formJson["product_family_id"];
            }
            if (identifier == "required_Document_id") {
                primaryVal = formJson["requiredDocument_id"];
            }
            if (identifier == "paymentmode_id") {
                primaryVal = formJson["paymentMode_id"];
            }
            if (identifier == "trading_block_id") {
                primaryVal = formJson["tradingBlock_id"];
            }
            if (identifier == "agentsPhytoID") {
                primaryVal = formJson["exporterConsignmentID"];
            }
            if (identifier == "inspectionRequirements_id") {
                primaryVal = formJson["inspectionRequirementID"];
            }
            if (identifier == "farmestablishmentsinspectionRequirementID") {
                primaryVal = formJson["inspectionRequirementID"];
            }
            if (identifier == "nonConformityinspectionRequirementID") {
                primaryVal = formJson["inspectionRequirementID"];
            }
            if (identifier == "farmMonthlyinspectionRequirementID") {
                primaryVal = formJson["inspectionRequirementID"];
            }
            if (identifier == "inspectionLocation_id") {
                primaryVal = formJson["inspection_location_id"];
            }
            if (identifier == "quarantineRequesteProductID") {
                primaryVal = formJson["quarantine_facility_product_request_id"];
            }
            if (identifier == "facilitycommoditiesrequest_id") {
                primaryVal = formJson["quarantineRequestProductId"];
            }
            if (identifier == "exporterLowRiskCommodityID") {
                primaryVal = formJson["exporterLowRiskCommodityID"];
            }
            if (identifier == "exporterLowRiskCommodityID") {
                primaryVal = formJson["exporterLowRiskCommodityID"];
            }
            if (identifier == "productHscode_id") {
                primaryVal = formJson["productHscodeId"];
            }
            if (identifier == "exporterFarmproductsID") {
                primaryVal = formJson["farm_product_id"];
            }
            if (identifier == "producenature_id") {
                primaryVal = formJson["produce_nature_id"];
            }
            if (identifier == "allReprints_id") {
                primaryVal = formJson["reprintApplicationId"];
            }
            if (identifier == "allImportConsignmentReprints_id") {
                primaryVal = formJson["reprintApplicationId"];
            }
            if (identifier == "userlocationdetails_id") {
                primaryVal = formJson["address_id"];
            }
            if (identifier == "pipApplicationVarietyRequestID") {
                primaryVal = formJson["pipApplicationVarietyID"];
            }
            if (identifier == "productBillingCategoryID") {
                primaryVal = formJson["productBillingCategoryId"];
            }
            if (identifier == "tradingcountry_id") {
                primaryVal = formJson["trading_block_country_id"];
            }
            if (identifier == "exporterFarmInspectionID") {
                primaryVal = formJson["exporterInspectionRequestID"];
            }
            if (primaryVal == "") {
                if (form_identifier == "pip_application") {
                    if (formJson["import_condition_id"] == 52) {
                        controller.showToastMsg("This is a prohibited commodity", "#ff6666");
                    } else {
                        delete formJson[identifier];
                        addURL = "addUrl";
                        url = currentFormObj[addURL];
                    }
                } else {
                    delete formJson[identifier];
                    addURL = "addUrl";
                    url = currentFormObj[addURL];
                }
            } else {
                if (form_identifier == "exporter") {
                    formJson["users_id"] = 0;
                }
                if (form_identifier == "importer_product") {
                    formJson["importer_id"] =
                        allFormObj["parent_selected"]["importer"]["importerID"];
                }
                if (form_identifier == "onetime_export_variety_details") {
                    try {
                        formJson["oneTimeExportID"] =
                            allFormObj["parent_selected"]["onetime_export_id"];
                    } catch (error) {}
                }
                if (form_identifier == "onetime_export_variety_details") {
                    try {
                        formJson["oneTimeExportID"] =
                            allFormObj["parent_selected"]["oneTimeExport"]["onetime_export_id"];
                    } catch (error) {}
                }
                if (
                    form_identifier == "consignmentInspectionRequest" &&
                    setupObj["agent_mgt"]
                ) {
                    formJson["importerID"] =
                        allFormObj["parent_selected"]["importer"]["importerID"];
                }
                editURL = "editUrl";
                url = currentFormObj[editURL];
            }
            formJson["active"] = true;
            if (form_identifier == "exporterConsignment") {
                var ucrnumber = $("#ucrNumber").val();
                var formData = JSON.stringify(formJson);
                controller.requestWithToken(
                    serverURL + "exporter/getExporterByCompanyID",
                    function(data1, status) {
                        if (data1.length > 0) {
                            var exporterID = data1[0].exporterID;
                            formJson["exporterID"] = exporterID;
                            formData = JSON.stringify(formJson);
                            controller.saveFormDetails(
                                formData,
                                url,
                                function(output) {
                                    if (output == "error") {
                                        return true;
                                    }
                                    if (action == "save_return") {
                                        try {
                                            if ($(".new-form-identifier").length) {
                                                controller.editRow(output, this, "exporterConsignment");
                                            }
                                        } catch (e) {}
                                    } else if (action == "save_new") {
                                        controller.clearForm(formID);
                                    } else if (action == "save_edit") {} else {}
                                },
                                "save",
                                currentFormObj.saveMessage
                            );
                        } else {
                            controller.requestWithToken(
                                serverURL + "agent/getAgentByCompany",
                                function(data2, status) {
                                    var agents_id = data2[0].agents_id;
                                    formJson["agents_id"] = agents_id;
                                    formData = JSON.stringify(formJson);
                                    controller.saveFormDetails(
                                        formData,
                                        url,
                                        function(output) {
                                            if (output == "error") {
                                                return true;
                                            }
                                            if (action == "save_return") {
                                                try {
                                                    if ($(".new-form-identifier").length) {
                                                        controller.editRow(
                                                            output,
                                                            this,
                                                            "exporterConsignment"
                                                        );
                                                    }
                                                } catch (e) {}
                                            } else if (action == "save_new") {
                                                controller.clearForm(formID);
                                            } else if (action == "save_edit") {} else {}
                                        },
                                        "save",
                                        currentFormObj.saveMessage
                                    );
                                }
                            );
                        }
                    }
                );
            } else if (form_identifier == "consolidatedPhyto") {
                var formData = JSON.stringify(formJson);
                controller.requestWithToken(
                    serverURL + "exporter/getExporterByCompanyID",
                    function(data1, status) {
                        var exporterID = data1[0].exporterID;
                        formJson["exporterID"] = exporterID;
                        formData = JSON.stringify(formJson);
                        controller.saveFormDetails(
                            formData,
                            url,
                            function(output) {
                                if (output == "error") {
                                    return true;
                                }
                                if (action == "save_return") {
                                    try {
                                        if ($(".new-form-identifier").length) {
                                            controller.editRow(output, this, "consolidatedPhyto");
                                        }
                                    } catch (e) {}
                                } else if (action == "save_new") {
                                    controller.clearForm(formID);
                                } else if (action == "save_edit") {} else {}
                            },
                            "save",
                            currentFormObj.saveMessage
                        );
                    }
                );
            } else {
                var formData = JSON.stringify(formJson);
                controller.saveFormDetails(
                    formData,
                    url,
                    function(output) {
                        if (output == "error") {
                            return true;
                        }
                        if (action == "save_return") {
                            if (form_identifier == "exporter") {
                                try {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "exporter");
                                    }
                                } catch (e) {}
                                showPaymentTable();
                            } else if (form_identifier == "quarantineFacilityInspection") {
                                window.location.reload();
                            } else if (form_identifier == "exporterConsignmentVarietyDetails") {
                                controller.refreshCrudTables("exporterConsignmentVarietyDetails");
                                controller.renderCRUDTable(
                                    currentFormObj,
                                    currentFormObj.postType
                                );
                                var m = "";
                                try {
                                    m = JSON.parse(output);
                                    controller.refreshCrudTables(
                                        "exporterConsignmentVarietyDetails"
                                    );
                                    controller.renderCRUDTable(
                                        currentFormObj,
                                        currentFormObj.postType
                                    );
                                } catch (e) {}
                                try {
                                    if (output.message == "FAILED" || m.message == "FAILED") {} else {}
                                } catch (e) {}
                            } else {
                                if (form_identifier == "pip_applicationrequest") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "pip_applicationrequest");
                                    }
                                }
                                if (form_identifier == "consolidatedPhyto") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "consolidatedPhyto");
                                    }
                                }
                                if (form_identifier == "quarantineRequesteProduct") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "quarantineRequesteProduct");
                                    }
                                }
                                if (form_identifier == "onetime_export") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "onetime_export");
                                    }
                                }
                                if (form_identifier == "region") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "region");
                                    }
                                }
                                if (form_identifier == "tradingBlock") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "tradingBlock");
                                    }
                                }
                                if (form_identifier == "onetime_import") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "onetime_import");
                                    }
                                }
                                if (form_identifier == "quarantineFacility") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "quarantineFacility");
                                    }
                                }
                                if (form_identifier == "exporterFarm") {
                                    if ($(".new-form-identifier").length) {
                                        controller.editRow(output, this, "exporterFarm");
                                    }
                                }
                                $(".main-form-action .return").click();
                            }
                        } else if (action == "save_new") {
                            if (form_identifier == "exporterConsignmentVarietyDetails") {
                                controller.refreshCrudTables("exporterConsignmentVarietyDetails");
                                controller.renderCRUDTable(
                                    currentFormObj,
                                    currentFormObj.postType
                                );
                            }
                            controller.clearForm(formID);
                            controller.refreshCrudTables(form_identifier);
                            controller.renderCRUDTable(currentFormObj, currentFormObj.postType);
                        } else if (action == "save_edit") {
                            if (form_identifier == "exporterConsignmentVarietyDetails") {
                                controller.refreshCrudTables("exporterConsignmentVarietyDetails");
                                controller.renderCRUDTable(
                                    currentFormObj,
                                    currentFormObj.postType
                                );
                            }
                            controller.refreshCrudTables(form_identifier);
                            controller.renderCRUDTable(currentFormObj, currentFormObj.postType);
                        } else {
                            controller.refreshCrudTables(form_identifier);
                            controller.renderCRUDTable(currentFormObj, currentFormObj.postType);
                        }
                    },
                    "save",
                    currentFormObj.saveMessage
                );
            }
        },
        deactivate: function(user, admreason) {
            var url =
                serverURL +
                "users/deleteUser?reason=" +
                admreason +
                "&users_id=" +
                user.users_id +
                "";
            var formData = {
                admreason: "admreason",
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                    controller.showToastMsg(
                        "" + user.firstName + " Deactivated",
                        "#1a5589"
                    );
                }
            );
        },
        addExporterDetails: function(
            name,
            email,
            tel,
            postalCode,
            streetName,
            town,
            country_id,
            contactPerson,
            importerID
        ) {
            var url = serverURL + "importerExporter/importerExporter";
            var formData = {
                name: name,
                email: email,
                tel: tel,
                postalCode: postalCode,
                streetName: streetName,
                town: town,
                country_id: country_id,
                contactPerson: contactPerson,
                importerID: importerID,
            };
            var async_status = true;
            controller.allPostRequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshExportersData();
                }
            );
        },
        addImporterConsigmentReprintRecord: function(recordID, reason) {
            var url = serverURL + "reprintApplication/reprintApplication";
            var formData = {
                consignment_inspection_request_id: recordID,
                reason: reason,
            };
            var postData = [formData];
            var async_status = true;
            controller.exporterPostRequest(
                url,
                postData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        addphytoReprintRecord: function(exporterConsignmentID, reason) {
            var url = serverURL + "reprintApplication/reprintApplication";
            var formData = {
                exporterConsignmentID: exporterConsignmentID,
                reason: reason,
            };
            var postData = [formData];
            var async_status = true;
            controller.exporterPostRequest(
                url,
                postData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        addPipReprintRecord: function(pipApplicationID, reason) {
            var url = serverURL + "reprintApplication/reprintApplication";
            var formData = {
                pip_application_id: pipApplicationID,
                reason: reason,
            };
            var postData = [formData];
            var async_status = true;
            controller.exporterPostRequest(
                url,
                postData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        addConsigneeDetails: function(
            consigneename,
            emailaddress,
            tel,
            postalAddress,
            streetName,
            town,
            country_id,
            physicalAddress,
            exporterID
        ) {
            var url = serverURL + "consignee/consignee";
            var formData = {
                name: consigneename,
                email: emailaddress,
                tel: tel,
                postalAddress: postalAddress,
                streetName: streetName,
                town: town,
                country_id: country_id,
                physicalAddress: physicalAddress,
                exporterID: exporterID,
            };
            var async_status = true;
            controller.allPostRequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    $("#consigneeform")[0].reset();
                    controller.refreshConsigneeData();
                }
            );
        },
        createImporterquarantineFacility: function(pip_application_id, facility_id) {
            var url = serverURL + "importQuarantineFacility/quarantineFacility";
            var formData = {
                pip_application_id: pip_application_id,
                quarantine_facilityid: facility_id,
            };
            var async_status = true;
            controller.postRequest(
                url,
                formData,
                async_status,
                function(data, status) {}
            );
        },
        createsamplingAnalysis: function(data, noOfSamples, samplingreason) {
            var url = serverURL + "sampleAnalysis/addSampleAnalysis";
            var formData = {
                exporterConsignmentId: data.exporterConsignment.exporterConsignmentID,
                exporterConsignmentVarietyDetailsId: data.exporterConsignmentVarietyDetailsID,
                productId: data.products.products_id,
                noOfSamples: noOfSamples,
                reason: samplingreason,
            };
            var async_status = true;
            controller.allPostRequest(
                url,
                formData,
                async_status,
                function(data, status) {}
            );
        },
        createLabData: function(
            data,
            expoexporterconsinmentid,
            office_location_id,
            labreason
        ) {
            var url = serverURL + "labAnalysis/addLabAnalysis";
            var formData = {
                consignmentInspectionRequestID: data.consignmentInspectionRequestID,
                officeLocationId: office_location_id,
                reason: labreason,
            };
            var async_status = true;
            controller.allPostRequest(
                url,
                formData,
                async_status,
                function(data, status) {}
            );
        },
        adduserregion: function(data, office_location_id, region_id) {
            var url = serverURL + "staffProfile/staffProfile";
            var formData = {
                users_id: data.users_id,
                office_location_id: office_location_id,
                region_id: region_id,
            };
            var async_status = true;
            controller.allPostRequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.showToastMsg("Region Set Successfully", "#1a5589");
                }
            );
        },
        activateUser: function(user) {
            var url = serverURL + "users/unlockUser?users_id=" + user.users_id + "";
            var formData = {
                admreason: "admreason",
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                    controller.showToastMsg("" + user.firstName + " Activated", "#1a5589");
                }
            );
        },
        activateregionCounty: function(data) {
            var url = serverURL + "regionCounty/updateRegionCounty";
            var formData = {
                active: true,
                regionCounty_id: data.regionCounty_id,
                subCounty_id: data.subCounty.subcounty_id,
                region_id: data.region.regionID,
                county_id: data.county.county_id,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateoffice: function(data) {
            var url = serverURL + "officeLocation/updateOfficeLocation";
            var formData = {
                active: true,
                description: data.description,
                name: data.name,
                officeLocation_id: data.office_location_id,
                region_id: data.region.regionID,
                validateUCR: data.isValidateUCR,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateconsignee: function(data) {
            var url = serverURL + "consignee/updateConsignee";
            var formData = {
                active: true,
                consigneeID: data.consigneeID,
                country_id: data.country.country_id,
                email: data.email,
                exporterID: data.exporter.exporterID,
                name: data.name,
                physicalAddress: data.physicalAddress,
                postalAddress: data.postalAddress,
                streetName: data.streetName,
                tel: data.tel,
                town: data.town,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateregion: function(data) {
            var url = serverURL + "region/updateRegion";
            var formData = {
                active: true,
                code: data.code,
                name: data.name,
                region_id: data.regionID,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateImportCondition: function(data) {
            var url = serverURL + "importcondition/updateImportCondition";
            var formData = {
                active: true,
                code: data.code,
                name: data.name,
                allowedForOnetimeimport: data.allowedForOnetimeimport,
                import_condition_id: data.import_condition_id,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateworkflow: function(data) {
            var url = serverURL + "wfWorkFlow/updateWFWorkFlow";
            var formData = {
                active: true,
                doctypeId: data.docType.docType_id,
                emailEnabled: data.emailEnabled,
                formType_id: data.formType.formType_id,
                name: data.name,
                regionBased: data.isRegionBased,
                role_id: data.role.role_id,
                tableRegister_id: data.tableRegister.tableRegister_id,
                wfWorkflow_id: data.wfWorkflow_id,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activatecertificatetype: function(data) {
            var url = serverURL + "certificateType/updateCertificateType";
            var formData = {
                active: true,
                name: data.name,
                description: data.description,
                certificate_type_id: data.certificate_type_id,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateagent: function(data) {
            var url = serverURL + "agentManagement/updateAgent";
            var formData = {
                active: true,
                agent_mgt_id: data.agent_mgt_id,
                agents_id: data.agent.agents_id,
                company_id: data.company.company_id,
                end_date: moment(data.end_date).format("YYYY-MM-DD"),
                start_date: moment(data.start_date).format("YYYY-MM-DD"),
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateresearchInstitute: function(data) {
            var url = serverURL + "researchInstitute/updateResearchInstitute";
            var formData = {
                active: true,
                name: data.name,
                description: data.description,
                researchInstituteID: data.researchInstituteID,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activatelicencsingbody: function(data) {
            var url = serverURL + "licensingBody/updateLicensingBody";
            var formData = {
                active: true,
                code: "N/A",
                name: data.name,
                licensingBodyID: data.licensingBodyID,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },

        activatehscode: function(data) {
            var url = serverURL + "hscode/updateHsCode";
            var formData = {
                active: true,
                code: data.code,
                description: data.description,
                hs_code_id: data.hs_code_id,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        activateImportRequirements: function(data) {
            var url = serverURL + "importRequirement/updateImportRequirement";
            var formData = {
                active: true,
                country_id: data.country.country_id,
                description: data.description,
                end_date: data.end_date,
                import_condition_id: data.importCondition.import_condition_id,
                import_purpose_id: data.importPurpose.importPurposeID,
                import_requirement_id: data.import_requirement_id,
                product_form_id: data.productForm.product_form_id,
                product_family_id: data.productFamily.product_family_id,
                products_id: data.products.products_id,
                start_date: data.start_date,
            };
            var async_status = true;
            controller.activatedeactivateUserPostrequest(
                url,
                formData,
                async_status,
                function(data, status) {
                    controller.refreshCrudTables();
                }
            );
        },
        clearForm: function(formID) {
            $(formID).find("input[type=text], textarea").val("");
        },
        getWindowURLObject: function() {
            var windowURL = window.location.href;
            var res = windowURL.split("/");
            return res;
        },
        loadComboObj: function(url, item, reponseObj, method = "GET", obj = "") {
            controller.show_progress();
            $.ajax({
                url: url,
                type: method,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    reponseObj(data, item, obj);
                    controller.hide_progress();
                },
                fail: function() {
                    $("#blinder").hide();
                    controller.hide_progress();
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#blinder").hide();
                    controller.hide_progress();
                },
            });
        },
        getRelationObjects: function(formName, exists) {
            var currentObj = allFormObj[formName];
            var relationObj = currentObj.relationObjects;
            var idType = currentObj.idType;
            getRelationObjects_(relationObj, formName, exists);
            controller.show_progress();
            async function getRelationObjects_(relationObj, formName, exists) {
                for (x in relationObj) {
                    var url = serverURL + relationObjectsMap[relationObj[x]];
                    await controller.loadComboObj(
                        url,
                        relationObj[x],
                        function(response, item, obj) {
                            setupObj[item] = response;
                        }
                    );
                }
                if (exists) {
                    controller.getFormData(formName);
                } else {
                    for (var key in setupObj) {
                        controller.setRelationValue(key, setupObj, true, idType);
                    }
                }
                controller.initializeDateFields(formName);
                afterLoad(this.myFormObj);
            }
        },
        setUpObjInitializeSpecificOne: function(url, item1, returnCall) {
            controller.loadComboObj(url, item1, function(response, item, obj) {
                setupObj[item] = response;
            });
        },
        setUpObjInitializeSpecificOneWithCallBack: function(url, item1, returnCall) {
            controller.loadComboObj(url, item1, function(response, item, obj) {
                setupObj[item] = response;
                returnCall(response);
            });
        },
        getRelationObjectsByParam: function(data, e) {
            var divElem = $(e).closest(".listings");
            var formName = divElem.attr("id");
            var formNameArr = formName.split("_");
            formName = formNameArr[1];
            var currentObj = allFormObj[formName];
            var idType = currentObj.idType;
            if (idType == 2) {
                var identifier = formName + "ID";
            } else if (idType == 3) {
                var identifier = "";
                try {
                    identifier = currentObj.primaryFieldName;
                } catch (e) {}
            } else {
                var identifier = formName + "_id";
            }
            if (formName == "assignConsignmentInspection") {
                var selectParentID = data["consignmentInspectionRequest"].identifier;
            } else if (formName == "clients") {
                var selectParentID = data["users_id"];
            } else if (formName == "exporterFarmInspection") {
                var selectParentID = data["exporterInspectionRequestID"];
            } else if (formName == "inspectionLocation") {
                var selectParentID = data["inspection_location_id"];
            } else if (formName == "tradingBlock") {
                var selectParentID = data["trading_block_id"];
            } else if (formName == "importConsignment") {
                var selectParentID = data["consignmentInspectionRequestID"];
            } else {
                var selectParentID = data[identifier];
            }
            var relationObj = currentObj.relationObjects;
            var postType = currentObj.postType;
            getRelationObjectsParam_(relationObj, identifier, selectParentID, formName);
            async function getRelationObjectsParam_(
                relationObj,
                identifier,
                selectParentID,
                formName
            ) {
                try {
                    for (x in relationObjectsMapParam) {
                        var relObj = relationObjectsMapParam[x];
                        if (relObj.name == identifier) {
                            var url_last_part = relObj.url;
                            var postType = relObj.postType;
                            var url = serverURL + url_last_part;
                            if (url_last_part == "undefined" || url_last_part == undefined) {} else {
                                url = url.replace("parentID", selectParentID);
                                await controller.loadComboObj(
                                    url,
                                    relObj.entity,
                                    function(response, item, relObj_) {
                                        if (!Array.isArray(response)) {
                                            setupObj[item] = [response];
                                        } else {
                                            setupObj[item] = response;
                                        }
                                        try {
                                            var childObj = relObj_.includeChild;
                                            setupObj[childObj] = response[childObj];
                                        } catch (e) {}
                                    },
                                    postType,
                                    relObj
                                );
                            }
                        }
                    }
                } catch (e) {}
            }
        },
        setRelationValue: function(
            key,
            obj,
            isnew,
            idType,
            option_id = "",
            formName,
            listEntityName = "",
            editing_id = "",
            editable = true,
            s_type = ""
        ) {
            var selectHTML = "";
            var b = "";
            var c = "";
            if (key == "docStatus") {
                if (isnew) {
                    $("#" + key + "_name").val("DRAFT");
                    $("#" + key + "_id").val(24);
                    controller.effectWindowRights(24);
                } else {
                    $("#" + key + "_name").val(obj[key].name);
                    $("#" + key + "_id").val(obj[key].docStatus_id);
                    $("." + key + "_id").val(obj[key].docStatus_id);
                    controller.effectWindowRights(obj[key].docStatus_id);
                }
            } else {
                try {
                    $("#" + key + "_name").val(obj[key].name);
                } catch (e) {}
                var setUpObj_ = setupObj[key];
                try {
                    if (key == "tableRegister") {
                        setUpObj_.sort((a, b) => {
                            let fa = a.tableName.toLowerCase(),
                                fb = b.tableName.toLowerCase();
                            if (fa < fb) {
                                return -1;
                            }
                            if (fa > fb) {
                                return 1;
                            }
                            return 0;
                        });
                    } else {
                        setUpObj_.sort((a, b) => {
                            let fa = a.name.toLowerCase(),
                                fb = b.name.toLowerCase();
                            if (fa < fb) {
                                return -1;
                            }
                            if (fa > fb) {
                                return 1;
                            }
                            return 0;
                        });
                    }
                } catch (error) {}
                var displayName = "";
                if (key == "tableRegister") {
                    displayName = "tableName";
                } else if (key == "exporter") {
                    displayName = "name";
                } else if (key == "users") {
                    displayName = "username";
                } else if (key == "consignmentInspectionRequest") {
                    displayName = "documentNumber";
                } else if (key == "pipApplicationRequest") {
                    displayName = "pipApplicationRequestID";
                } else if (key == "pip_application") {
                    displayName = "documentNumber";
                } else if (key == "pipApplications") {
                    displayName = "documentNumber";
                } else if (
                    key == "consignmentInspectionRequest" &&
                    formName == "lab_analysis_technician"
                ) {
                    displayName = "documentNumber";
                } else {
                    displayName = "name";
                }
                try {
                    var optionDisplayName = this.myFormObj.relationObjectsFields;
                    for (var displayNameKey in optionDisplayName) {
                        var displayNameJson = optionDisplayName[displayNameKey];
                        try {
                            var tmpDisplayName = displayNameJson[key];
                            if (tmpDisplayName != undefined) {
                                displayName = tmpDisplayName;
                            }
                        } catch (e) {}
                    }
                } catch (e) {
                    if (key == "tableRegister") {
                        displayName = "tableName";
                    } else {
                        displayName = "name";
                    }
                }
                var selectedV = false;
                var optionsCount = 0;
                for (var option in setUpObj_) {
                    optionObj = setUpObj_[option];
                    var option_val = "";
                    var option_key = "";
                    var myID = "";
                    try {
                        var hasOwnProp = optionObj.hasOwnProperty(key + "ID");
                    } catch (e) {}
                    if (hasOwnProp) {
                        myID = key + "ID";
                    } else {
                        myID = key + "_id";
                    }
                    if (myID == "exporterFarmID") {}
                    try {
                        if (option_id == "") {
                            option_val = optionObj[myID];
                            option_key = myID;
                        } else {
                            option_val = optionObj[option_id];
                            option_key = option_id;
                        }
                    } catch (e) {}
                    if (key == "roles") {
                        option_key = "role_id";
                        var hasRole = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hasRole = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hasRole) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hasRole) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "previousCrops") {
                        option_key = "products_id";
                        var hasPreviousCrops = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hasPreviousCrops = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hasPreviousCrops) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hasPreviousCrops) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "formTypes") {
                        option_key = "formType_id";
                        var hasformTypes = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hasformTypes = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hasformTypes) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hasformTypes) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "country") {
                        option_key = "country_id";
                        var hascountry = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hascountry = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hascountry) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hascountry) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "tradingBlocks") {
                        option_key = "trading_block_id";
                        var hastradingBlocks = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hastradingBlocks = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hastradingBlocks) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hastradingBlocks) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "roles") {
                        option_key = "roleName";
                        var hastradingBlocks = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hastradingBlocks = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hastradingBlocks) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hastradingBlocks) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else if (key == "marketDestinations") {
                        var hascountry = false;
                        if (Array.isArray(obj[key])) {
                            for (x in obj[key]) {
                                if (optionObj[option_key] == obj[key][x][option_key]) {
                                    hascountry = true;
                                }
                            }
                        }
                        var objDisplay = optionObj[displayName];
                        var optionDisplay = "";
                        if (objDisplay.hasOwnProperty("name")) {
                            optionDisplay = optionObj[displayName].name;
                        } else {
                            optionDisplay = optionObj[displayName];
                        }
                        if (editable == true) {
                            if (hascountry) {
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                selectHTML +=
                                    "<option value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                            }
                        } else {
                            if (hascountry) {
                                selectHTML += optionDisplay + ",";
                            }
                        }
                    } else {
                        if (key == "exporter") {
                            var objDisplay = optionObj["company"];
                            var optionDisplay = "";
                            if (objDisplay.hasOwnProperty("name")) {
                                optionDisplay = objDisplay.name;
                            } else {
                                optionDisplay = objDisplay;
                            }
                        } else if (key == "tableRegister") {
                            var objDisplay = optionObj;
                            var optionDisplay = "";
                            optionDisplay = objDisplay.tableName;
                        } else if (key == "pipApplication") {
                            var objDisplay = optionObj;
                            var optionDisplay = "";
                            optionDisplay = objDisplay.documentNumber;
                        } else if (key == "onetimeImport") {
                            var objDisplay = optionObj;
                            var optionDisplay = "";
                            optionDisplay = objDisplay.documentNumber;
                        } else if (key == "importer") {
                            var objDisplay = optionObj;
                            var optionDisplay = "";
                            optionDisplay = objDisplay.company.name;
                        } else if (key == "wFDepartment") {
                            var objDisplay = optionObj["department"];
                            var optionDisplay = "";
                            if (objDisplay.hasOwnProperty("name")) {
                                optionDisplay = objDisplay.name;
                            } else {
                                optionDisplay = objDisplay;
                            }
                        } else if (key == "agents") {
                            var objDisplay = optionObj["company"];
                            var optionDisplay = "";
                            optionDisplay = objDisplay.name;
                        } else if (key == "exporterConsignment") {
                            optionDisplay = optionObj["documentNumber"];
                        } else if (key == "consolidatedPhyto") {
                            optionDisplay = optionObj["documentNumber"];
                        } else if (
                            key == "exporterFarm" &&
                            formName == "exporterConsignmentVarietyDetails"
                        ) {
                            optionDisplay = optionObj["farmName"];
                        } else if (
                            key == "exporterfarmss" &&
                            formName == "exporterFarmproducts"
                        ) {
                            optionDisplay = optionObj["farmName"];
                        } else if (key == "exporterFarm") {
                            optionDisplay = optionObj["farmName"];
                        } else if (key == "hsCode") {
                            optionDisplay = optionObj["code"] + optionObj["description"];
                        } else if (key == "hsCode") {
                            optionDisplay = optionObj["code"] + optionObj["description"];
                        } else if (key == "menu") {
                            optionDisplay = optionObj["code"] + ": " + optionObj["name"];
                        } else if (key == "agent_mgt") {
                            optionDisplay = optionObj["company"].name;
                            option_val = optionObj["company"].company_id;
                            selectOptIdentity = obj["agent"][option_key];
                        } else if (key == "exporterFirm") {
                            optionDisplay = optionObj["fullName"];
                        } else if (key == "exporterLowRiskCommodity") {
                            optionDisplay = optionObj["farmName"];
                        } else if (key == "productss") {
                            try {
                                optionDisplay = optionObj["products"].name;
                                option_val = optionObj["products"].products_id;
                            } catch (error) {}
                        } else if (key == "agent") {
                            optionDisplay = optionObj.agent_name;
                            option_val = optionObj.agents_id;
                        } else if (key == "officeLocation") {
                            option_key = "office_location_id";
                            optionDisplay = optionObj["name"];
                            option_val = optionObj[option_key];
                        } else {
                            try {
                                var objDisplay = optionObj[displayName];
                                var optionDisplay = "";
                                try {
                                    objDisplay.hasOwnProperty("name");
                                    if (objDisplay.hasOwnProperty("name")) {
                                        optionDisplay = optionObj[displayName].name;
                                    } else {
                                        optionDisplay = optionObj[displayName];
                                    }
                                } catch (e) {}
                            } catch (error) {}
                        }
                        try {} catch (e) {}
                        var selectOptIdentity = "";
                        try {
                            if (key == "licensingbodies") {
                                selectOptIdentity = obj.licensingBody;
                            } else {
                                if (editing_id != "") {
                                    selectOptIdentity = obj[key][editing_id];
                                } else {
                                    selectOptIdentity = obj[key][option_key];
                                }
                            }
                        } catch (e) {}
                        try {
                            if (optionObj[option_key] == selectOptIdentity) {
                                optionsCount++;
                                selectHTML +=
                                    "<option selected value=" +
                                    option_val +
                                    ">" +
                                    optionDisplay +
                                    "</option>";
                                selectedV = true;
                            } else {
                                optionsCount++;
                                if (editable == true) {
                                    selectHTML +=
                                        "<option value=" +
                                        option_val +
                                        ">" +
                                        optionDisplay +
                                        "</option>";
                                } else {}
                            }
                        } catch (error) {}
                    }
                }
                if (selectedV) {
                    if (editable == true) {
                        if (s_type == "") {
                            selectHTML += "<option value=''>-- Select Option --</option>";
                        }
                    }
                } else {
                    if (optionsCount == 1) {
                        if (key == "importerExporter") {
                            var importer_exporterid = $("#importer_exporterid").val();
                            controller.getImporter_exporterCountry(option_val);
                        }
                        if (allFormObj["exporterFarm"]) {
                            if (key == "productss") {
                                controller.getCategoryByProduct(option_val, "");
                            }
                        }
                        if (key == "consignee") {
                            controller.getConsigneeCountry(option_val, "");
                        }
                    } else {
                        if (key == "countryOfOrigin") {
                            if (allFormObj["exporterConsignment"]) {
                                selectHTML += "<option selected value=1>ETHIOPIA</option>";
                            } else {
                                if (s_type == "") {
                                    selectHTML +=
                                        "<option selected value=''>-- Select Option --</option>";
                                }
                            }
                        }
                        if (key == "countryOforigin") {
                            if (allFormObj["exporterFarm"]) {
                                selectHTML += "<option selected value=1>ETHIOPIA</option>";
                            } else {
                                if (s_type == "") {
                                    selectHTML +=
                                        "<option selected value=''>-- Select Option --</option>";
                                }
                            }
                        }
                        if (key == "countryOforigin") {
                            if (allFormObj["exporterFirm"]) {
                                selectHTML += "<option selected value=1>ETHIOPIA</option>";
                            } else {
                                if (s_type == "") {
                                    selectHTML += "<option selected value=1>ETHIOPIA</option>";
                                }
                            }
                        } else if (key == "countryOfTransit") {
                            if (allFormObj["exporterConsignment"]) {
                                selectHTML += "<option selected value='0'>None</option>";
                            } else {
                                if (s_type == "") {
                                    selectHTML +=
                                        "<option selected value=''>-- Select Option --</option>";
                                }
                            }
                        } else if (key == "country") {
                            if (allFormObj["exporterFarm"]) {
                                selectHTML += "<option selected value='1'>ETHIOPIA</option>";
                            } else {
                                if (s_type == "") {
                                    selectHTML += "<option selected value='1'>ETHIOPIA</option>";
                                }
                            }
                        } else {
                            if (s_type == "") {
                                selectHTML +=
                                    "<option selected value=''>-- Select Option --</option>";
                            }
                        }
                    }
                }
                $("." + key + "ID").html(selectHTML);
            }
            return selectHTML;
        },
        openMap: function() {
            const map = new google.maps.Map(document.getElementById("googleMap"), {
                center: { lat: -1.2921, lng: 36.8219 },
                zoom: 13,
                mapTypeId: "roadmap",
            });
            const input = document.getElementById("pac-input");
            const searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            map.addListener("bounds_changed", () => {
                searchBox.setBounds(map.getBounds());
            });
            let markers = [];
            searchBox.addListener("places_changed", () => {
                const places = searchBox.getPlaces();
                if (places.length == 0) {
                    return;
                }
                markers.forEach((marker) => {
                    marker.setMap(null);
                });
                markers = [];
                const bounds = new google.maps.LatLngBounds();
                places.forEach((place) => {
                    if (!place.geometry || !place.geometry.location) {
                        return;
                    }
                    const icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25),
                    };
                    markers.push(
                        new google.maps.Marker({
                            map,
                            icon,
                            title: place.name,
                            position: place.geometry.location,
                        })
                    );
                    if (place.geometry.viewport) {
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
            });
            $(".modal.fade.farm_map").modal("show");
        },
        initializemap: function() {
            var lat = localStorage.getItem("lat");
            var lng = localStorage.getItem("lng");
            var longitude, latitude;
            lat = lat.substring(0, lat.indexOf(".") + 5);
            lng = lng.substring(0, lng.indexOf(".") + 5);
            var latt = parseFloat(lat);
            var lngg = parseFloat(lng);
            const myLatlng = { lat: lat, lng: lng };
            const map = new google.maps.Map(document.getElementById("googleMap"), {
                zoom: 10,
                center: {
                    lat: latt,
                    lng: lngg,
                },
                mapTypeId: "roadmap",
            });
            var marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(latt, lngg),
            });
            let infoWindow = new google.maps.InfoWindow({
                content: "Click the Farm Location to get the Latitude and Longitude!",
                position: myLatlng,
            });
            infoWindow.open(map);
            map.addListener("click", (mapsMouseEvent) => {
                infoWindow.close();
                infoWindow = new google.maps.InfoWindow({
                    position: mapsMouseEvent.latLng,
                });
                infoWindow.setContent(
                    JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
                );
                infoWindow.open(map);
                longitude = $("#latitude").val(mapsMouseEvent.latLng.lat);
                latitude = $("#longtitude").val(mapsMouseEvent.latLng.lng);

                try {
                    longitude = $("#latitude_2").val(mapsMouseEvent.latLng.lat);
                    latitude = $("#longtitude_2").val(mapsMouseEvent.latLng.lng);
                } catch (error) {}
            });
            const input = document.getElementById("pac-input");
            const searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            map.addListener("bounds_changed", () => {
                searchBox.setBounds(map.getBounds());
            });
            let markers = [];
            searchBox.addListener("places_changed", () => {
                const places = searchBox.getPlaces();
                if (places.length == 0) {
                    return;
                }
                markers.forEach((marker) => {
                    marker.setMap(null);
                });
                markers = [];
                const bounds = new google.maps.LatLngBounds();
                places.forEach((place) => {
                    if (!place.geometry || !place.geometry.location) {
                        return;
                    }
                    const icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25),
                    };
                    markers.push(
                        new google.maps.Marker({
                            map,
                            icon,
                            title: place.name,
                            position: place.geometry.location,
                        })
                    );
                    if (place.geometry.viewport) {
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
            });
            $(".modal.fade.farm_map").modal("show");
            $("#setLocation").hide();
        },
        initMap: function() {
            var longitude, latitude;
            const myLatlng = { lat: 9.0300, lng: 38.7400 };

            const map = new google.maps.Map(document.getElementById("googleMap"), {
                zoom: 12,
                center: myLatlng,
                mapTypeId: "roadmap",
            });
            let infoWindow = new google.maps.InfoWindow({
                content: "Click the Farm Location to get the Latitude and Longitude!",
                position: myLatlng,
            });
            infoWindow.open(map);
            map.addListener("click", (mapsMouseEvent) => {
                infoWindow.close();
                infoWindow = new google.maps.InfoWindow({
                    position: mapsMouseEvent.latLng,
                });
                infoWindow.setContent(
                    JSON.stringify(mapsMouseEvent.latLng.toJSON(), null, 2)
                );
                infoWindow.open(map);
                longitude = $("#latitude").val(mapsMouseEvent.latLng.lat);
                latitude = $("#longtitude").val(mapsMouseEvent.latLng.lng);

                try {
                    longitude = $("#latitude_2").val(mapsMouseEvent.latLng.lat);
                    latitude = $("#longtitude_2").val(mapsMouseEvent.latLng.lng);
                } catch (error) {}
            });
            const input = document.getElementById("pac-input");
            const searchBox = new google.maps.places.SearchBox(input);
            map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
            map.addListener("bounds_changed", () => {
                searchBox.setBounds(map.getBounds());
            });
            let markers = [];
            searchBox.addListener("places_changed", () => {
                const places = searchBox.getPlaces();
                if (places.length == 0) {
                    return;
                }
                markers.forEach((marker) => {
                    marker.setMap(null);
                });
                markers = [];
                const bounds = new google.maps.LatLngBounds();
                places.forEach((place) => {
                    if (!place.geometry || !place.geometry.location) {
                        return;
                    }
                    const icon = {
                        url: place.icon,
                        size: new google.maps.Size(71, 71),
                        origin: new google.maps.Point(0, 0),
                        anchor: new google.maps.Point(17, 34),
                        scaledSize: new google.maps.Size(25, 25),
                    };
                    markers.push(
                        new google.maps.Marker({
                            map,
                            icon,
                            title: place.name,
                            position: place.geometry.location,
                        })
                    );
                    if (place.geometry.viewport) {
                        bounds.union(place.geometry.viewport);
                    } else {
                        bounds.extend(place.geometry.location);
                    }
                });
                map.fitBounds(bounds);
            });
            $(".modal.fade.farm_map").modal("show");
            $("#setLocation").click(function() {
                $(".modal.fade.farm_map").modal("hide");
            });
        },
        effectWindowRights: function(docStatus) {
            $(".controls").html("");
            if (docStatus == draftID) {
                if (urlPage == "mission") {
                    $(".controls").append(
                        "<button type='button' class='ui button save mission_only'><i class='save icon'></i>Save</button>"
                    );
                    $(".controls").append(
                        "<button type='button' class='ui button teal mofa_only start_approve'>Submit for User/Mission <i class='arrow right icon'></i></button>"
                    );
                }
                if (urlPage == "mofa") {
                    $(".controls").append(
                        "<button type='button' style='display:none;' class='ui button teal mofa_only forward'>Approve <i class='arrow right icon'></i></button>"
                    );
                }
            } else if (docStatus == completedID) {
                controller.disableForm(true);
                if (urlPage == "mission") {}
                if (urlPage == "mofa") {
                    $(".controls").append(
                        "<button type='button' style='display:none;' class='ui button print_note blue mofa_only'><i class='print icon'></i> Print Note </button>"
                    );
                    $(".controls").append(
                        "<button type='button' style='display:none;' class='ui button print_form blue mofa_only'><i class='print icon'></i> Print Form </button>"
                    );
                }
            } else if (docStatus == inProgressID) {
                controller.disableForm(true);
                if (urlPage == "mission") {}
                if (urlPage == "mofa") {
                    $(".controls").append(
                        "<button type='button' style='display:none;' class='ui button teal mofa_only'>Approve <i class='arrow right icon'></i></button>"
                    );
                }
                disableForm(true);
            } else if (docStatus == rejectedID) {
                disableForm(true);
            } else if (docStatus == ammendID) {
                $(".print").hide();
            }
            $(".print_note").on("click", function() {
                controller.printNote(this);
            });
            $(".print_form").on("click", function() {
                controller.printEntity(this);
            });
            $("#isDualCitizen").on("click", function() {
                if ($("#isDualCitizen").prop("checked") == true) {
                    $(".otherCountry").show();
                } else {
                    $(".otherCountry").hide();
                }
            });
        },
        loadDocumentsUploadDefaultList: function(tableID, url, formType_id) {
            listings.getRequiredDocument(formType_id, function(response) {
                var requiredDocJSON = response;
                var documentTypesUploaded = [];
                var tableHTML = $(tableID);
                html =
                    html +
                    "<tr><td>Document Type</td><td>Document</td><td>Status</td></tr>";
                for (var i = 0; i < requiredDocJSON.length; i++) {
                    var selectVal = requiredDocJSON[i];
                    if (
                        requiredDocJSON[i]["documentUploadType"]["documentUploadType_id"] ==
                        7631
                    ) {
                        html = "<tr><td></td></tr>";
                    } else {
                        html =
                            html +
                            "<tr><td>" +
                            requiredDocJSON[i]["documentUploadType"]["name"] +
                            "</td><td><form id='document-setup_' enctype='multipart/form-data'>";
                        html =
                            html +
                            "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                        html =
                            html +
                            "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                            html +
                            "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                        html =
                            html +
                            "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                        html =
                            html +
                            "<input type='file' class='doc_file_input' name='file' id='file' placeholder='File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button' onclick='controller.saveDocument(" +
                            requiredDocJSON[i]["documentUploadType"]["documentUploadType_id"] +
                            ",this);' value='Save Document'></form></td><td><i style='color:red;' class='exclamation circle icon'></i> Pending Upload</td></tr>";
                    }
                }
                tableHTML.html(html);
            });
            var html = "";
        },
        getPrimaryValue: function(e) {
            var form = $(e).closest(".form");
            var form_identifier = form.attr("form_identifier");
            var currentFormObj = allFormObj["selected"];
            var identifier = form_identifier + "ID";
            if (identifier in currentFormObj) {} else {
                identifier = form_identifier + "_id";
            }
            if (identifier == "importer") {
                var identifier = currentFormObj["importer"].importerID;
            }
            var value = currentFormObj[identifier];
            return value;
        },
        getPrimaryValueByName: function(name) {
            var form_identifier = name;
            var currentFormObj = allFormObj["selected"];
            var identifier = form_identifier + "ID";
            if (identifier in currentFormObj) {} else {
                identifier = form_identifier + "_id";
            }
            var value = currentFormObj[identifier];
            return value;
        },
        getFormObj: function(e) {
            var form = $(e).closest(".form");
            var form_identifier = form.attr("form_identifier");
            var formObj_ = allFormObj[form_identifier];
            return formObj_;
        },
        saveDocument: function(typeId, e, saveObj) {
            var primaryId = controller.getPrimaryValue(e);
            var docStatus_id = 24;
            $(".documentUploadType_id").val(typeId);
            $(".documentDocStatus_id").val(docStatus_id);
            $(".document_parent_id").val(primaryId);
            $("#primaryDoc_id").val("");
            if (primaryId == "") {
                alert("First Save Main Document");
            } else {
                event.stopPropagation();
                $("#myfile").html("");
                $(e).addClass("loading");
                controller.saveDocumentEntity(
                    "document-setup",
                    function(status) {
                        $(e).removeClass("loading");
                    },
                    e,
                    saveObj
                );
            }
        },
        saveDocumentReport: function(typeId, e, saveObj) {
            var primaryId = controller.getPrimaryValue(e);
            var docStatus_id = 24;
            $(".documentUploadType_id").val(typeId);
            $(".document_parent_id").val(primaryId);
            $("#primaryDoc_id").val("");
            if (primaryId == "") {
                alert("First Save Main Document");
            } else {
                event.stopPropagation();
                $("#myfile").html("");
                $(e).addClass("loading");
                controller.saveDocumentReports(
                    "document-setup",
                    function(status) {
                        $(e).removeClass("loading");
                    },
                    e,
                    saveObj
                );
            }
        },

        // Importer required documents
        saveAttachments: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsImporter(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },

        saveAttachmentsEdit: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsImporterEdit(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },

        // Importer required documents
        saveAttachmentsExporter: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsexporter(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },

        saveAttachmentsExporterEdit: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsexporterEdit(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },

        // Agent required documents
        saveAttachmentsByAgent: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsByAgent(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },
        saveAttachmentsAgentEdit: function(typeId, e, saveObj) {
            $(".documentUploadType_id").val(typeId);
            $("#primaryDoc_id").val("");
            controller.saveRequiredDocumentsAgentsEdit(
                "document-setup",
                function(status) {
                    $(e).removeClass("loading");
                },
                e,
                saveObj
            );
        },
        openFile: function(file) {
            var extension = file.substr(file.lastIndexOf(".") + 1);
            switch (extension) {
                case "jpg":
                case "PNG":
                case "JPEG":
                case "jpeg":
                case "png":
                case "JPG":
                case "docx":
                case "DOCX":
                case "gif":
                case "GIF":
                case "tiff":
                    return true;
                    break;
                case "TIFF":
                    return true;
                    break;
                case "pdf":
                    return true;
                    break;
                case "PDF":
                    return true;
                    break;
                default:
                    return false;
            }
        },
        saveDocumentReports: function(formDocumentID, callback, e, saveObj) {
            var formObj = controller.getFormObj(e);
            var documentFormObj_ = allFormObj["documents_reports"];
            var selectParentID = controller.getPrimaryValue(e);
            var url = "";
            var formJson = $("#" + formDocumentID + "_").serializeObject();
            var fileName = "";
            var fileObj = "";
            $('input[name="file"]').each(function() {
                if (!isNaN(this.value)) {} else {
                    fileName = this.value;
                    fileObj = this;
                }
            });
            if (!controller.openFile(fileName)) {
                controller.showToastMsg("Invalid File Type!", "#ff6666");
                callback();
                return false;
            }
            delete formJson.documentDocStatus_id;
            formJson["docStatus_id"] = $(".documentDocStatus_id").val();
            delete formJson.document_parent_id;
            formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
            var file_data = fileObj;
            formJson["file"] = fileName;
            if (typeof saveObj == "undefined") {
                delete formJson["primaryDoc_id"];
                url = documentFormObj_.addUrl;
                url =
                    url +
                    "?docStatus_id=" +
                    $(".documentDocStatus_id").val() +
                    "&" +
                    formObj.formName +
                    "_id=" +
                    $(".document_parent_id").val() +
                    "&documentUploadType_id=" +
                    $(".documentUploadType_id").val();
            } else {
                url = documentFormObj_.editUrl;
            }
            var formdata = new FormData();
            var file_data = fileObj.files;
            formdata.append("file", file_data[0]);
            if (file_data[0].size > 2097152) {
                controller.showToastMsg(
                    "This Document is greater than 2Mbs" +
                    ", Kindly Upload Documents less than 2 Mbs",
                    "#ff6666"
                );
                return;
            } else {
                url =
                    url +
                    "?" +
                    "globalDocument_id=" +
                    saveObj["globalDocument_id"] +
                    "&name=" +
                    saveObj["name"] +
                    "&" +
                    "recordId=" +
                    saveObj["recordId"] +
                    "&tableRegisterId=" +
                    saveObj["tableRegister"]["tableRegister_id"] +
                    "description=name" +
                    "&documentUploadType_id=0";
                $.ajax({
                    url: url,
                    headers: {
                        Authorization: userObj.tokenType + " " + userObj.accessToken,
                    },
                    async: true,
                    type: "POST",
                    data: formdata,
                    processData: false,
                    contentType: false,
                    success: function(data, textStatus, xhr) {
                        if (xhr.status == 200) {}
                    },
                    fail: function(xhr, textStatus) {},
                    error: function(xhr, textStatus) {},
                });
            }
        },

        // Agent
        saveRequiredDocumentsByAgent: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            controller.requestWithToken(
                serverURL + "agent/getAgentByCompany",
                function(data1, status) {
                    var agents_id = data1[0].agents_id;

                    var url =
                        serverURL +
                        "agentDocument/addAgentDocument?documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&agents_id=" +
                        agents_id;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(agents_id);
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveRequiredDocumentsAgentsEdit: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            var agentDocument_id = saveObj.agent_document_id;
            controller.requestWithToken(
                serverURL + "agent/getAgentByCompany",
                function(data1, status) {
                    var agents_id = data1[0].agents_id;

                    var url =
                        serverURL +
                        "agentDocument/updateAgentDocument?docStatus_id=24&documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&agent_id=" +
                        agents_id +
                        "&agentDocument_id=" +
                        agentDocument_id;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(agents_id);

                                        // window.location.reload();
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveRequiredDocumentsImporter: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            controller.requestWithToken(
                serverURL + "importer/getImporterByCompanyID",
                function(data1, status) {
                    var importerID = data1[0].importerID;

                    var url =
                        serverURL +
                        "importerDocument/addImporterDocument?docStatus_id=24&documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&importer_id=" +
                        importerID;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(importerID);
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveRequiredDocumentsexporter: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            controller.requestWithToken(
                serverURL + "exporter/getExporterByCompanyID",
                function(data1, status) {
                    var exporterID = data1[0].exporterID;

                    var url =
                        serverURL +
                        "exporterDocument/addExporterDocument?docStatus_id=24&documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&exporter_id=" +
                        exporterID;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(exporterID);
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveRequiredDocumentsexporterEdit: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            var exporterDocumentID = saveObj.exporterDocument_id;
            controller.requestWithToken(
                serverURL + "exporter/getExporterByCompanyID",
                function(data1, status) {
                    var exporterID = data1[0].exporterID;

                    var url =
                        serverURL +
                        "exporterDocument/updateExporterDocument?docStatus_id=24&documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&exporter_id=" +
                        exporterID +
                        "&exporterDocument_id=" +
                        exporterDocumentID;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(exporterID);
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveRequiredDocumentsImporterEdit: function(
            formDocumentID,
            callback,
            e,
            saveObj
        ) {
            var importerDocumentID = saveObj.importerDocumentID;
            controller.requestWithToken(
                serverURL + "importer/getImporterByCompanyID",
                function(data1, status) {
                    var importerID = data1[0].importerID;

                    var url =
                        serverURL +
                        "importerDocument/updateImporterDocument?docStatus_id=24&documentUploadType_id=" +
                        saveObj.documentUploadType.documentUploadType_id +
                        "&importerID=" +
                        importerID +
                        "&importerDocumentID=" +
                        importerDocumentID;
                    var formJson = $("#" + formDocumentID + "_").serializeObject();
                    var fileName = "";
                    var fileObj = "";
                    $('input[name="file"]').each(function() {
                        if (!isNaN(this.value)) {} else {
                            fileName = this.value;
                            fileObj = this;
                        }
                    });
                    if (!controller.openFile(fileName)) {
                        controller.showToastMsg("Invalid File Type!", "#ff6666");
                        callback();
                        return false;
                    }
                    delete formJson.documentDocStatus_id;
                    formJson["docStatus_id"] = $(".documentDocStatus_id").val();
                    delete formJson.document_parent_id;
                    formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
                    var file_data = fileObj;
                    formJson["file"] = fileName;
                    var formdata = new FormData();
                    var file_data = fileObj.files;
                    formdata.append("file", file_data[0]);
                    if (file_data[0].size > 2097152) {
                        controller.showToastMsg(
                            "This Document is greater than 2Mbs" +
                            ", Kindly Upload Documents less than 2 Mbs",
                            "#ff6666"
                        );
                        return;
                    } else {
                        $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            type: "POST",
                            data: formdata,
                            processData: false,
                            contentType: false,
                            success: function(data, textStatus, xhr) {
                                if (xhr.status == 200) {
                                    controller.showToastMsg(
                                        "Document Uploaded Successfully",
                                        "#1a5589"
                                    );

                                    setTimeout(() => {
                                        requiredAttachments(importerID);
                                    }, 1000);
                                }
                            },
                            fail: function(xhr, textStatus) {},
                            error: function(xhr, textStatus) {},
                        });
                    }
                }
            );
        },

        saveDocumentEntity: function(formDocumentID, callback, e, saveObj) {
            var formObj = controller.getFormObj(e);
            var documentFormObj_ = allFormObj["documents"];
            var selectParentID = controller.getPrimaryValue(e);
            var url = "";
            var formJson = $("#" + formDocumentID + "_").serializeObject();
            var fileName = "";
            var fileObj = "";
            $('input[name="file"]').each(function() {
                if (!isNaN(this.value)) {} else {
                    fileName = this.value;
                    fileObj = this;
                }
            });
            if (!controller.openFile(fileName)) {
                controller.showToastMsg("Invalid File Type!", "#ff6666");
                callback();
                return false;
            }
            delete formJson.documentDocStatus_id;
            formJson["docStatus_id"] = $(".documentDocStatus_id").val();
            delete formJson.document_parent_id;
            formJson[formObj.formName + "_id"] = $(".document_parent_id").val();
            var file_data = fileObj;
            formJson["file"] = fileName;
            if (typeof saveObj == "undefined") {
                delete formJson["primaryDoc_id"];
                url = documentFormObj_.addUrl;
                url =
                    url +
                    "?docStatus_id=" +
                    $(".documentDocStatus_id").val() +
                    "&" +
                    formObj.formName +
                    "_id=" +
                    $(".document_parent_id").val() +
                    "&documentUploadType_id=" +
                    $(".documentUploadType_id").val();
            } else {
                url = documentFormObj_.editUrl;
                if (formObj.formName == "exporter") {
                    url =
                        url +
                        "?" +
                        formObj.formName +
                        "_id=" +
                        formJson[formObj.formName + "_id"] +
                        "&docStatus_id=" +
                        saveObj["docStatus"]["docStatus_id"] +
                        "&" +
                        formObj.formName +
                        "Document_id=" +
                        saveObj[formObj.formName + "Document_id"] +
                        "&documentUploadType_id=" +
                        saveObj["documentUploadType"]["documentUploadType_id"];
                } else if (formObj.formName == "importer") {
                    url =
                        url +
                        "?" +
                        formObj.formName +
                        "ID=" +
                        formJson[formObj.formName + "_id"] +
                        "&docStatus_id=" +
                        saveObj["docStatus"]["docStatus_id"] +
                        "&" +
                        formObj.formName +
                        "DocumentID=" +
                        saveObj[formObj.formName + "DocumentID"] +
                        "&documentUploadType_id=" +
                        saveObj["documentUploadType"]["documentUploadType_id"];
                } else if (formObj.formName == "agents") {
                    url =
                        url +
                        "?" +
                        "agent_id=" +
                        formJson[formObj.formName + "_id"] +
                        "&docStatus_id=" +
                        saveObj["docStatus"]["docStatus_id"] +
                        "&" +
                        "agentDocument_id=" +
                        saveObj["agent_document_id"] +
                        "&documentUploadType_id=" +
                        saveObj["documentUploadType"]["documentUploadType_id"];
                }
            }
            var data = new FormData();
            var form_data = $("#" + formDocumentID).serializeArray();
            var file_data = fileObj.files;
            data.append("file", file_data[0]);
            if (file_data[0].size > 2097152) {
                controller.showToastMsg(
                    "This Document is greater than 2Mbs" +
                    ", Kindly Upload Documents less than 2Mibs",
                    "#ff6666"
                );
                return;
            } else {
                controller.saveFormUploadDetails(
                    data,
                    url,
                    function(output) {
                        callback();
                        $(".modal.fade.document").modal("hide");
                        var select = $(".documentUploadStatus");
                        var table = $(".documentUploadStatus");
                        var formObj_ = allFormObj["documents"];
                        var selectParentID = controller.getPrimaryValueByName(
                            formObj_["parentTable"]
                        );
                        controller.loadDocumentsUploadStatus(
                            "#Attachments",
                            formObj_["listUrl"] + selectParentID,
                            formObj_["formType_id"],
                            function() {}
                        );
                    },
                    "save",
                    "Document has been Saved Successfully"
                );
            }
        },
        saveFormUploadDetails: function(formData, url, handleData) {
            $(".save").addClass("loading");
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                type: "post",
                data: formData,
                processData: false,
                contentType: false,
                success: function(data, textStatus, xhr) {
                    handleData(data);
                    if (xhr.status == 200) {
                        controller.showToastMsg("Document Uploaded Successfully", "#1a5589");
                    } else if (xhr.status == 201) {
                        controller.showToastMsg("Error! Created", "#ff6666");
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Error! Fields are empty", "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized", "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden", "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found", "#ff6666");
                    } else if (xhr.status == 500) {
                        controller.showToastMsg("Error! Duplicate, Record Exists", "#ff6666");
                    }
                    $(".save").removeClass("loading");
                },
                fail: function(xhr, textStatus) {
                    if (xhr.status == 200) {
                        controller.showToastMsg("Updated Successfully", "#1a5589");
                    } else if (xhr.status == 201) {
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        var t = xhr.responseText;
                        var obj = JSON.parse(t);
                        var errorArr = obj.errors;
                        var errorMsg = "";
                        for (var i in errorArr) {
                            errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
                        }
                        controller.showToastMsg(
                            "Error! Fields are empty" + errorMsg,
                            "#ff6666"
                        );
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                    }
                    $(".save").removeClass("loading");
                },
                error: function(xhr, textStatus) {
                    if (xhr.status == 200) {
                        controller.showToastMsg("Updated Successfully", "#1a5589");
                    } else if (xhr.status == 201) {
                        controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
                    } else if (xhr.status == 400) {
                        controller.showToastMsg("Failed Updating Document", "#ff6666");
                    } else if (xhr.status == 401) {
                        controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
                    } else if (xhr.status == 403) {
                        controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
                    } else if (xhr.status == 404) {
                        controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
                    } else if (xhr.status == 500) {
                        var errorMsg = xhr.responseJSON.message;
                        controller.showToastMsg("Error!" + errorMsg, "#ff6666");
                    }
                    $(".save").removeClass("loading");
                },
            });
        },
        getPaymentPhytoInvoice: function(tableID, recordID, formTypeID, reponseObj) {
            var html = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    $("#makephytoApplicationpaymentbtn").hide();
                    $("#submitphytoApplicationbtn").show();
                    var requiredDocJSON = data;
                    if (requiredDocJSON.length > 0) {
                        var tableHTML = $(tableID);
                        var visible = "";
                        html = html + "<h2>Payments</h2>";
                        html =
                            html +
                            "<table class='table table-striped'><tr><td style='color:#5ebd86'>Document Number</td><td style='color:#5ebd86'>Description</td><td style='color:#5ebd86'>Total Amount</td><td style='color:#3543B3'>Payment Status</td><td style='color:#3543B3'>Action</td></tr>";
                        var num = 0;
                        var paid;
                        try {
                            for (var i = 0; i < requiredDocJSON.length; i++) {
                                if (
                                    requiredDocJSON[i].isPaid == true ||
                                    requiredDocJSON[i].isPaid == "true"
                                ) {
                                    var visibility = "style='visibility: hidden;'";
                                    paid = "Paid";
                                } else {
                                    var visibility = "style='visibility: visible;'";
                                    paid = "Not Paid";
                                }
                                if (recordID == requiredDocJSON[i]["record_id"]) {
                                    html =
                                        html +
                                        "<tr><td>" +
                                        requiredDocJSON[i]["documentNumber"] +
                                        "</td><td>" +
                                        requiredDocJSON[i]["description"] +
                                        "</td><td><i style='color:green;' class='fa fa-money' style='margin-right:4px'> </i> BIRR :" +
                                        requiredDocJSON[i]["amount"] +
                                        "</td><td style='color:#3543B3'>" +
                                        paid +
                                        "</td>";
                                    html = html + "</td><td " + visibility + ">";
                                    html =
                                        html +
                                        "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton(" +
                                        recordID +
                                        ");' value='Pay' style='backgound-color: yellow; color: white'>";
                                    html =
                                        html +
                                        "<input type='button' id='payImporterRegistrationd'  class='btn btn-info' onclick='postPayPayments(" +
                                        requiredDocJSON[i]["payment_id"] +
                                        ");' value='On Account' style='backgound-color: yellow; color: white'>";
                                    html =
                                        html +
                                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='refreshCrudPayments();' value='Refresh' style='backgound-color: yellow; color: white'></td>";
                                } else {
                                    num++;
                                    html =
                                        html +
                                        "<tr><td>" +
                                        num +
                                        ". " +
                                        requiredDocJSON[i]["documentNumber"] +
                                        "</td><td>" +
                                        requiredDocJSON[i]["description"] +
                                        "</td><td>BIRR" +
                                        requiredDocJSON[i]["amount"] +
                                        "</td></td><td></td>";
                                    html = html + "</td><td>";
                                    html = html + "<tr></tr>";
                                }
                            }
                        } catch (error) {}
                        html = html + "</table>";
                        tableHTML.html(html);
                        reponseObj(html);
                    } else {
                        var tableHTML = $(tableID);
                        tableHTML.html("");
                        html = html + "</table>";
                        tableHTML.html(html);
                        reponseObj(html);
                    }
                },
                fail: function() {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },

        getAllPaymentsInvoice: function(tableID, recordID, formTypeID, reponseObj) {
            if (isEditOnly == true) {
                $(".crud_section_lines").hide();
            } else {
                var html = "";
                recordsIds = [];
                var data = SelectedData[SelectedData.length - 1];
                if (data.length > 0) {
                    for (let i = 0; i < data.length; i++) {
                        recordsIds.push(data[i]);
                    }
                    var formData = recordsIds;
                    var companyName = "";
                    var paid;
                    var total = 0;
                    var amount = 0;
                    var currentamount = 0;
                    var docNo = "";
                    var description = "";
                    var postpayrecordID = 0;
                    $(".crud_section_lines").show();
                    var visibility = "";
                    try {
                        for (i in recordsIds) {
                            var url =
                                serverURL +
                                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                                formData[i][recordID] +
                                "&formTypeID=" +
                                formTypeID;
                            recordIDPostPay = formData[i][recordID];
                            controller.requestWithToken(url, function(data, status) {
                                let desc = document.getElementById("description");
                                let amount = document.getElementById("totalAmount");
                                let currentamt = document.getElementById(
                                    "currentSelecttotalAmount"
                                );
                                let docNumber = document.getElementById("documentNumberLabel");
                                let ispaid = document.getElementById("ispaidRecord");
                                if (data.length > 0) {
                                    docNo = data[0].documentNumber;
                                    total += data[0].amount;
                                    currentamount = data[0].amount.toLocaleString();
                                    amount.innerHTML = +total;
                                    currentamt.innerHTML = +total;
                                    docNumber.innerHTML = docNo;
                                    var formattedTotal = total.toLocaleString();
                                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                                        visibility = "display:none; visibility: hidden";
                                        paid = "Paid";
                                        $("#buttonssectionholder").hide();
                                    } else {
                                        $("#buttonssectionholder").show();
                                        paid = "Not Paid";
                                        visibility = "display:block;visibility: visible";
                                    }
                                    description +=
                                        "<label style='width: 400px'>" +
                                        data[0].description +
                                        "</label>" +
                                        "<label style='width: 80px'>" +
                                        "BIRR " +
                                        data[0].amount.toLocaleString() +
                                        "</label>" +
                                        "<label style='color:#3543B3'>" +
                                        paid +
                                        "</label>" +
                                        "<br>";
                                    desc.innerHTML = description;
                                } else {
                                    amount.innerHTML = 0;
                                    paid = "No payment has been created";
                                    docNumber.innerHTML = "None";
                                    amount.innerHTML = total;
                                    currentamount = 0;
                                    currentamt.innerHTML = 0;
                                    ispaid.innerHTML = "None";
                                    desc.innerHTML = "No Payment found";
                                }
                            });
                        }
                    } catch (error) {}
                    var tableHTML = $(tableID);
                    tableHTML.html("");
                    html = html + "<div  id='buttonssectionholder'>";
                    html =
                        html +
                        "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton();' value='Pay' style='backgound-color: yellow; color: white'>";
                    html =
                        html +
                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.refreshPayments();' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
                    html =
                        html +
                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
                    html = html + "</div>";
                    html =
                        html +
                        '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
                    html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
                    html =
                        html +
                        '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
                    html =
                        html +
                        '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
                    html = html + "<tbody>";
                    html =
                        html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                    html =
                        html +
                        '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
                    html = html + "<p>Payment Details</p>";
                    html = html + "</td>";
                    html = html + "<td>";
                    html =
                        html +
                        '<p style="font-size: 12px">(Other charges)Convinience fee of BIRR 50 per Application</p>';
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + " </tbody>";
                    html = html + "  </table>";
                    html = html + " </td>";
                    html = html + " </tr>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
                    html =
                        html +
                        '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                        "Total Amount in BIRR " +
                        "<label id='currentSelecttotalAmount'></label>" +
                        '</strong ><span style="color:red; margin-left:4px">' +
                        "" +
                        "<label id='ispaidRecord'></label>" +
                        "</span></td>";
                    html =
                        html +
                        '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                        '<label id="documentNumberLabel" style="color: #000"></label>' +
                        "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + ' <td style="padding: 0;"></td>';
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
                    html =
                        html +
                        '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td valign="top"  style="padding: 20px;">';
                    html = html + "<h3";
                    html =
                        html +
                        'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
                    html = html + "Summary";
                    html = html + "</h3>";
                    html =
                        html +
                        '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html =
                        html + '<td><label id="description">' + description + "</label></td>";
                    html = html + "</tr>";
                    html =
                        html +
                        '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                    html =
                        html +
                        '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</tr>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + '<tr style="color: #666; font-size: 12px;">';
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html =
                        html +
                        '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html = html + " </tr>";
                    html = html + "</tbody>";
                    html = html + " </table>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</table>";
                    tableHTML.html(html);
                    reponseObj(html);
                } else {
                    var html = "";
                    var tableHTML = $(tableID);
                    tableHTML.html("");
                    html = html + "</table>";
                    tableHTML.html(html);
                    reponseObj(html);
                }
            }
        },

        getBulkPaymentWindowInvoice: function(
            tableID,
            recordID,
            formTypeID,
            reponseObj
        ) {
            var html = "";
            recordsIds = [];
            var selectedRecords = phytoDataArray;
            // var data = SelectedData[SelectedData.length - 1];
            if (selectedRecords.length > 0) {
                for (let i = 0; i < selectedRecords.length; i++) {
                    recordsIds.push(selectedRecords[i]);
                }
                var formData = recordsIds;
                var companyName = "";
                var paid;
                var total = 0;
                var amount = 0;
                var currentamount = 0;
                var docNo = "";
                var description = "";
                var postpayrecordID = 0;
                $(".crud_section_lines").show();
                var visibility = "";
                try {
                    for (i in recordsIds) {
                        var url =
                            serverURL +
                            "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                            formData[i][recordID] +
                            "&formTypeID=" +
                            formTypeID;
                        recordIDPostPay = formData[i][recordID];
                        controller.requestWithToken(url, function(data, status) {
                            let desc = document.getElementById("description");
                            let amount = document.getElementById("totalAmount");
                            let currentamt = document.getElementById(
                                "currentSelecttotalAmount"
                            );
                            let docNumber = document.getElementById("documentNumberLabel");
                            let ispaid = document.getElementById("ispaidRecord");
                            if (data.length > 0) {
                                docNo = data[0].documentNumber;
                                total += data[0].amount;
                                currentamount = data[0].amount.toLocaleString();
                                amount.innerHTML = +total;
                                currentamt.innerHTML = +total;
                                docNumber.innerHTML = docNo;
                                var formattedTotal = total.toLocaleString();
                                if (data[0].isPaid == true || data[0].isPaid == "true") {
                                    visibility = "display:none; visibility: hidden";
                                    paid = "Paid";
                                    $("#buttonssectionholder").hide();
                                } else {
                                    $("#buttonssectionholder").show();
                                    paid = "Not Paid";
                                    visibility = "display:block;visibility: visible";
                                }
                                description +=
                                    "<label style='width: 400px'>" +
                                    data[0].description +
                                    "</label>" +
                                    "<label style='width: 80px'>" +
                                    "BIRR " +
                                    data[0].amount.toLocaleString() +
                                    "</label>" +
                                    "<label style='color:#3543B3'>" +
                                    paid +
                                    "</label>" +
                                    "<br>";
                                desc.innerHTML = description;
                            } else {
                                amount.innerHTML = 0;
                                paid = "No payment has been created";
                                docNumber.innerHTML = "None";
                                amount.innerHTML = total;
                                currentamount = 0;
                                currentamt.innerHTML = 0;
                                ispaid.innerHTML = "None";
                                desc.innerHTML = "No Payment found";
                            }
                        });
                    }
                } catch (error) {}
                var tableHTML = $(".crud_section_lines");
                tableHTML.html("");
                html = html + "<div  id='buttonssectionholder'>";
                html =
                    html +
                    "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton();' value='Pay' style='backgound-color: yellow; color: white'>";
                html =
                    html +
                    "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.refreshPayments();' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
                html =
                    html +
                    "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
                html = html + "</div>";
                html =
                    html +
                    '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
                html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
                html =
                    html +
                    '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
                html = html + "<tbody>";
                html = html + "<tr>";
                html = html + '<td width="5px" style="padding: 0;"></td>';
                html =
                    html +
                    '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
                html =
                    html +
                    '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
                html = html + "<tbody>";
                html =
                    html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                html =
                    html +
                    '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
                html = html + "<p>Payment Details</p>";
                html = html + "</td>";
                html = html + "<td>";
                html =
                    html +
                    '<p style="font-size: 12px">(Other charges)Convinience fee of BIRR 50 per Application</p>';
                html = html + "</td>";
                html = html + "</tr>";
                html = html + " </tbody>";
                html = html + "  </table>";
                html = html + " </td>";
                html = html + " </tr>";
                html = html + "<tr>";
                html = html + '<td width="5px" style="padding: 0;"></td>';
                html =
                    html +
                    '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
                html =
                    html +
                    '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
                html = html + "<tbody>";
                html = html + "<tr>";
                html =
                    html +
                    '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                    "Total Amount in BIRR " +
                    "<label id='currentSelecttotalAmount'></label>" +
                    '</strong ><span style="color:red; margin-left:4px">' +
                    "" +
                    "<label id='ispaidRecord'></label>" +
                    "</span></td>";
                html =
                    html +
                    '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                    '<label id="documentNumberLabel" style="color: #000"></label>' +
                    "</td>";
                html = html + "</tr>";
                html = html + "</tbody>";
                html = html + "</table>";
                html = html + "</td>";
                html = html + ' <td style="padding: 0;"></td>';
                html = html + '<td width="5px" style="padding: 0;"></td>';
                html = html + "</tr>";
                html = html + "<tr>";
                html = html + '<td width="5px" style="padding: 0;"></td>';
                html =
                    html +
                    '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
                html =
                    html +
                    '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
                html = html + "<tbody>";
                html = html + "<tr>";
                html = html + '<td valign="top"  style="padding: 20px;">';
                html = html + "<h3";
                html =
                    html +
                    'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
                html = html + "Summary";
                html = html + "</h3>";
                html =
                    html +
                    '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
                html = html + "<tbody>";
                html = html + "<tr>";
                html =
                    html + '<td><label id="description">' + description + "</label></td>";
                html = html + "</tr>";
                html =
                    html +
                    '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                html =
                    html +
                    '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
                html = html + "</tr>";
                html = html + "</tbody>";
                html = html + "</tr>";
                html = html + "</table>";
                html = html + "</td>";
                html = html + "</tr>";
                html = html + "</tbody>";
                html = html + "</table>";
                html = html + "</td>";
                html = html + '<td width="5px" style="padding: 0;"></td>';
                html = html + "</tr>";
                html = html + '<tr style="color: #666; font-size: 12px;">';
                html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                html =
                    html +
                    '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
                html = html + "</td>";
                html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                html = html + " </tr>";
                html = html + "</tbody>";
                html = html + " </table>";
                html = html + "</div>";
                html = html + "</div>";
                html = html + "</table>";
                tableHTML.html(html);
            } else {
                var html = "";
                var tableHTML = $(".crud_section_lines");
                tableHTML.html("");
                html = html + "</table>";
                tableHTML.html(html);
            }
        },

        getPaymentInvoice_phyto_main: function(recordID) {
            var formTypeID = 324;
            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".section_payments").show();
            var visibility = "";

            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description");
                let amount = document.getElementById("totalAmount");
                let currentamt = document.getElementById("currentSelecttotalAmount");
                let docNumber = document.getElementById("documentNumberLabel");
                let ispaid = document.getElementById("ispaidRecord");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                    } else {
                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            var tableHTML = $(".section_payments");
            html = html + "<div  id='buttonssectionholder'  style='display:none'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" +
                recordID +
                ");' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getPaymentInvoice_phyto_main(" +
                recordID +
                ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },

        getPaymentInvoice_By_RecordID_FormTypeID: function(recordID, formTypeID) {
            var formTypeID = formTypeID;
            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".section_payments").show();
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description");
                let amount = document.getElementById("totalAmount");
                let currentamt = document.getElementById("currentSelecttotalAmount");
                let docNumber = document.getElementById("documentNumberLabel");
                let ispaid = document.getElementById("ispaidRecord");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                    } else {
                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            var tableHTML = $(".section_payments");

            html = html + "<div  id='buttonssectionholder'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" +
                recordID +
                ");' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getPaymentInvoice_By_RecordID_FormTypeID(" +
                recordID +
                ", " +
                formTypeID +
                ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },
        getGlobalPaymentInvoce: function(recordID, formTypeID) {
            var formTypeID = formTypeID;
            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $("#section_payments").show();
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description");
                let amount = document.getElementById("totalAmount");
                let currentamt = document.getElementById("currentSelecttotalAmount");
                let docNumber = document.getElementById("documentNumberLabel");
                let ispaid = document.getElementById("ispaidRecord");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                    } else {
                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            var tableHTML = $("#section_payments");
            html = html + "<div  id='buttonssectionholder'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" +
                recordID +
                ");' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getGlobalPaymentInvoce(" +
                recordID +
                ", " +
                formTypeID +
                ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },










        getGlobalPaymentInvoceView: function(recordID, formTypeID) {
            var formTypeID = formTypeID;
            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $("#section_payments").show();
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description");
                let amount = document.getElementById("totalAmount");
                let currentamt = document.getElementById("currentSelecttotalAmount");
                let docNumber = document.getElementById("documentNumberLabel");
                let ispaid = document.getElementById("ispaidRecord");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                    } else {
                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            var tableHTML = $("#section_payments");
            html = html + "<div  id='buttonssectionholder'>";
            // html =
            //   html +
            //   "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" + recordID +");' value='Pay' style='backgound-color: yellow; color: white'>";
            // html = html +
            //   "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getGlobalPaymentInvoce(" +recordID + ", " + formTypeID + ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            // html =
            //   html +
            //   "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            // html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },



        getPaymentInvoice_By_RecordID_FormTypeID_edit: function(
            recordID,
            formTypeID
        ) {
            var formTypeID = formTypeID;
            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".section_payments_2").show();
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description");
                let amount = document.getElementById("totalAmount");
                let currentamt = document.getElementById("currentSelecttotalAmount");
                let docNumber = document.getElementById("documentNumberLabel");
                let ispaid = document.getElementById("ispaidRecord");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                        isPaid = true;
                    } else {
                        isPaid = false;
                        $("#previousbtn").show();

                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            // var tableHTML = $(".section_payments");
            var tableHTML2 = $(".section_payments_2");

            html = html + "<div  id='buttonssectionholder' style='display:none'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" +
                recordID +
                ");' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getPaymentInvoice_By_RecordID_FormTypeID_edit(" +
                recordID +
                ", " +
                formTypeID +
                ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            // tableHTML.html(html);
            tableHTML2.html(html);

            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },

        getPaymentInvoice_2: function(recordID) {
            var formTypeID = 324;

            var html = "";
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".section_payments_2").show();
            var visibility = "";

            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            controller.requestWithToken(url, function(data, status) {
                let desc = document.getElementById("description_2");
                let amount = document.getElementById("totalAmount_2");
                let currentamt = document.getElementById("currentSelecttotalAmount_2");
                let docNumber = document.getElementById("documentNumberLabel_2");
                let ispaid = document.getElementById("ispaidRecord_2");
                if (data.length > 0) {
                    docNo = data[0].documentNumber;
                    total += data[0].amount;
                    currentamount = data[0].amount.toLocaleString();
                    amount.innerHTML = +total;
                    currentamt.innerHTML = +total;
                    docNumber.innerHTML = docNo;
                    var formattedTotal = total.toLocaleString();
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none; visibility: hidden";
                        paid = "Paid";
                        $("#buttonssectionholder").hide();
                    } else {
                        $("#buttonssectionholder").show();
                        paid = "Not Paid";
                        visibility = "display:block;visibility: visible";
                    }
                    description +=
                        "<label style='width: 400px'>" +
                        data[0].description +
                        "</label>" +
                        "<label style='width: 80px'>" +
                        "BIRR " +
                        data[0].amount.toLocaleString() +
                        "</label>" +
                        "<label style='color:#3543B3'>" +
                        paid +
                        "</label>" +
                        "<br>";
                    desc.innerHTML = description;
                } else {
                    amount.innerHTML = 0;
                    paid = "No payment has been created";
                    docNumber.innerHTML = "None";
                    amount.innerHTML = total;
                    currentamount = 0;
                    currentamt.innerHTML = 0;
                    ispaid.innerHTML = "None";
                    desc.innerHTML = "No Payment found";
                }
            });

            var tableHTML = $(".section_payments_2");
            html = html + "<div  id='buttonssectionholder' style='display:none'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButtonNow(" +
                recordID +
                ");' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.getPaymentInvoice_2(" +
                recordID +
                ");' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount_2'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord_2'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel_2" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description_2">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount_2"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            // controller.getStepperPaymentsInvoice('.section_payments', recordID, formTypeID, function() {});
        },

        getStepperPaymentsInvoice: function(
            tableID,
            recordID,
            formTypeID,
            reponseObj
        ) {
            var html = "";
            recordsIds = [];
            var data = SelectedData[SelectedData.length - 1];
            for (let i = 0; i < data.length; i++) {
                recordsIds.push(data[i]);
            }
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".section_payments").show();
            var visibility = "";
            try {
                for (i in recordsIds) {
                    var url =
                        serverURL +
                        "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                        recordID +
                        "&formTypeID=" +
                        formTypeID;
                    recordIDPostPay = formData[i][recordID];
                    controller.requestWithToken(url, function(data, status) {
                        let desc = document.getElementById("description");
                        let amount = document.getElementById("totalAmount");
                        let currentamt = document.getElementById("currentSelecttotalAmount");
                        let docNumber = document.getElementById("documentNumberLabel");
                        let ispaid = document.getElementById("ispaidRecord");
                        if (data.length > 0) {
                            docNo = data[0].documentNumber;
                            total += data[0].amount;
                            currentamount = data[0].amount.toLocaleString();
                            amount.innerHTML = +total;
                            currentamt.innerHTML = +total;
                            docNumber.innerHTML = docNo;
                            var formattedTotal = total.toLocaleString();
                            if (data[0].isPaid == true || data[0].isPaid == "true") {
                                visibility = "display:none; visibility: hidden";
                                paid = "Paid";
                                $("#buttonssectionholder").hide();
                            } else {
                                $("#buttonssectionholder").show();
                                paid = "Not Paid";
                                visibility = "display:block;visibility: visible";
                            }
                            description +=
                                "<label style='width: 400px'>" +
                                data[0].description +
                                "</label>" +
                                "<label style='width: 80px'>" +
                                "BIRR " +
                                data[0].amount.toLocaleString() +
                                "</label>" +
                                "<label style='color:#3543B3'>" +
                                paid +
                                "</label>" +
                                "<br>";
                            desc.innerHTML = description;
                        } else {
                            amount.innerHTML = 0;
                            paid = "No payment has been created";
                            docNumber.innerHTML = "None";
                            amount.innerHTML = total;
                            currentamount = 0;
                            currentamt.innerHTML = 0;
                            ispaid.innerHTML = "None";
                            desc.innerHTML = "No Payment found";
                        }
                    });
                }
            } catch (error) {}
            var tableHTML = $(tableID);
            tableHTML.html("");
            html = html + "<div  id='buttonssectionholder'>";
            html =
                html +
                "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton()' value='Pay' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='controller.refreshPayments();' value='Refresh Payments' style='backgound-color: yellow; color: white'>";
            html =
                html +
                "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable();' value='Print Invoice' style='backgound-color: yellow; color: white'>";
            html = html + "</div>";
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "Total Amount in BIRR " +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "" +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            reponseObj(html);
        },

        getAllPrintoutAccountPaymentsInvoice: function(
            tableID,
            recordID,
            formTypeID,
            reponseObj
        ) {
            var html = "";
            recordsIds = [];
            var data = SelectedData[SelectedData.length - 1];
            for (let i = 0; i < data.length; i++) {
                recordsIds.push(data[i]);
            }
            var formData = recordsIds;
            var companyName = "";
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var description = "";
            var postpayrecordID = 0;
            $(".crud_attached_receipt").show();
            $(".crud_attached_receipt").html("Payment Loading... Please Wait");
            var visibility = "";
            try {
                for (i in recordsIds) {
                    var url =
                        serverURL +
                        "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                        formData[i][recordID] +
                        "&formTypeID=" +
                        formTypeID;
                    recordIDPostPay = formData[i][recordID];
                    controller.requestWithToken(url, function(data, status) {
                        paymentID = data[0].payment_id;
                        let desc = document.getElementById("description");
                        let amount = document.getElementById("totalAmount");
                        let currentamt = document.getElementById("currentSelecttotalAmount");
                        let docNumber = document.getElementById("documentNumberLabel");
                        let ispaid = document.getElementById("ispaidRecord");
                        if (data.length > 0) {
                            docNo = data[0].documentNumber;
                            total = data[0].amount.toLocaleString();
                            currentamount = data[0].amount.toLocaleString();
                            amount.innerHTML = total;
                            currentamt.innerHTML = currentamount;
                            docNumber.innerHTML = docNo;
                            var formattedTotal = total.toLocaleString();
                            if (data[0].isPaid == true || data[0].isPaid == "true") {
                                visibility = "display:none; visibility: hidden";
                                paid = "Paid";
                                ispaid.innerHTML = "Paid";
                                $("#buttonssectionholder").hide();
                            } else {
                                $("#buttonssectionholder").show();
                                paid = "Not Paid";
                                visibility = "display:block;visibility: visible";
                                ispaid.innerHTML = paid;
                            }
                            description +=
                                "<label style='width: 400px'>" +
                                data[0].description +
                                "</label>" +
                                "<label style='width: 80px'>" +
                                "BIRR " +
                                data[0].amount.toLocaleString() +
                                "</label>" +
                                "<label style='color:#3543B3'>" +
                                paid +
                                "</label>" +
                                "<br>";
                            desc.innerHTML = description;
                        } else {
                            amount.innerHTML = 0;
                            paid = "None";
                            docNumber.innerHTML = "None";
                            amount.innerHTML = total;
                            currentamount = 0;
                            currentamt.innerHTML = 0;
                            ispaid.innerHTML = "None";
                            desc.innerHTML =
                                "No Payment found for selected Replacement Application";
                        }
                        var url1 =
                            serverURL +
                            "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
                            paymentID;
                        var htmlview = "";
                        $.ajax({
                            url: url1,
                            type: "GET",
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            success: function(data2) {
                                try {
                                    var requiredDocJSON = data2;
                                    var tableHTML = $(".paymentdocuments");
                                    htmlview =
                                        htmlview +
                                        "<table class='table table-bordered'><tr style='background: #3543B3'><td colspan='2' style='text-align:left; color: #ffff ; font-weight: 800;'>Attachment</td></tr>";
                                    htmlview = htmlview + "<tr>";
                                    htmlview =
                                        htmlview + "<td>Proof Of Payment</td><td>Action</td>";
                                    htmlview = htmlview + "</tr>";
                                    htmlview = htmlview + "<tr>";
                                    htmlview =
                                        htmlview + "<td>" + requiredDocJSON[0]["name"] + "</td>";
                                    htmlview =
                                        htmlview +
                                        " <td><a href='javascript:controller.donwloadAttachment(" +
                                        JSON.stringify(requiredDocJSON[0]) +
                                        ") '><i>View Attachment</></a></td>";
                                    htmlview = htmlview + "</tr>";
                                    htmlview = htmlview + "</table>";
                                    tableHTML.html(htmlview);
                                } catch (error) {}
                            },
                            fail: function() {},
                            error: function(XMLHttpRequest, textStatus, errorThrown) {},
                        });
                    });
                }
            } catch (error) {}
            var tableHTML = $(tableID);
            tableHTML.html("");
            html =
                html +
                '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
            html = html + '<div id="invoiceprintout"  height="100%" width="100%">';
            html =
                html +
                '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; margin: 0 auto; max-width: 800px; padding: 10px 0;">';
            html =
                html +
                '<table width="100%" cellspacing="0" style="border-collapse: collapse;">';
            html = html + "<tbody>";
            html = html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
            html =
                html +
                '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
            html = html + "<p>Payment Details</p>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + " </tbody>";
            html = html + "  </table>";
            html = html + " </td>";
            html = html + " </tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block; margin: 0 auto; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html +
                '<td width="50%" style="padding: 20px;"><strong style="color: #333; font-size: 24px;"><i style="color:green; margin-right:4px" class="fa fa-money"> </i>' +
                "BIRR" +
                "<label id='currentSelecttotalAmount'></label>" +
                '</strong ><span style="color:red; margin-left:4px">' +
                "Selected Record Is: " +
                "<label id='ispaidRecord'></label>" +
                "</span></td>";
            html =
                html +
                '<td align="right" width="50%" style="padding: 20px;">Document Number: ' +
                '<label id="documentNumberLabel" style="color: #000"></label>' +
                "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + ' <td style="padding: 0;"></td>';
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + "<tr>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html =
                html +
                '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; margin: 0 auto; max-width: 800px; padding: 0;">';
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000; margin: 0 auto; max-width: 800px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html = html + '<td valign="top"  style="padding: 20px;">';
            html = html + "<h3";
            html =
                html +
                'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
            html = html + "Summary";
            html = html + "</h3>";
            html =
                html +
                '<table cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
            html = html + "<tbody>";
            html = html + "<tr>";
            html =
                html + '<td><label id="description">' + description + "</label></td>";
            html = html + "</tr>";
            html =
                html +
                '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
            html =
                html +
                '<td><label style="width: 400px">Total Amount</label>BIRR <label  id="totalAmount"></label></td>';
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</tr>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + "</tr>";
            html = html + "</tbody>";
            html = html + "</table>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 0;"></td>';
            html = html + "</tr>";
            html = html + '<tr style="color: #666; font-size: 12px;">';
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html =
                html +
                '<td style="clear: both; display: block; margin: 0 auto; max-width: 800px; padding: 10px 0;">';
            html = html + '<div id="paymentdocuments" class="paymentdocuments">';
            html = html + "</div>";
            html = html + "</td>";
            html = html + '<td width="5px" style="padding: 10px 0;"></td>';
            html = html + " </tr>";
            html = html + "</tbody>";
            html = html + " </table>";
            html = html + "</div>";
            html = html + "</div>";
            html = html + "</table>";
            tableHTML.html(html);
            reponseObj(html);
        },
        getPaymentInvoice: function(tableID, recordID, reponseObj) {
            var url = serverURL + "payment/getPaymentByExporter?exporterID=" + recordID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    $(".crud_section_lines").show();
                    var requiredDocJSON = data;
                    var tableHTML = $(tableID);
                    var visible = "";
                    html =
                        html +
                        "<table class='table table-striped'><tr><td style='color:#5ebd86'>Document Number</td><td style='color:#5ebd86'>Description</td><td style='color:#5ebd86'>Total Amount</td><td style='color:#3543B3'>Payment Status</td><td style='color:#3543B3'>Action</td></tr>";
                    var num = 0;
                    var paid;
                    try {
                        for (var i = 0; i < requiredDocJSON.length; i++) {
                            if (
                                requiredDocJSON[i].isPaid == true ||
                                requiredDocJSON[i].isPaid == "true"
                            ) {
                                var visibility = "style='visibility: hidden;'";
                                paid = "Paid";
                            } else {
                                var visibility = "style='visibility: visible;'";
                                paid = "Not Paid";
                            }
                            if (recordID == requiredDocJSON[i]["record_id"]) {
                                html =
                                    html +
                                    "<tr><td>" +
                                    requiredDocJSON[i]["documentNumber"] +
                                    "</td><td>" +
                                    requiredDocJSON[i]["description"] +
                                    "</td><td><i style='color:green;' class='fa fa-money' style='margin-right:4px'> </i> BIRR :" +
                                    requiredDocJSON[i]["amount"] +
                                    "</td><td style='color:#3543B3'>" +
                                    paid +
                                    "</td>";
                                html = html + "</td><td " + visibility + ">";
                                html =
                                    html +
                                    "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton(" +
                                    recordID +
                                    ");' value='Pay' style='backgound-color: yellow; color: white'>";
                                html =
                                    html +
                                    "<input type='button' id='payImporterRegistrationd'  class='btn btn-info' onclick='postPayPayments(" +
                                    requiredDocJSON[i]["payment_id"] +
                                    ");' value='On Account' style='backgound-color: yellow; color: white'>";
                                html =
                                    html +
                                    "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='refreshPayments();' value='Refresh Payments' style='backgound-color: yellow; color: white'></td>";
                            } else {
                                num++;
                                html =
                                    html +
                                    "<tr><td>" +
                                    num +
                                    ". " +
                                    requiredDocJSON[i]["documentNumber"] +
                                    "</td><td>" +
                                    requiredDocJSON[i]["description"] +
                                    "</td><td>BIRR" +
                                    requiredDocJSON[i]["amount"] +
                                    "</td></td><td></td>";
                                html = html + "</td><td>";
                                html = html + "<tr></tr>";
                            }
                        }
                    } catch (error) {}
                    html = html + "</table>";
                    tableHTML.html(html);
                    reponseObj(html);
                },
                fail: function() {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
            var html = "";
        },

        getExporterInvoice: function(tableID, recordID, reponseObj) {
            var html = "";
            recordsIds = [];
            var paid;
            var linesPaid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var paymentDate = "";
            var companyName = "";
            var otheritems = "";
            var description = "";
            $(".crud_section_2").html("Payment Loading... Please Wait!");
            var url = serverURL + "payment/getPaymentByExporter?exporterID=" + recordID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    if (data[0].amount != 0) {
                        $(".crud_section_2").show();
                        $(".crud_section_2").html("");
                        var tableHTML = $(tableID);
                        var visibility = "";
                        var tableHTML = $(tableID);
                        tableHTML.html("");
                        var requiredDocJSON = data;
                        var paymentID = requiredDocJSON[0].payment_id;
                        for (var i = 0; i < requiredDocJSON.length; i++) {
                            if (recordID == requiredDocJSON[i]["record_id"]) {
                                docNo = requiredDocJSON[i].documentNumber;
                                amount = requiredDocJSON[i].amount;
                                paymentDate = requiredDocJSON[i].paymentDate;
                                companyName = requiredDocJSON[i].user.company.name;
                                if (
                                    requiredDocJSON[i].isPaid == true ||
                                    requiredDocJSON[i].isPaid == "true"
                                ) {
                                    paid = "Paid";
                                    html = html + "<div>";
                                    html =
                                        html +
                                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable(" +
                                        recordID +
                                        ");' value='Preview Invoice' style='backgound-color: yellow; color: white;'></td>";
                                    html = html + "</div>";
                                } else {
                                    html = html + "<div>";
                                    html =
                                        html +
                                        "<input type='button' id='payImporterRegistrfation'  class='btn btn-success' onclick='paymentButton(" +
                                        recordID +
                                        ");' value='Pay' style='backgound-color: yellow; color: white;" +
                                        visibility +
                                        "'>";
                                    html =
                                        html +
                                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-success' onclick='refreshPayments();' value='Refresh Payments' style='backgound-color: yellow; color: white;" +
                                        visibility +
                                        "'></td>";
                                    html =
                                        html +
                                        "<input type='button' id='payImpdorterRegistration'  class='btn btn-warning' onclick='controller.PrintTable(" +
                                        recordID +
                                        ");' value='Print Invoice' style='backgound-color: yellow; color: white;'></td>";
                                    html = html + "</div>";
                                    paid = "Not Paid";
                                }
                            } else {
                                if (
                                    requiredDocJSON[i].isPaid == false ||
                                    requiredDocJSON[i].isPaid == "false"
                                ) {
                                    linesPaid = "Not Paid";
                                } else {
                                    linesPaid = "Paid";
                                }
                                total += requiredDocJSON[i].amount;
                                var formattedTotal = total.toLocaleString();
                                description +=
                                    "<label style='width: 400px'>" +
                                    requiredDocJSON[i].description +
                                    "</label>" +
                                    "<label style='width: 80px'>" +
                                    "BIRR " +
                                    requiredDocJSON[i].amount.toLocaleString() +
                                    "</label>" +
                                    "<label style='color:#3543B3'>" +
                                    linesPaid +
                                    "</label>" +
                                    "<br>";
                            }
                            if (total == 0) {
                                formattedTotal = 0;
                            }
                        }
                        html =
                            html +
                            '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
                        html =
                            html +
                            '<div id="invoiceprintout"  height="100%" width="100%"  style="padding-top: 10px;">';
                        html =
                            html +
                            '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding-top: 10px; width: 100%;" width="100%">';
                        html = html + "<tbody>";
                        html = html + "<tr>";
                        html = html + '<td width="5px" style="padding: 0;"></td>';
                        html =
                            html +
                            '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block;  max-width: 800px; padding: 0;">';
                        html =
                            html +
                            '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
                        html = html + "<tbody>";
                        html =
                            html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                        html =
                            html +
                            '<td style="padding: 0; font-weight:800; font-size:18px; text-align: center">';
                        html = html + "<p>Payment Details</p>";
                        html = html + "</td>";
                        html = html + "</tr>";

                        html = html + '<tr style="padding: 0; color: #000; ">';
                        html =
                            html +
                            '<td style="padding: 0; font-weight:800; font-size:14px; text-align: center">';
                        html =
                            html +
                            "<p>Kindly note that attaching an invalid document may lead to your application being rejected.</p>";
                        html = html + "</td>";
                        html = html + "</tr>";
                        html = html + "<tr>";
                        html =
                            html +
                            '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 24px;"><i style="color:green; margin-right:4px; font-size: 16px" class="fa fa-money"> </i>' +
                            "<label style='font-size: 18px'>BIRR:" +
                            formattedTotal +
                            "</label>" +
                            '</strong ><span style="color:#3543B3; margin-left:4px">' +
                            "Payment Status: " +
                            "<label>" +
                            paid +
                            "</label>" +
                            '</span><span style=" padding-left:20px; color: #000">Invoice No: ' +
                            docNo +
                            "</span></td>";
                        html = html + "</tr>";
                        html = html + "<tr>";
                        html =
                            html +
                            '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 16px;"><i style="color:green; margin-right:20px"> </i>' +
                            "Company Name: " +
                            "<label>" +
                            companyName +
                            "</label>" +
                            "</strong ></td>";
                        html = html + "</tr>";
                        html = html + "<tr>";
                        html =
                            html +
                            '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 16px;"><i style="color:green; margin-right:20px"> </i>' +
                            "Payment Date: " +
                            "<label>" +
                            paymentDate +
                            "</label>" +
                            "</strong ></td>";
                        html = html + "</tr>";
                        html = html + "</tbody>";
                        html = html + "</table>";
                        html = html + "</td>";
                        html = html + ' <td style="padding: 0;"></td>';
                        html = html + '<td width="5px" style="padding: 0;"></td>';
                        html = html + "</tr>";
                        html = html + "<tr>";
                        html = html + '<td width="5px" style="padding: 0;"></td>';
                        html =
                            html +
                            '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block;  max-width: 800px; padding: 0;">';
                        html =
                            html +
                            '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000; max-width: 800px;">';
                        html = html + "<tbody>";
                        html = html + "<tr>";
                        html = html + '<td valign="top"  style="padding: 20px;">';
                        html = html + "<h3>Summary</h3>";
                        html = html + '<table cellspacing="0">';
                        html = html + "<tbody>";
                        html = html + "<tr>";
                        html = html + "<td>" + description + "</td>";
                        html = html + "</tr>";
                        html =
                            html +
                            '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                        html =
                            html +
                            '<td><label style="width: 400px">Total Amount</label><label>BIRR' +
                            formattedTotal +
                            "</label></td>";
                        html = html + "</tr>";
                        html = html + "</tbody>";
                        html = html + "</tr>";
                        html = html + "</tr>";
                        html = html + "</table>";
                        html = html + "</td>";
                        html = html + "</tr>";
                        html = html + "</tbody>";
                        html = html + "</table>";
                        html = html + "</td>";
                        html = html + '<td width="5px" style="padding: 0;"></td>';
                        html = html + "</tr>";
                        html = html + '<tr style="color: #666; font-size: 12px;">';
                        html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                        html =
                            html +
                            '<td style="clear: both; display: block;  max-width: 800px; padding: 10px 0;">';
                        html = html + '<div id="paymentdocuments" class="paymentdocuments">';
                        html = html + "</div>";
                        html = html + "</td>";
                        html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                        html = html + " </tr>";
                        html = html + "</tbody>";
                        html = html + " </table>";
                        html = html + "</div>";
                        html = html + "</div>";
                        html = html + "</table>";
                        tableHTML.html(html);
                        var url1 =
                            serverURL +
                            "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
                            paymentID;
                        var htmlview = "";
                        $.ajax({
                            url: url1,
                            type: "GET",
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            success: function(data2) {
                                try {
                                    var requiredDocJSON = data2;
                                    var tableHTML = $(".paymentdocuments");
                                    htmlview =
                                        htmlview +
                                        "<table class='table table-bordered'><tr style='background: #3543B3'><td colspan='2' style='text-align:left; color: #ffff ; font-weight: 800;'>Attachment</td></tr>";
                                    htmlview = htmlview + "<tr>";
                                    htmlview =
                                        htmlview + "<td>Proof Of Payment</td><td>Action</td>";
                                    htmlview = htmlview + "</tr>";
                                    htmlview = htmlview + "<tr>";
                                    htmlview =
                                        htmlview + "<td>" + requiredDocJSON[0]["name"] + "</td>";
                                    htmlview =
                                        htmlview +
                                        " <td><a href='javascript:controller.previewExporterPayment(" +
                                        JSON.stringify(requiredDocJSON[0]) +
                                        ") '><i>View Attachment</></a></td>";
                                    htmlview = htmlview + "</tr>";
                                    htmlview = htmlview + "</table>";
                                    tableHTML.html(htmlview);
                                } catch (error) {}
                            },
                            fail: function() {},
                            error: function(XMLHttpRequest, textStatus, errorThrown) {},
                        });
                    } else {
                        var htmlview = "";
                        $(".crud_section_2").hide();
                        var tableHTML = $(".crud_section_payments_section");
                        htmlview = htmlview + "<table class='table table-bordered'>";
                        htmlview = htmlview + "<tr>";
                        htmlview =
                            htmlview +
                            "<td>To add details to your application click on the edit button.</td>";
                        htmlview = htmlview + "</tr>";
                        htmlview = htmlview + "</table>";
                        tableHTML.html(htmlview);
                    }
                },
                fail: function() {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
            var html = "";
        },

        getAccountantExporterInvoice: function(tableID, recordID, reponseObj) {
            var html = "";
            recordsIds = [];
            var paid;
            var linesPaid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var paymentDate = "";
            var companyName = "";
            var otheritems = "";
            var description = "";
            var checkNumber = "";
            $(".crud_attached_receipt").show();
            $(".crud_attached_receipt").html("Payment Loading... Please Wait");
            var url = serverURL + "payment/getPaymentByExporter?exporterID=" + recordID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    $(".crud_attached_receipt").show();
                    var tableHTML = $(tableID);
                    var visibility = "";
                    var tableHTML = $(tableID);
                    tableHTML.html("");
                    var requiredDocJSON = data;
                    var paymentID = requiredDocJSON[0].payment_id;
                    for (var i = 0; i < requiredDocJSON.length; i++) {
                        if (recordID == requiredDocJSON[i]["record_id"]) {
                            docNo = requiredDocJSON[i].documentNumber;
                            checkNumber = requiredDocJSON[i].checkNumber;
                            amount = requiredDocJSON[i].amount;
                            paymentDate = requiredDocJSON[i].paymentDate;
                            companyName = requiredDocJSON[i].user.company.name;
                            if (
                                requiredDocJSON[i].isPaid == true ||
                                requiredDocJSON[i].isPaid == "true"
                            ) {
                                paid = "Paid";
                            } else {
                                paid = "Not Paid";
                            }
                        } else {
                            if (
                                requiredDocJSON[i].isPaid == false ||
                                requiredDocJSON[i].isPaid == "false"
                            ) {
                                linesPaid = "Not Paid";
                            } else {
                                linesPaid = "Paid";
                            }
                            total += requiredDocJSON[i].amount;
                            var formattedTotal = total.toLocaleString();
                            description +=
                                "<label style='width: 400px'>" +
                                requiredDocJSON[i].description +
                                "</label>" +
                                "<label style='width: 80px'>" +
                                "BIRR " +
                                requiredDocJSON[i].amount.toLocaleString() +
                                "</label>" +
                                "<label style='color:#3543B3'>" +
                                linesPaid +
                                "</label>" +
                                "<br>";
                        }
                        if (total == 0) {
                            formattedTotal = 0;
                        }
                    }
                    html =
                        html +
                        '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
                    html =
                        html +
                        '<div id="invoiceprintout"  height="100%" width="100%"  style="padding-top: 10px;">';
                    html = html + '<div class="tableinvoice" id="tableinvoice">';
                    html =
                        html +
                        '<table bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding-top: 10px; width: 100%;" width="100%">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block; ; max-width: 800px; padding: 0;">';
                    html =
                        html +
                        '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999;">';
                    html = html + "<tbody>";
                    html =
                        html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                    html =
                        html +
                        '<td style="padding-left: 40px; font-weight:800; font-size:18px;">';
                    html = html + "<p>Payment Details</p>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 16px;"><i style="color:green; margin-right:20px" > </i>' +
                        "Company Name: " +
                        "<label>" +
                        companyName +
                        "</label>" +
                        "</strong ></td>";
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 16px;"><i style="color:green; margin-right:20px"> </i>' +
                        "Payment Date: " +
                        "<label>" +
                        paymentDate +
                        "</label>" +
                        "</strong ></td>";
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 24px;"><i style="color:green; margin-right:20px; font-size: 16px" > </i>' +
                        "<label style='font-size: 18px'>BIRR:" +
                        formattedTotal +
                        "</label>" +
                        '</strong ><span style="color:#3543B3; margin-left:4px">' +
                        "Payment Status: " +
                        "<label>" +
                        paid +
                        "</label>" +
                        '</span><span style=" padding-left:20px; color: #000">Invoice No: ' +
                        docNo +
                        '</span><span style=" padding-left:20px; color: #000">Reference No: ' +
                        checkNumber +
                        "</span></td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + ' <td style="padding: 0;"></td>';
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block; max-width: 800px; padding: 0;">';
                    html =
                        html +
                        '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000; margin: 0 auto; max-width: 800px;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td valign="top"  style="padding: 20px;">';
                    html = html + "<h3>Summary</h3>";
                    html = html + '<table cellspacing="0">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + "<td>" + description + "</td>";
                    html = html + "</tr>";
                    html =
                        html +
                        '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                    html =
                        html +
                        '<td><label style="width: 400px">Total Amount</label><label>BIRR' +
                        formattedTotal +
                        "</label></td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</tr>";
                    html = html + "</tr>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + '<tr style="color: #666; font-size: 12px;">';
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html =
                        html +
                        '<td style="clear: both; display: block; max-width: 800px; padding: 10px 0;">';
                    html = html + '<div id="paymentdocuments" class="paymentdocuments">';
                    html = html + "</div>";
                    html =
                        html + '<div id="donwloadAttachment" class="donwloadAttachment">';
                    html = html + "</div>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html = html + " </tr>";
                    html = html + "</tbody>";
                    html = html + " </table>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</table>";
                    tableHTML.html(html);
                    var url1 =
                        serverURL +
                        "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
                        paymentID;
                    var htmlview = "";
                    $.ajax({
                        url: url1,
                        type: "GET",
                        headers: {
                            Authorization: userObj.tokenType + " " + userObj.accessToken,
                        },
                        async: true,
                        success: function(data2) {
                            try {
                                var requiredDocJSON = data2;
                                var tableHTML = $(".paymentdocuments");
                                htmlview =
                                    htmlview +
                                    "<table class='table table-bordered'><tr style='background: #3543B3'><td colspan='2' style='text-align:left; color: #ffff ; font-weight: 800;'>Attachment</td></tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview = htmlview + "<td>Proof Of Payment</td><td>Action</td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview =
                                    htmlview + "<td>" + requiredDocJSON[0]["name"] + "</td>";
                                htmlview =
                                    htmlview +
                                    " <td><a href='javascript:controller.donwloadAttachment(" +
                                    JSON.stringify(requiredDocJSON[0]) +
                                    ") '><i>View Attachment</></a></td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "</table>";
                                tableHTML.html(htmlview);
                            } catch (error) {}
                        },
                        fail: function() {},
                        error: function(XMLHttpRequest, textStatus, errorThrown) {},
                    });
                },
                fail: function() {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
            var html = "";
        },
        getAccountantOtherApplicationsInvoice2: function(
            tableID,
            recordID,
            formTypeID,
            reponseObj
        ) {
            var html = "";
            recordsIds = [];
            var data = SelectedData[SelectedData.length - 1];
            for (let i = 0; i < data.length; i++) {
                recordsIds.push(data[i]);
            }
            var formData = recordsIds;
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var mode = "";
            var paymentID = 0;
            var description = "";
            var postpayrecordID = 0;

            // checkNumber
            // $(".crud_attached_receipt_2").show();
            // $('.crud_attached_receipt_2').html("Payment Loading... Please Wait");
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            recordIDPostPay = recordID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    console.log("getAccountantOtherApplicationsInvoice2", data);
                    paymentID = data[0].payment_id;
                    description = data[0].description;
                    docNo = data[0].documentNumber;
                    total = data[0].amount;
                    mode = data[0].paymentMode.name;
                    refno = data[0].rPnref;
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none";
                        paid = "Paid";
                    } else {
                        visibility = "display:block";
                        paid = "Not Paid";
                    }
                    var tableHTML = $(tableID);
                    tableHTML.html("");
                    html =
                        html +
                        '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%; !important" height="100%" width="100%">';
                    html =
                        html +
                        '<div id="invoiceprintout"  height="100%" width="100%"  style="padding-top: 20px">';
                    html = html + '<div class="tableinvoice" id="tableinvoice">';
                    html =
                        html +
                        '<table  bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block; max-width: 100%; padding: 0;">';
                    html =
                        html +
                        '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999; padding-top: 20px">';
                    html = html + "<tbody>";
                    html =
                        html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                    html =
                        html +
                        '<td style="padding-left: 20px; font-weight:800; font-size:18px;">';
                    html = html + "<p>Payment Details</p>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green;" > </i>' +
                        "BIRR" +
                        "<label id='currentSelecttotalAmount'>" +
                        total +
                        "</label>" +
                        '</strong ><span style="color:green; margin-left:4px">' +
                        "Payment Status: " +
                        "<label id='ispaidRecord'>" +
                        paid +
                        "</label><lable style='padding-left:10px'>Reference Number: " +
                        data[0].checkNumber +
                        "</label>" +
                        '</span><span><img style="float: right; padding-right: 15px; height: 66px;   width: 200px; padding-top: 3px;" src="img/EAAlogo.png" width="60px" height="30px"></span></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;">' +
                        '<label id="documentNumberLabel" style="color: #000">Document Number: ' +
                        docNo +
                        "</label>" +
                        "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + ' <td style="padding: 0;"></td>';
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block;  max-width: 100%; padding: 0;">';
                    html =
                        html +
                        '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 100%;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td valign="top"  style="padding: 20px;">';
                    html = html + "<h3";
                    html =
                        html +
                        'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
                    html = html + "Summary";
                    html = html + "</h3>";
                    html =
                        html +
                        '<table class="table table-bordered" cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 400px">' +
                        '<label id="description">' +
                        description +
                        "</label></td>";
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 100px">' +
                        '<label id="description">BIRR: ' +
                        total +
                        "</label></td>";
                    html = html + "</tr>";
                    html =
                        html +
                        '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 400px">' +
                        '<label id="description">Total Amount</label></td>';
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 100px">' +
                        '<label id="description"BIRR:>BIRR: ' +
                        total +
                        "</label></td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</tr>";
                    html = html + "</tr>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + '<tr style="color: #666; font-size: 12px;">';
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html =
                        html +
                        '<td style="clear: both; display: block;  max-width: 100%; padding: 10px 0;">';
                    html = html + '<div id="paymentdocuments" class="paymentdocuments">';
                    html = html + "</div>";

                    // html = html + '<div id="donwloadAttachment" class="donwloadAttachment">';
                    // html = html + '</div>';
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html = html + " </tr>";
                    html = html + "</tbody>";
                    html = html + " </table>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</table>";
                    tableHTML.html(html);
                    var url1 =
                        serverURL +
                        "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
                        paymentID;
                    var htmlview = "";
                    $.ajax({
                        url: url1,
                        type: "GET",
                        headers: {
                            Authorization: userObj.tokenType + " " + userObj.accessToken,
                        },
                        async: true,
                        success: function(data2) {
                            try {
                                var requiredDocJSON = data2;
                                var tableHTML = $(".paymentdocuments");
                                htmlview =
                                    htmlview +
                                    "<table class='table table-bordered'><tr style='background: #3543B3'><td colspan='2' style='text-align:left; color: #ffff ; font-weight: 800;'>Attachment</td></tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview =
                                    htmlview +
                                    "<td><h5>Proof Of Payment</h5></td><td><h5>Action</h5></td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview =
                                    htmlview + "<td>" + requiredDocJSON[0]["name"] + "</td>";
                                htmlview =
                                    htmlview +
                                    " <td><a href='javascript:controller.donwloadAttachment(" +
                                    JSON.stringify(requiredDocJSON[0]) +
                                    ") '><i>View Attachment</></a></td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "</table>";
                                tableHTML.html(htmlview);
                            } catch (error) {}
                        },
                        fail: function() {},
                        error: function(XMLHttpRequest, textStatus, errorThrown) {},
                    });
                },
                fail: function(e) {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        getAccountantOtherApplicationsInvoice: function(
            tableID,
            recordID,
            formTypeID,
            reponseObj
        ) {
            var html = "";
            recordsIds = [];
            var data = SelectedData[SelectedData.length - 1];
            for (let i = 0; i < data.length; i++) {
                recordsIds.push(data[i]);
            }
            var formData = recordsIds;
            var paid;
            var total = 0;
            var amount = 0;
            var currentamount = 0;
            var docNo = "";
            var mode = "";
            var paymentID = 0;
            var description = "";
            var postpayrecordID = 0;
            $(".crud_attached_receipt").show();
            $(".crud_attached_receipt").html("Payment Loading... Please Wait");
            var visibility = "";
            var url =
                serverURL +
                "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
                recordID +
                "&formTypeID=" +
                formTypeID;
            recordIDPostPay = recordID;
            $.ajax({
                url: url,
                headers: {
                    Authorization: userObj.tokenType + " " + userObj.accessToken,
                },
                async: true,
                success: function(data) {
                    paymentID = data[0].payment_id;
                    description = data[0].description;
                    docNo = data[0].documentNumber;
                    total = data[0].amount;
                    mode = data[0].paymentMode.name;
                    refno = data[0].rPnref;
                    if (data[0].isPaid == true || data[0].isPaid == "true") {
                        visibility = "display:none";
                        paid = "Paid";
                    } else {
                        visibility = "display:block";
                        paid = "Not Paid";
                    }
                    var tableHTML = $(tableID);
                    tableHTML.html("");
                    html =
                        html +
                        '<div  bgcolor="#f6f6f6" style="color: #333; height: 100%; width: 100%;" height="100%" width="100%">';
                    html =
                        html +
                        '<div id="invoiceprintout"  height="100%" width="100%"  style="padding-top: 20px">';
                    html = html + '<div class="tableinvoice" id="tableinvoice">';
                    html =
                        html +
                        '<table  bgcolor="#f6f6f6" cellspacing="0" style="border-collapse: collapse; padding: 2px; width: 100%;" width="100%">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td bgcolor="#FFFFFF" style="border: 1px solid #000; clear: both; display: block; max-width: 100%; padding: 0;">';
                    html =
                        html +
                        '<table width="100%" style="background: #f9f9f9; border-bottom: 1px solid #eee; border-collapse: collapse; color: #999; padding-top: 20px">';
                    html = html + "<tbody>";
                    html =
                        html + '<tr style="padding: 0; color: #fff; background: #3543B3 ">';
                    html =
                        html +
                        '<td style="padding-left: 20px; font-weight:800; font-size:18px;">';
                    html = html + "<p>Payment Details</p>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;"><strong style="color: #333; font-size: 18px;"><i style="color:green;" > </i>' +
                        "BIRR" +
                        "<label id='currentSelecttotalAmount'>" +
                        total +
                        "</label>" +
                        '</strong ><span style="color:green; margin-left:4px">' +
                        "Payment Status: " +
                        "<label id='ispaidRecord'>" +
                        paid +
                        "</label><lable style='padding-left:10px'>Reference Number: " +
                        data[0].checkNumber +
                        "</label>" +
                        '</span><span><img style="float: right; padding-right: 15px; height: 66px;   width: 200px; padding-top: 3px;" src="img/EAAlogo.png" width="60px" height="30px"></span></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td width="100%" style="padding-left: 20px;">' +
                        '<label id="documentNumberLabel" style="color: #000">Document Number: ' +
                        docNo +
                        "</label>" +
                        "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + ' <td style="padding: 0;"></td>';
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + "<tr>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html =
                        html +
                        '<td style="border: 1px solid #000; border-top: 0; clear: both; display: block;  max-width: 100%; padding: 0;">';
                    html =
                        html +
                        '<table cellspacing="0" style="border-collapse: collapse; border-left: 1px solid #000;  max-width: 100%;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html = html + '<td valign="top"  style="padding: 20px;">';
                    html = html + "<h3";
                    html =
                        html +
                        'style="border-bottom: 1px solid #000;color: #000;font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;font-size: 18px;  font-weight: bold; line-height: 1.2;   margin: 0; margin-bottom: 15px; padding-bottom: 5px;>';
                    html = html + "Summary";
                    html = html + "</h3>";
                    html =
                        html +
                        '<table class="table table-bordered" cellspacing="0" style="border-collapse: collapse; margin-bottom: 40px;">';
                    html = html + "<tbody>";
                    html = html + "<tr>";
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 400px">' +
                        '<label id="description">' +
                        description +
                        "</label></td>";
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 100px">' +
                        '<label id="description">BIRR: ' +
                        total +
                        "</label></td>";
                    html = html + "</tr>";
                    html =
                        html +
                        '<tr style="border-bottom: 2px solid #000; border-top: 2px solid #000; font-weight: bold; padding: 5px 0;">';
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 400px">' +
                        '<label id="description">Total Amount</label></td>';
                    html =
                        html +
                        '<td style="padding: 5px 0; width: 100px">' +
                        '<label id="description"BIRR:>BIRR: ' +
                        total +
                        "</label></td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</tr>";
                    html = html + "</tr>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + "</tr>";
                    html = html + "</tbody>";
                    html = html + "</table>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 0;"></td>';
                    html = html + "</tr>";
                    html = html + '<tr style="color: #666; font-size: 12px;">';
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html =
                        html +
                        '<td style="clear: both; display: block;  max-width: 100%; padding: 10px 0;">';
                    html = html + '<div id="paymentdocuments" class="paymentdocuments">';
                    html = html + "</div>";

                    html =
                        html + '<div id="donwloadAttachment" class="donwloadAttachment">';
                    html = html + "</div>";
                    html = html + "</td>";
                    html = html + '<td width="5px" style="padding: 10px 0;"></td>';
                    html = html + " </tr>";
                    html = html + "</tbody>";
                    html = html + " </table>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</div>";
                    html = html + "</table>";
                    tableHTML.html(html);
                    var url1 =
                        serverURL +
                        "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
                        paymentID;
                    var htmlview = "";
                    $.ajax({
                        url: url1,
                        type: "GET",
                        headers: {
                            Authorization: userObj.tokenType + " " + userObj.accessToken,
                        },
                        async: true,
                        success: function(data2) {
                            try {
                                var requiredDocJSON = data2;
                                var tableHTML = $(".paymentdocuments");
                                htmlview =
                                    htmlview +
                                    "<table class='table table-bordered'><tr style='background: #3543B3'><td colspan='2' style='text-align:left; color: #ffff ; font-weight: 800;'>Attachment</td></tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview =
                                    htmlview +
                                    "<td><h5>Proof Of Payment</h5></td><td><h5>Action</h5></td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "<tr>";
                                htmlview =
                                    htmlview + "<td>" + requiredDocJSON[0]["name"] + "</td>";
                                htmlview =
                                    htmlview +
                                    " <td><a href='javascript:controller.donwloadAttachment(" +
                                    JSON.stringify(requiredDocJSON[0]) +
                                    ") '><i>View Attachment</></a></td>";
                                htmlview = htmlview + "</tr>";
                                htmlview = htmlview + "</table>";
                                tableHTML.html(htmlview);
                            } catch (error) {}
                        },
                        fail: function() {},
                        error: function(XMLHttpRequest, textStatus, errorThrown) {},
                    });
                },
                fail: function(e) {},
                error: function(XMLHttpRequest, textStatus, errorThrown) {},
            });
        },
        donwloadAttachment: function(x, e) {
            $(".modal.fade.eporterPaymentdocument").modal("show");
            $("#donwloadAttachment").html("Attachment Preview Loading.. Please Wait");
            for (var key in x) {
                if (x.hasOwnProperty(key)) {
                    if (key == "docStatus") {
                        $("#" + key + "_name").val(x[key].name);
                    }
                    $("#" + key).val(x[key]);
                } else {
                    $("#" + key).val(x[key]);
                }
            }
            var imageURL = serverURL + "paymentDocument/downloadFile/" + x.name;
            $("#donwloadAttachment").html("Attachment Preview Loading.. Please Wait");
            controller.getFile(imageURL, function(response) {
                var path = x.path;
                var ext = path.split(".").pop();
                if (ext == "pdf") {
                    PDFObject.embed(response, "#donwloadAttachment");
                } else {
                    $("#donwloadAttachment").html(
                        "<img style='width:100%;min-height: 500px !important; height:100%;' src='" +
                        response +
                        "'>"
                    );
                }
            });
            $(".delete").show();
        },

        previewExporterPayment: function(x, e) {
            $(".modal.fade.eporterPaymentdocument").modal("show");
            $("#donwloadAttachment").html("Attachment Preview Loading.. Please Wait");
            for (var key in x) {
                if (x.hasOwnProperty(key)) {
                    if (key == "docStatus") {
                        $("#" + key + "_name").val(x[key].name);
                    }
                    $("#" + key).val(x[key]);
                } else {
                    $("#" + key).val(x[key]);
                }
            }
            var imageURL = serverURL + "paymentDocument/downloadFile/" + x.name;
            controller.getFile(imageURL, function(response) {
                var path = x.path;
                var ext = path.split(".").pop();
                if (ext == "pdf") {
                    PDFObject.embed(response, "#donwloadAttachment");
                } else {
                    $("#donwloadAttachment").html(
                        "<img style='width:100%;min-height: 500px !important; height:100%;' src='" +
                        response +
                        "'>"
                    );
                }
            });
            $(".delete").show();
        },

        PrintTableInvoicePdf: function(recordID) {
            document
                .getElementById("PrintTableInvoicePdf")
                .addEventListener("click", function() {
                    var invoiceContainer = document.querySelector(".invoice-container");

                    html2canvas(invoiceContainer).then(function(canvas) {
                        var pdf = new jsPDF();
                        var imgData = canvas.toDataURL("image/png");
                        pdf.addImage(
                            imgData,
                            "PNG",
                            0,
                            0,
                            pdf.internal.pageSize.getWidth(),
                            pdf.internal.pageSize.getHeight()
                        );
                        pdf.save("invoice.pdf");
                    });
                });
        },
        PrintTableInvoice: function(recordID) {
                var url = serverURL + "payment/getPaymentByExporter?exporterID=" + recordID;
                $.ajax({
                            url: url,
                            headers: {
                                Authorization: userObj.tokenType + " " + userObj.accessToken,
                            },
                            async: true,
                            success: function(data) {
                                    var total = data[0].amount;
                                    var formattedTotal = total.toLocaleString();
                                    var totalAmount = data.reduce(
                                        (total, payment) => total + payment.amount,
                                        0
                                    );

                                    var invoiceHtml = `<style>
                              body {
                                  font-family: Arial, sans-serif;
                                  margin: 0;
                                  padding: 0;
                              }
                              .invoice-container {
                                  max-width: 800px;
                                  padding: 20px;
                                  border: 1px solid #ccc;
                                  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
                                  background-color: #fff;
                              }
                              .invoice-header {
                                  text-align: center;
                                  margin-bottom: 20px;
                              }
                              .invoice-title {
                                  font-size: 24px;
                                  color: #333;
                                  margin-bottom: 10px;
                              }
                              .invoice-details {
                                  margin-bottom: 20px;
                              }
                              .invoice-details p {
                                  margin: 5px 0;
                              }
                              table {
                                  width: 100%;
                                  border-collapse: collapse;
                                  margin-bottom: 20px;
                              }
                              th, td {
                                  padding: 10px;
                                  border-bottom: 1px solid #ccc;
                                  text-align: left;
                              }
                              th {
                                  background-color: #f5f5f5;
                              }
                              .invoice-total {
                                  text-align: right;
                              }
                              .invoice-status {
                                  text-align: right;
                              }
                              .paid {
                                  color: green;
                              }
                              .not-paid {
                                  color: red;
                              }
                          </style>
                          <div class="invoice-container_section">
                          <input type='button' id='PrintTableInvoicePdf'  class='btn btn-warning' onclick='controller.PrintTableInvoicePdf();' value='Generate PDF' style='backgound-color: yellow; color: white;'>
                          <div class="invoice-container">
                          <div class="invoice-header">
                              <h2 class="invoice-title">Payment Invoice</h2>
                          </div>
                          <div class="invoice-details">
                              <div class="company-details">
                                  <p style="display: inline-block;">Company Name: ${
                                    data[0].user.company.name
                                  }</p>
                                  <img src="img/EAAlogo.png" alt="Company Logo" style="width: 180px; height: auto; float: right;">
                              </div>
                              <p>Total Amount BIRR : ${formattedTotal}</p>
                              <p>Document Number: ${data[0].documentNumber}</p>
                              <p>Invoice Number: ${data[0].rPnref}</p>
                              <p>Payment Date: ${data[0].paymentDate}</p>
                          </div>
                          <table>
                              <tr>
                                  <th>Description</th>
                                  <th>Amount</th>
                              </tr>
                              ${data
                                .map(
                                  (payment) => `
                                  <tr>
                                      <td>${payment.description}</td>
                                      <td>${payment.amount}</td>
                                  </tr>
                              `
                                )
                                .join("")}
                          </table>
                          <div class="invoice-total">
                              <p>Total Amount: ${formattedTotal}</p>
                          </div>
                          <div class="invoice-status">
                              <p class="${
                                data[0].isPaid ? "paid" : "not-paid"
                              }">Status: ${
            data[0].isPaid ? "Paid" : "Not Paid"
          }</p>
                          </div>
                      </div>
                      </div>
                      `;
  
          // Append or insert 'invoiceHtml' into your desired element in the DOM
  
          // Inject the invoice HTML into the DOM element
          var invoiceContainer = document.getElementById(
            "crud_section_payments_section"
          );
          invoiceContainer.innerHTML = invoiceHtml;
        },
        fail: function () {},
        error: function (XMLHttpRequest, textStatus, errorThrown) {},
      });
      var html = "";
    },
  
    PrintTable: function () {
      var printWindow = window.open("", "_blank", "height=600,width=800");
      printWindow.document.write("<html><head><title>Payment Details</title>");
      var table_style = document.getElementById("table_style").innerHTML;
      printWindow.document.write('<style type = "text/css">');
      printWindow.document.write(table_style);
      printWindow.document.write("</style>");
      printWindow.document.write("</head>");
      printWindow.document.write("<body>");
      var divContents = document.getElementById("invoiceprintout").innerHTML;
      printWindow.document.write(divContents);
      printWindow.document.write("</body>");
      printWindow.document.write("</html>");
      printWindow.print();
      printWindow.document.close();
    },
    refreshPayments: function () {
      location.reload();
    },
    postPayPayments: function (payment_id) {
      var url =
        serverURL + "payment/updatePostPaymentByID?paymentID=" + payment_id + "";
      controller.requestWithTokenPOST(url, "", function (data, status) {
        if (data) {
          controller.showToastMsg(
            "Payment Successfully Updated...Proceed",
            "#1a5589"
          );
          setTimeout(() => {
            refreshPayments();
          }, 1000);
        }
      });
    },
    otherpaymentmodesAttachments: function (
      tableID,
      recordID,
      amount,
      reponseObj
    ) {
      var url =
        serverURL +
        "paymentDocument/getPaymentDocumentByPaymentID?paymentID=" +
        recordID;
      var html = "";
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        success: function (data) {
          var requiredDocJSON = data;
          var jsonData = requiredDocJSON;
          var documentTypesUploaded = [];
          var tableHTML = $(tableID);
          var visible = "";
          var visibility = "style='visibility: hidden; display:none'";
          html =
            html +
            "<h3 style='color:#3543B3; border-bottom: 0px;'> Total Amount Expected To Pay: BIRR " +
            amount +
            "</h3>";
          html =
            html +
            "<table class='table table-striped'><tr><td>Attachment</td><td>Path(Click link to Preview)</td><td>Status</td></tr>";
          try {
            for (var i = 0; i < requiredDocJSON.length; i++) {
              html =
                html +
                "<tr><td>" +
                requiredDocJSON[i]["name"] +
                "</td><td><a href='javascript:controller.previewglobalDocument(" +
                JSON.stringify(requiredDocJSON[i]["name"]) +
                ",this);'>" +
                jsonData[i]["name"] +
                "</a></td>";
              html = html + "</td>";
            }
          } catch (error) {}
          html = html + "</table>";
          tableHTML.html(html);
          reponseObj(html);
        },
        fail: function () {},
        error: function (XMLHttpRequest, textStatus, errorThrown) {},
      });
    },
    loadDocumentsReportsByRecordidandTableid: function (
      tableID,
      recordID,
      tableRegisterID,
      reponseObj
    ) {
      var html = "";
      if (isCrudAttachmentview == false) {
        var visibility = "style='visibility: hidden; display:none'";
      } else if (isCrudAttachmentview == true) {
        html =
          html +
          "<div id='uploaldDocumentReportsdiv'> <a href='javascript:BtnuploadDocumentReports();'><input type='button' id='attachdocumentglobal' class='upload_btn ui button btn btn-info' style='background: burlywood; ' value='Upload Document'></a></div> ";
      }
      var url =
        serverURL +
        "globalDocument/getGlobalDocumentByTableRegisterAndRecordID?tableRegisterId=" +
        tableRegisterID +
        "&recordId=" +
        recordID;
      controller.getUploadDocumentsByUser(
        recordID,
        tableRegisterID,
        function (response) {
          var requiredDocJSON = response;
          $.ajax({
            url: url,
            headers: {
              Authorization: userObj.tokenType + " " + userObj.accessToken,
            },
            async: true,
            success: function (data) {
              var jsonData = requiredDocJSON;
              var documentTypesUploaded = [];
              var tableHTML = $(tableID);
              var visible = "";
              var visibility = "visibility: hidden; display:none";
              html =
                html +
                "<table class='table table-striped'><tr><td>Document</td><td>Path(Click to Preview)</td><td>Status</td><td id='updatecolumnVisisbility' style='" +
                visibility +
                "'>Update Document</td></tr>";
              try {
                for (var i = 0; i < requiredDocJSON.length; i++) {
                  html =
                    html +
                    "<tr><td>" +
                    requiredDocJSON[i]["name"] +
                    "</td><td><a href='javascript:controller.previewglobalDocument(" +
                    JSON.stringify(requiredDocJSON[i]["name"]) +
                    ",this);'>" +
                    jsonData[i]["name"] +
                    "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                  html = html + "</td><td>";
                  html =
                    html +
                    "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                  html =
                    html +
                    "<input type='hidden' name='projectid' class='projectid'>";
                  html =
                    html +
                    "<input type='hidden' name='projectdocumentid' class='projectdocumentid'>";
                  html =
                    html +
                    "<input type='hidden' class='attachment_id' name='attachment_id' id='attachment_id'>";
                  html =
                    html +
                    "<input type='hidden' class='name' name='name' id='name'>";
                  html =
                    html +
                    "<input type='hidden' class='downloadUri' name='downloadUri' id='downloadUri'>";
                  html =
                    html +
                    "<input type='button' id='btnupdatedocuments'  class='btn btn-info' onclick='controller.editglobalDocument(" +
                    requiredDocJSON[i]["globalDocument_id"] +
                    ",this," +
                    JSON.stringify(jsonData[i]) +
                    ");' value='Update Document' style='backgound-color: yellow; color: white; " +
                    visibility +
                    "'></form></td>";
                }
              } catch (error) {}
              html = html + "</table>";
              tableHTML.html(html);
              reponseObj(html);
            },
            fail: function () {},
            error: function (XMLHttpRequest, textStatus, errorThrown) {},
          });
        }
      );
    },
    loadDocumentsUploadStatus: function (tableID, url, formType_id, reponseObj) {
      controller.getRequiredDocument(formType_id, function (response) {
        var requiredDocJSON = response;
        $.ajax({
          url: url,
          headers: {
            Authorization: userObj.tokenType + " " + userObj.accessToken,
          },
          async: true,
          success: function (data) {
            var visibility;
            var jsonData = data;
            var documentTypesUploaded = [];
            var tableHTML = $(tableID);
            if (
              formObj.formName.startsWith("assign") ||
              formObj.formName.startsWith("assigned")
            ) {
              visibility = "style='visibility: hidden; display:none'";
            }
            if (isreadOnly == true) {
              visibility = "style='visibility: hidden; display:none'";
            }
            var newData = JSON.parse(localStorage.getItem("userObj"));
            html =
              html +
              "<table class='table table-striped'><tr><td>Document Type</td><td>Document</td><td>Status</td><td id='documentupdate'" +
              visibility +
              ">Action</td></tr>";
            for (var i = 0; i < requiredDocJSON.length; i++) {
              var selectVal = requiredDocJSON[i];
              var exists = false;
              var visibility_institution_letter = "";
              var visibility_certificate_of_Incorporation = "";
              for (var j = 0; j < jsonData.length; j++) {
                if (
                  jsonData[j]["documentUploadType"]["documentUploadType_id"] ==
                  requiredDocJSON[i]["documentUploadType"][
                    "documentUploadType_id"
                  ]
                ) {
                  try {
                    if (newData.company.entityType.entityType_id == 7080) {
                      if (
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] == 3472
                      ) {
                        visibility_institution_letter = "";
                      } else {
                        visibility_institution_letter = "";
                      }
                    } else {
                      if (
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] == 3472
                      ) {
                      } else {
                        visibility_institution_letter = "";
                      }
                    }
                  } catch (error) {}
                  if (allFormObj["parent_selected"]["isResearcher"]) {
                    if (
                      jsonData[j]["documentUploadType"][
                        "documentUploadType_id"
                      ] == 7631
                    ) {
                      visibility_institution_letter = "";
                    } else {
                      visibility_institution_letter = "";
                    }
                  } else {
                    if (
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] == 7631
                    ) {
                      visibility_institution_letter = "display:none;";
                    } else {
                      visibility_institution_letter = "";
                    }
                  }
                  exists = true;
                  html =
                    html +
                    "<tr  style='" +
                    visibility_institution_letter +
                    "' status='" +
                    jsonData[j]["isActive"] +
                    "'><td>" +
                    requiredDocJSON[i]["documentUploadType"]["name"] +
                    "</td><td><a href='javascript:controller.editDocumentRow(" +
                    JSON.stringify(jsonData[j]) +
                    ",this);'>" +
                    jsonData[j]["name"] +
                    "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                  if (formObj.crudEdit == false) {
                  } else {
                    if (isreadOnly == false) {
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-default' onclick='controller.saveDocument(" +
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        ",this," +
                        JSON.stringify(jsonData[j]) +
                        ");' value='Save New Document'></form></td>";
                    } else {
                      $("#documentupdate").hide();
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                    }
                  }
                  html = html + "</tr>";
                }
              }
              if (exists == false) {
                try {
                  if (newData.company != null) {
                    if (newData.company.entityType.entityType_id == 7080) {
                      if (
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ] == 3472
                      ) {
                        visibility_institution_letter = "display:none;";
                      } else {
                        visibility_institution_letter = "";
                      }
                    } else {
                      if (
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ] == 3472
                      ) {
                      } else {
                        visibility_institution_letter = "";
                      }
                    }
                  }
                } catch (error) {}
                if (allFormObj["parent_selected"]["isResearcher"]) {
                  if (
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] == 7631
                  ) {
                    visibility_institution_letter = "";
                  } else {
                    visibility_institution_letter = "";
                  }
                } else {
                  if (
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] == 7631
                  ) {
                    visibility_institution_letter = "display:none;";
                  } else {
                    visibility_institution_letter = "";
                  }
                }
                if (isreadOnly == false) {
                  html =
                    html +
                    "<tr style='" +
                    visibility_institution_letter +
                    "'><td>" +
                    requiredDocJSON[i]["documentUploadType"]["name"] +
                    "</td>";
                  html = html + "</td><td>";
                  html =
                    html +
                    "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                  html =
                    html +
                    "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                  html =
                    html +
                    "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                  html =
                    html +
                    "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                  html =
                    html +
                    "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                  html =
                    html +
                    "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-primary' onclick='controller.saveDocument(" +
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] +
                    ",this," +
                    JSON.stringify(jsonData[j]) +
                    ");' value='Save Document'></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                } else {
                  html =
                    html +
                    "<tr style='" +
                    visibility_institution_letter +
                    "'><td>" +
                    requiredDocJSON[i]["documentUploadType"]["name"] +
                    "</td>";
                  html = html + "</td><td>";
                  html =
                    html +
                    "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                  html =
                    html +
                    "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                  html =
                    html +
                    "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                  html =
                    html +
                    "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                  html =
                    html +
                    "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                }
              }
            }
            html = html + "</table>";
            tableHTML.html(html);
            reponseObj(html);
          },
          fail: function () {},
          error: function (XMLHttpRequest, textStatus, errorThrown) {},
        });
      });
      var html = "";
    },
  
    loadRequiredDocumentsImporter: function (
      tableID,
      url,
      formType_id,
      reponseObj
    ) {
      controller.getRequiredDocument(formType_id, function (response) {
        var requiredDocJSON = response;
        $.ajax({
          url: url,
          headers: {
            Authorization: userObj.tokenType + " " + userObj.accessToken,
          },
          async: true,
          success: function (data) {
            var visibility;
            var jsonData = data;
            var documentTypesUploaded = [];
            var tableHTML = $(tableID);
  
            var newData = JSON.parse(localStorage.getItem("userObj"));
            html =
              html +
              "<table class='table table-striped'><tr><td>Document Type</td><td>Document</td><td>Status</td><td id='documentupdate'" +
              visibility +
              ">Action</td></tr>";
            for (var i = 0; i < requiredDocJSON.length; i++) {
              var selectVal = requiredDocJSON[i];
              var exists = false;
              var visibility_institution_letter = "";
              var visibility_certificate_of_Incorporation = "";
  
              if (registered == true) {
                for (var j = 0; j < jsonData.length; j++) {
                  if (
                    jsonData[j]["documentUploadType"]["documentUploadType_id"] ==
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ]
                  ) {
                    try {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "display: none";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    } catch (error) {}
  
                    exists = true;
                    html =
                      html +
                      "<tr  style='" +
                      visibility_institution_letter +
                      "' status='" +
                      jsonData[j]["isActive"] +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td><td><a href='javascript:viewImporterDocuments(" +
                      JSON.stringify(jsonData[j]) +
                      ",this);'>" +
                      jsonData[j]["name"] +
                      "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                    if (inprogress == false) {
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf' onchange='controller.saveAttachmentsEdit(" +
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        ",this," +
                        JSON.stringify(jsonData[j]) +
                        ")'><br></form></td>";
                    } else {
                      $("#documentupdate").hide();
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                    }
                    html = html + "</tr>";
                  }
                }
                if (exists == false) {
                  try {
                    if (newData.company != null) {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "display:none;";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    }
                  } catch (error) {}
                  if (
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] == 7631
                  ) {
                    visibility_institution_letter = "display:none;";
                  } else {
                    // comment out this line if importer is individual - Certificate of Incorporation/Business Registration
                    // visibility_institution_letter = "";
                  }
                  if (isreadOnly == false) {
                    console.log("documentUploadType documentUploadType");
  
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                    html =
                      html +
                      "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf' onchange='controller.saveAttachments(" +
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] +
                      ",this," +
                      JSON.stringify(requiredDocJSON[i]) +
                      ")'><br></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                  } else {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                  }
                }
              } else {
                console.log("documentUploadType documentUploadType");
  
                for (var j = 0; j < jsonData.length; j++) {
                  if (
                    jsonData[j]["documentUploadType"]["documentUploadType_id"] ==
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ]
                  ) {
                    try {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    } catch (error) {}
  
                    exists = true;
                    html =
                      html +
                      "<tr  style='" +
                      visibility_institution_letter +
                      "' status='" +
                      jsonData[j]["isActive"] +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td><td><a href='javascript:viewImporterDocuments(" +
                      JSON.stringify(jsonData[j]) +
                      ",this);'>" +
                      jsonData[j]["name"] +
                      "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                    if (formObj.crudEdit == false) {
                    } else {
                      if (isreadOnly == false) {
                        html =
                          html +
                          "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                          jsonData[j]["exporterDocument_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                          jsonData[j]["docStatus"]["docStatus_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf'  onchange='controller.saveAttachmentsEdit(" +
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          ",this," +
                          JSON.stringify(jsonData[j]) +
                          ")'><br></form></td>";
                      } else {
                        $("#documentupdate").hide();
                        html =
                          html +
                          "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                          jsonData[j]["exporterDocument_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                          jsonData[j]["docStatus"]["docStatus_id"] +
                          "'>";
                      }
                    }
                    html = html + "</tr>";
                  }
                }
                if (exists == false) {
                  try {
                    if (newData.company != null) {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "display:none;";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    }
                  } catch (error) {}
                  var isResearcher = responseData[0].isResearcher;
                  if (isResearcher == true) {
                    if (
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] == 7631
                    ) {
                      visibility_institution_letter = "display:block;";
                    }
                    try {
                      $("#isExportConsolidator").prop("disabled", true); //true|disabled will work on all
                      $("#isDryCommodityExporter").prop("disabled", true); //true|disabled will work on all
                      $("#isOwnFarmExporter").prop("disabled", true); //true|disabled will work on all
                    } catch (error) {}
                  } else {
                    if (
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] == 7631
                    ) {
                      visibility_institution_letter = "display:none;";
                    }
                    try {
                      $("#isExportConsolidator").prop("disabled", false); //true|disabled will work on all
                      $("#isDryCommodityExporter").prop("disabled", false); //true|disabled will work on all
                      $("#isOwnFarmExporter").prop("disabled", false); //true|disabled will work on all
                    } catch (error) {}
                  }
                  if (isreadOnly == false) {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                    html =
                      html +
                      "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf' onchange='controller.saveAttachments(" +
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] +
                      ",this," +
                      JSON.stringify(requiredDocJSON[i]) +
                      ")'><br></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                  } else {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                  }
                }
              }
            }
            html = html + "</table>";
            tableHTML.html(html);
            reponseObj(html);
          },
          fail: function () {},
          error: function (XMLHttpRequest, textStatus, errorThrown) {},
        });
      });
      var html = "";
    },
  
    loadRequiredDocumentsExporter: function (
      tableID,
      url,
      formType_id,
      reponseObj
    ) {
      var urlEXP = serverURL + "exporter/getExporterByCompanyID";
      $.ajax({
        url: urlEXP,
        type: "GET",
        async: true,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        success: function (responseData, textStatus, xhr) {
  
          console.log("responseData   :::::::::::", responseData[0].exporterID)
          var exportid = responseData[0].exporterID;
          
          controller.getRequiredDocumentExporter(exportid, formType_id, function (response) {
            var requiredDocJSON = response;
            $.ajax({
              url: url,
              headers: {
                Authorization: userObj.tokenType + " " + userObj.accessToken,
              },
              async: true,
              success: function (data) {
                var visibility;
                var jsonData = data;
                var documentTypesUploaded = [];
                var tableHTML = $(tableID);
  
                var newData = JSON.parse(localStorage.getItem("userObj"));
                html =
                  html +
                  "<table class='table table-striped'><tr><td>Document Type</td><td>Document</td><td>Status</td><td id='documentupdate'" +
                  visibility +
                  ">Action</td></tr>";
                for (var i = 0; i < requiredDocJSON.length; i++) {
                  var selectVal = requiredDocJSON[i];
                  var exists = false;
                  var visibility_institution_letter = "";
                  var visibility_certificate_of_Incorporation = "";
  
                  if (registered == true) {
                    for (var j = 0; j < jsonData.length; j++) {
                      if (
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] ==
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ]
                      ) {
                        try {
                          if (newData.company.entityType.entityType_id == 7080) {
                            if (
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                              visibility_institution_letter = "";
                            } else {
                              visibility_institution_letter = "";
                            }
                          } else {
                            if (
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                            } else {
                              visibility_institution_letter = "";
                            }
                          }
                        } catch (error) {}
  
                        exists = true;
                        html =
                          html +
                          "<tr  style='" +
                          visibility_institution_letter +
                          "' status='" +
                          jsonData[j]["isActive"] +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td><td><a href='javascript:viewImporterDocuments(" +
                          JSON.stringify(jsonData[j]) +
                          ",this);'>" +
                          jsonData[j]["name"] +
                          "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                        if (inprogress == false) {
                          html =
                            html +
                            "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                          html =
                            html +
                            "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                            jsonData[j]["exporterDocument_id"] +
                            "'>";
                          html =
                            html +
                            "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                          html =
                            html +
                            "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                            jsonData[j]["documentUploadType"][
                              "documentUploadType_id"
                            ] +
                            "'>";
                          html =
                            html +
                            "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                            jsonData[j]["docStatus"]["docStatus_id"] +
                            "'>";
                          html =
                            html +
                            "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf'  onchange='controller.saveAttachmentsExporterEdit(" +
                            requiredDocJSON[i]["documentUploadType"][
                              "documentUploadType_id"
                            ] +
                            ",this," +
                            JSON.stringify(jsonData[j]) +
                            ")'><br></form></td>";
                        } else {
                          $("#documentupdate").hide();
                          html =
                            html +
                            "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                          html =
                            html +
                            "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                            jsonData[j]["exporterDocument_id"] +
                            "'>";
                          html =
                            html +
                            "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                          html =
                            html +
                            "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                            jsonData[j]["documentUploadType"][
                              "documentUploadType_id"
                            ] +
                            "'>";
                          html =
                            html +
                            "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                            jsonData[j]["docStatus"]["docStatus_id"] +
                            "'>";
                        }
                        html = html + "</tr>";
                      }
                    }
                    if (exists == false) {
                      try {
                        if (newData.company != null) {
                          if (newData.company.entityType.entityType_id == 7080) {
                            if (
                              requiredDocJSON[i]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                              visibility_institution_letter = "display:none;";
                            } else {
                              visibility_institution_letter = "";
                            }
                          } else {
                            if (
                              requiredDocJSON[i]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                            } else {
                              visibility_institution_letter = "";
                            }
                          }
                        }
                      } catch (error) {}
  
                      var isResearcher = responseData[0].isResearcher;
                      if (isResearcher == true) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 7631
                        ) {
                          visibility_institution_letter = "";
                        }
                        try {
                          $("#isExportConsolidator").prop("disabled", true); //true|disabled will work on all
                          $("#isDryCommodityExporter").prop("disabled", true); //true|disabled will work on all
                          $("#isOwnFarmExporter").prop("disabled", true); //true|disabled will work on all
                        } catch (error) {}
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 7631
                        ) {
                          visibility_institution_letter = "display:none;";
                        }
                        try {
                          $("#isExportConsolidator").prop("disabled", false); //true|disabled will work on all
                          $("#isDryCommodityExporter").prop("disabled", false); //true|disabled will work on all
                          $("#isOwnFarmExporter").prop("disabled", false); //true|disabled will work on all
                        } catch (error) {}
                      }
  
                      if (isreadOnly == false) {
                        html =
                          html +
                          "<tr style='" +
                          visibility_institution_letter +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td>";
                        html = html + "</td><td>";
                        html =
                          html +
                          "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        try {
                          if (newData.company != null) {
                            if (
                              newData.company.entityType.entityType_id == 7080
                            ) {
                              if (
                                requiredDocJSON[i]["documentUploadType"][
                                  "documentUploadType_id"
                                ] == 3472
                              ) {
                                visibility_institution_letter = "display:none;";
                              } else {
                                visibility_institution_letter = "";
                              }
                            } else {
                              if (
                                requiredDocJSON[i]["documentUploadType"][
                                  "documentUploadType_id"
                                ] == 3472
                              ) {
                              } else {
                                visibility_institution_letter = "";
                              }
                            }
                          }
                        } catch (error) {}
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 7631
                        ) {
                          visibility_institution_letter = "display:none;";
                        } else {
                          visibility_institution_letter = "";
                        }
                        tml =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                        html =
                          html +
                          "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf' onchange='controller.saveAttachmentsExporter(" +
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          ", this, " +
                          JSON.stringify(requiredDocJSON[i]) +
                          ")'><br></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                      } else {
                        html =
                          html +
                          "<tr style='" +
                          visibility_institution_letter +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td>";
                        html = html + "</td><td>";
                        html =
                          html +
                          "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                      }
                    }
                  } else {
                    for (var j = 0; j < jsonData.length; j++) {
                      if (
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] ==
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ]
                      ) {
                        try {
                          if (newData.company.entityType.entityType_id == 7080) {
                            if (
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                              visibility_institution_letter = "";
                            } else {
                              visibility_institution_letter = "";
                            }
                          } else {
                            if (
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                            } else {
                              visibility_institution_letter = "";
                            }
                          }
                        } catch (error) {}
  
                        exists = true;
                        html =
                          html +
                          "<tr  style='" +
                          visibility_institution_letter +
                          "' status='" +
                          jsonData[j]["isActive"] +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td><td><a href='javascript:viewImporterDocuments(" +
                          JSON.stringify(jsonData[j]) +
                          ",this);'>" +
                          jsonData[j]["name"] +
                          "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                        if (formObj.crudEdit == false) {
                        } else {
                          if (isreadOnly == false) {
                            html =
                              html +
                              "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                            html =
                              html +
                              "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                              jsonData[j]["exporterDocument_id"] +
                              "'>";
                            html =
                              html +
                              "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                            html =
                              html +
                              "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] +
                              "'>";
                            html =
                              html +
                              "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                              jsonData[j]["docStatus"]["docStatus_id"] +
                              "'>";
                            html =
                              html +
                              "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf' onchange='controller.saveAttachmentsExporter(" +
                              requiredDocJSON[i]["documentUploadType"][
                                "documentUploadType_id"
                              ] +
                              ", this, " +
                              JSON.stringify(requiredDocJSON[i]) +
                              ")'><br></form></td>";
                          } else {
                            $("#documentupdate").hide();
                            html =
                              html +
                              "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                            html =
                              html +
                              "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                              jsonData[j]["exporterDocument_id"] +
                              "'>";
                            html =
                              html +
                              "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                            html =
                              html +
                              "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                              jsonData[j]["documentUploadType"][
                                "documentUploadType_id"
                              ] +
                              "'>";
                            html =
                              html +
                              "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                              jsonData[j]["docStatus"]["docStatus_id"] +
                              "'>";
                          }
                        }
                        html = html + "</tr>";
                      }
                    }
                    if (exists == false) {
                      try {
                        if (newData.company != null) {
                          if (newData.company.entityType.entityType_id == 7080) {
                            if (
                              requiredDocJSON[i]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                              visibility_institution_letter = "display:none;";
                            } else {
                              visibility_institution_letter = "";
                            }
                          } else {
                            if (
                              requiredDocJSON[i]["documentUploadType"][
                                "documentUploadType_id"
                              ] == 3472
                            ) {
                            } else {
                              visibility_institution_letter = "";
                            }
                          }
                        }
                      } catch (error) {}
                      var isResearcher = responseData[0].isResearcher;
                      if (isResearcher == true) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 7631
                        ) {
                          visibility_institution_letter = "display:block;";
                        }
                        try {
                          $("#isExportConsolidator").prop("disabled", true); //true|disabled will work on all
                          $("#isDryCommodityExporter").prop("disabled", true); //true|disabled will work on all
                          $("#isOwnFarmExporter").prop("disabled", true); //true|disabled will work on all
                        } catch (error) {}
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 7631
                        ) {
                          visibility_institution_letter = "display:none;";
                        }
                        try {
                          $("#isExportConsolidator").prop("disabled", false); //true|disabled will work on all
                          $("#isDryCommodityExporter").prop("disabled", false); //true|disabled will work on all
                          $("#isOwnFarmExporter").prop("disabled", false); //true|disabled will work on all
                        } catch (error) {}
                      }
                      if (isreadOnly == false) {
                        html =
                          html +
                          "<tr style='" +
                          visibility_institution_letter +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td>";
                        html = html + "</td><td>";
                        html =
                          html +
                          "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                        html =
                          html +
                          "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf' onchange='controller.saveAttachmentsExporter(" +
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          ", this, " +
                          JSON.stringify(requiredDocJSON[i]) +
                          ")'><br></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                      } else {
                        html =
                          html +
                          "<tr style='" +
                          visibility_institution_letter +
                          "'><td>" +
                          requiredDocJSON[i]["documentUploadType"]["name"] +
                          "</td>";
                        html = html + "</td><td>";
                        html =
                          html +
                          "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                      }
                    }
                  }
                }
                html = html + "</table>";
                tableHTML.html(html);
                reponseObj(html);
              },
              fail: function () {},
              error: function (XMLHttpRequest, textStatus, errorThrown) {},
            });
          });
          var html = "";
        },
        fail: function (xhr, textStatus) {},
        error: function (xhr, textStatus) {},
      });
    },
  
    loadRequiredDocumentsAgents: function (
      tableID,
      url,
      formType_id,
      reponseObj
    ) {
      controller.getRequiredDocument(formType_id, function (response) {
        var requiredDocJSON = response;
        $.ajax({
          url: url,
          headers: {
            Authorization: userObj.tokenType + " " + userObj.accessToken,
          },
          async: true,
          success: function (data) {
            var visibility;
            var jsonData = data;
            var documentTypesUploaded = [];
            var tableHTML = $(tableID);
  
            var newData = JSON.parse(localStorage.getItem("userObj"));
            html =
              html +
              "<table class='table table-striped'><tr><td>Document Type</td><td>Document</td><td>Status</td><td id='documentupdate'" +
              visibility +
              ">Action</td></tr>";
            for (var i = 0; i < requiredDocJSON.length; i++) {
              var selectVal = requiredDocJSON[i];
              var exists = false;
              var visibility_institution_letter = "";
              var visibility_certificate_of_Incorporation = "";
  
              if (registered == true) {
                for (var j = 0; j < jsonData.length; j++) {
                  if (
                    jsonData[j]["documentUploadType"]["documentUploadType_id"] ==
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ]
                  ) {
                    try {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    } catch (error) {}
  
                    exists = true;
                    html =
                      html +
                      "<tr  style='" +
                      visibility_institution_letter +
                      "' status='" +
                      jsonData[j]["isActive"] +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td><td><a href='javascript:viewImporterDocuments(" +
                      JSON.stringify(jsonData[j]) +
                      ",this);'>" +
                      jsonData[j]["name"] +
                      "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                    if (inprogress == false) {
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-default' onclick='controller.saveAttachmentsAgentEdit(" +
                        requiredDocJSON[i]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        ",this," +
                        JSON.stringify(jsonData[j]) +
                        ");' value='Save New Document'></form></td>";
                    } else {
                      $("#documentupdate").hide();
                      html =
                        html +
                        "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                      html =
                        html +
                        "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                        jsonData[j]["exporterDocument_id"] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                      html =
                        html +
                        "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                        jsonData[j]["documentUploadType"][
                          "documentUploadType_id"
                        ] +
                        "'>";
                      html =
                        html +
                        "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                        jsonData[j]["docStatus"]["docStatus_id"] +
                        "'>";
                    }
                    html = html + "</tr>";
                  }
                }
                if (exists == false) {
                  try {
                    if (newData.company != null) {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "display:none;";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    }
                  } catch (error) {}
                  if (
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] == 7631
                  ) {
                    visibility_institution_letter = "display:none;";
                  } else {
                    visibility_institution_letter = "";
                  }
                  if (isreadOnly == false) {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                    html =
                      html +
                      "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-primary' onclick='controller.saveAttachmentsByAgent(" +
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] +
                      ",this," +
                      JSON.stringify(requiredDocJSON[i]) +
                      ");' value='Save Document'></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                  } else {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                  }
                }
              } else {
                for (var j = 0; j < jsonData.length; j++) {
                  if (
                    jsonData[j]["documentUploadType"]["documentUploadType_id"] ==
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ]
                  ) {
                    try {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    } catch (error) {}
  
                    exists = true;
                    html =
                      html +
                      "<tr  style='" +
                      visibility_institution_letter +
                      "' status='" +
                      jsonData[j]["isActive"] +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td><td><a href='javascript:viewImporterDocuments(" +
                      JSON.stringify(jsonData[j]) +
                      ",this);'>" +
                      jsonData[j]["name"] +
                      "</a></td><td><i style='color:green;' class='fa fa-check'> </i> Uploaded</td>";
                    if (formObj.crudEdit == false) {
                    } else {
                      if (isreadOnly == false) {
                        html =
                          html +
                          "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                          jsonData[j]["exporterDocument_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                          jsonData[j]["docStatus"]["docStatus_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='file' class='doc_file_input btn btn-default' name='file' id='file' placeholder='Update File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-default' onclick='controller.saveAttachmentsEdit(" +
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          ",this," +
                          JSON.stringify(jsonData[j]) +
                          ");' value='Save New Document'></form></td>";
                      } else {
                        $("#documentupdate").hide();
                        html =
                          html +
                          "<td><form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                        html =
                          html +
                          "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id' value='" +
                          jsonData[j]["exporterDocument_id"] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                        html =
                          html +
                          "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id' value='" +
                          jsonData[j]["documentUploadType"][
                            "documentUploadType_id"
                          ] +
                          "'>";
                        html =
                          html +
                          "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id' value='" +
                          jsonData[j]["docStatus"]["docStatus_id"] +
                          "'>";
                      }
                    }
                    html = html + "</tr>";
                  }
                }
                if (exists == false) {
                  try {
                    if (newData.company != null) {
                      if (newData.company.entityType.entityType_id == 7080) {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                          visibility_institution_letter = "display:none;";
                        } else {
                          visibility_institution_letter = "";
                        }
                      } else {
                        if (
                          requiredDocJSON[i]["documentUploadType"][
                            "documentUploadType_id"
                          ] == 3472
                        ) {
                        } else {
                          visibility_institution_letter = "";
                        }
                      }
                    }
                  } catch (error) {}
                  if (
                    requiredDocJSON[i]["documentUploadType"][
                      "documentUploadType_id"
                    ] == 7631
                  ) {
                    visibility_institution_letter = "display:none;";
                  } else {
                    visibility_institution_letter = "";
                  }
                  if (isreadOnly == false) {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                    html =
                      html +
                      "<input type='file' class='doc_file_input btn btn-primary' name='file' id='file' placeholder='File' accept='image/*,application/pdf'><br><input type='button' id='add-document-row' class='upload_btn ui button btn btn-primary' onclick='controller.saveAttachments(" +
                      requiredDocJSON[i]["documentUploadType"][
                        "documentUploadType_id"
                      ] +
                      ",this," +
                      JSON.stringify(requiredDocJSON[i]) +
                      ");' value='Save Document'></form></td><td><i style='color:#3543B3;' class='fa fa-exclamation'></i> Pending Upload</td></tr>";
                  } else {
                    html =
                      html +
                      "<tr style='" +
                      visibility_institution_letter +
                      "'><td>" +
                      requiredDocJSON[i]["documentUploadType"]["name"] +
                      "</td>";
                    html = html + "</td><td>";
                    html =
                      html +
                      "<form class='document-setup_' id='document-setup_' enctype='multipart/form-data'>";
                    html =
                      html +
                      "<input type='hidden' name='primaryDoc_id' class='diplomatDocument_id'>";
                    html =
                      html +
                      "<input type='hidden' name='document_parent_id' class='document_parent_id'>";
                    html =
                      html +
                      "<input type='hidden' name='documentUploadType_id' class='documentUploadType_id'>";
                    html =
                      html +
                      "<input type='hidden' class='docStatus_id documentDocStatus_id' name='documentDocStatus_id' id='documentDocStatus_id'>";
                  }
                }
              }
            }
            html = html + "</table>";
            tableHTML.html(html);
            reponseObj(html);
          },
          fail: function () {},
          error: function (XMLHttpRequest, textStatus, errorThrown) {},
        });
      });
      var html = "";
    },
  
    loadCommodities() {
      if (commoditiesArray.length > 0) {
        var option_ = "";
        option_ += "<option selected value=''>-Select Option-</option>";
        option_ += controller.loadSelect(
          commoditiesArray,
          "products_id",
          "name",
          ""
        );
        $("#products_id").html(option_);
      } else {
        var url_p = serverURL + "product/productApprovedList";
        var pageSize = 200; // Number of records to fetch in each batch
        var currentPage = 0; // The current page number
        var isFetching = false; // Flag to prevent concurrent fetches
        // Hide the select element while loading
        // selectElement.style.display = 'none';
        var option_a = "";
  
        function fetchRecords() {
          if (isFetching) {
            return; // Avoid concurrent fetches
          }
          isFetching = true;
          var url = url_p + "?pageNo=" + currentPage + "&pageSize=" + pageSize;
          controller.getAuthRequest(url, true, function (data, status) {
            isFetching = false;
            if (data.length > 0) {
              commoditiesArray = commoditiesArray.concat(data);
              option_a += "<option selected value=''>-Select Option-</option>";
              option_a += controller.loadSelect(
                commoditiesArray,
                "products_id",
                "name",
                ""
              );
              $("#products_id").html(option_a);
              currentPage++;
              fetchRecords();
            }
          });
        }
  
        // Start fetching records from the first page (page 0)
        fetchRecords();
      }
    },
  
    loadEditCommodities() {
      if (commoditiesArray.length > 0) {
        var option_ = "";
        option_ += controller.loadSelect(
          commoditiesArray,
          "products_id",
          "name",
          ""
        );
        $("#products_id").html(option_);
      } else {
        var url_p = serverURL + "product/productApprovedList";
        var pageSize = 200; // Number of records to fetch in each batch
        var currentPage = 0; // The current page number
        var isFetching = false; // Flag to prevent concurrent fetches
        // Hide the select element while loading
        // selectElement.style.display = 'none';
        function fetchRecords() {
          if (isFetching) {
            return; // Avoid concurrent fetches
          }
          isFetching = true;
          var url = url_p + "?pageNo=" + currentPage + "&pageSize=" + pageSize;
          controller.getAuthRequest(url, true, function (data, status) {
            isFetching = false;
  
            if (data.length > 0) {
              commoditiesArray = commoditiesArray.concat(data);
              var option_a = "";
              option_a += controller.loadSelect(
                commoditiesArray,
                "products_id",
                "name",
                ""
              );
              $("#products_id").html(option_a);
              currentPage++;
              fetchRecords();
            }
          });
        }
  
        // Start fetching records from the first page (page 0)
        fetchRecords();
      }
    },
  
    pesaflowGetByRecordIdAndFormTypeID: function (
      recordID,
      formTypeID,
      success_url
    ) {
      var url =
        serverURL +
        "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
        recordID +
        "&formTypeID=" +
        formTypeID;
      controller.requestWithToken(url, function (data, status) {
        if (data.length > 0) {
          var payment_id = data[0].payment_id;
        } else {
          var tableHTML = $(".pesaflowWindowSection");
          tableHTML.html(
            "Sorry! No Payment has been Created for this record, Please Contact Admin !"
          );
        }
        var url_ =
          serverURL +
          "api/mpesa/requestPesaflow?recordID=" +
          payment_id +
          "&successURL=" +
          callback_url +
          "" +
          success_url;
        controller.requestWithToken(url_, function (data, status) {
          var tableHTML = $(".pesaflowWindowSection");
          tableHTML.html("");
          tableHTML.html("Loading.....Please wait!!!");
          var response = data.data;
          if (response) {
            var tableHTML = $(".pesaflowWindowSection");
            tableHTML.html(response);
          } else {
            var tableHTML = $(".pesaflowWindowSection");
            tableHTML.html(
              "Sorry! No Payment has been created for this record,Please Contact Admin !"
            );
          }
        });
      });
      // controller.checkPesaflowPaymentStatus(recordID, formTypeID);
    },
  
    pesaflowGetByRecordIdAndFormTypeIDBulk: function (
      recordID,
      formTypeID,
      success_url
    ) {
      var url =
        serverURL +
        "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
        recordID +
        "&formTypeID=" +
        formTypeID;
      controller.requestWithToken(url, function (data, status) {
        if (data.length > 0) {
          var payment_id = data[0].payment_id;
        } else {
          var tableHTML = $(".pesaflowWindowSection");
          tableHTML.html(
            "Sorry! No Payment has been Created for this record, Please Contact Admin !"
          );
        }
        var url_ =
          serverURL +
          "api/mpesa/requestPesaflowBulkPayment?recordID=" +
          payment_id +
          "&successURL=" +
          callback_url +
          "" +
          success_url;
        controller.requestWithToken(url_, function (data, status) {
          var tableHTML = $(".pesaflowWindowSection");
          var response = data.data;
          if (response) {
            var tableHTML = $(".pesaflowWindowSection");
            tableHTML.html(response);
          } else {
            var tableHTML = $(".pesaflowWindowSection");
            tableHTML.html(
              "Sorry! No Payment has been created for this record,Please Contact Admin !"
            );
          }
        });
      });
      // controller.checkPesaflowPaymentStatus(recordID, formTypeID);
    },
  
    checkPesaflowPaymentStatus: function (recordID, formTypeID) {
      var fetchCount = 0;
      var maxFetchCount = 6;
      var intervals = setInterval(fetchDataFromEndpoint, 15000); // 15000 ms = 15 seconds
      var isIntervalsCleared = false; // Flag to track if intervals are cleared
  
      function fetchDataFromEndpoint() {
        if (isIntervalsCleared) {
          return; // Don't proceed with further calls if intervals are cleared
        }
        var url =
          serverURL +
          "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
          recordID +
          "&formTypeID=" +
          formTypeID;
        controller.requestWithToken(url, function (response, status) {
          var paymentRecordID = response[0].payment_id;
          var url_ =
            serverURL +
            "api/mpesa/queryPaymentStatuPesaflow?recordID=" +
            paymentRecordID;
          controller.requestWithTokenPOSTPesaflow(
            url_,
            "",
            function (data, status) {
              if (data.status == "pending") {
                fetchCount++;
                if (fetchCount === maxFetchCount) {
                  clearInterval(intervals);
                  isIntervalsCleared = true; // Set the flag to true
                  recordID = null; // Clearing the recordID
                  formTypeID = null; // Clearing the formTypeID
                  // controller.showToastMsg("Sorry! Payment not Received !", "#ff6666");
                }
              } else if (data.status == "settled") {
                fetchCount++;
                if (fetchCount === maxFetchCount) {
                  clearInterval(intervals);
                  isIntervalsCleared = true; // Set the flag to true
                  recordID = null; // Clearing the recordID
                  formTypeID = null; // Clearing the formTypeID
                  // controller.showToastMsg("Sorry! Payment not Received !", "#ff6666");
                }
                clearInterval(intervals);
                // controller.showToastMsg("Payment has been Received Successfully !", "#1a5589");
                // $('.pesaflowWindow').modal('hide');
              } else {
                clearInterval(intervals);
              }
            }
          );
        });
      }
      fetchDataFromEndpoint();
    },
    reloadPage: function (recordID, formTypeID) {
      // Get the current URL
      const currentURL = window.location.href;
  
      // Navigate to the current URL
      window.location.href = currentURL;
    },
  
    getRequiredDocument: function (formType_id, callbackFunc) {
      var listUrl =
        serverURL +
         "requiredDocument/requiredDocumentByFormTypeID?formType_id=322&pageNo=0&pageSize=100";
        // "requiredDocument/requiredDocumentList?pageNo=0&pageSize=1000";
      $.ajax({
        url: listUrl,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        success: function (data) {
          var jsonData = data;
          var arrayIds = [];
          for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i]["formType"]["formType_id"] == formType_id) {
              arrayIds.push(jsonData[i]);
            }
          }
          callbackFunc(arrayIds);
        },
        fail: function () {
          $("#blinder").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $("#blinder").hide();
        },
      });
    },
  
  
    getRequiredDocumentExporter: function (exportid, formType_id, callbackFunc) {
      var listUrl =
        serverURL +
         "requiredDocument/requiredDocumentByFormTypeIDAndExporterID?exporterID="+exportid+"&formType_id=322";
        // "requiredDocument/requiredDocumentList?pageNo=0&pageSize=1000";
      $.ajax({
        url: listUrl,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        success: function (data) {
          var jsonData = data;
          var arrayIds = [];
          for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i]["formType"]["formType_id"] == formType_id) {
              arrayIds.push(jsonData[i]);
            }
          }
          callbackFunc(arrayIds);
        },
        fail: function () {
          $("#blinder").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $("#blinder").hide();
        },
      });
    },
  
    getUploadDocumentsByUser: function (recordID, tableRegisterID, callbackFunc) {
      var recordId = recordID;
      var listUrl =
        serverURL +
        "globalDocument/getGlobalDocumentByTableRegisterAndRecordID?tableRegisterId=" +
        tableRegisterID +
        "&recordId=" +
        recordId;
      $.ajax({
        url: listUrl,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        success: function (data) {
          var jsonData = data;
          var arrayIds = [];
          for (var i = 0; i < jsonData.length; i++) {
            if (jsonData[i]["recordId"] == recordID) {
              arrayIds.push(jsonData[i]);
            }
          }
          callbackFunc(arrayIds);
        },
        fail: function () {
          $("#blinder").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $("#blinder").hide();
        },
      });
    },
    postDocumentWithFormData: function () {
      var data = new FormData();
      var form_data = $("#" + formDocumentID).serializeArray();
      var file_data = $('input[name="file"]')[0].files;
      for (var i = 0; i < file_data.length; i++) {
        data.append("file", file_data[i]);
      }
    },
    previewglobalDocument: function (x, e) {
      $("#myfile").html("");
      $(".modal.fade.document").modal("show");
      for (var key in x) {
        if (x.hasOwnProperty(key)) {
          if (key == "docStatus") {
            $("#" + key + "_name").val(x[key].name);
          }
          $("#" + key).val(x[key]);
        } else {
          $("#" + key).val(x[key]);
        }
      }
      var formObj_ = allFormObj["attachment"];
      var imageURL = serverURL + "globalDocument/downloadFile/" + x;
      $("#myfile").html("Preview Loading... Please Wait");
      controller.getFile(imageURL, function (response) {
        var path = x;
        var ext = path.split(".").pop();
        if (ext == "pdf") {
          PDFObject.embed(response, "#myfile");
        } else {
          $("#myfile").html(
            "<img style='width:100%;height:100%;' src='" + response + "'>"
          );
        }
      });
      $(".delete").show();
    },
    editglobalDocument: function (ID, e, saveobj) {
      document.getElementById("name").value = null;
      document.getElementById("name").value = "";
      document.getElementById("description").value = null;
      document.getElementById("filename").value = null;
      $(".reportAttachmentUpload").modal("show");
      document.getElementById("confirmUploadBtn").style = "display:none;";
      $("#confirmUploadBtn").hide();
      $("#confirmUpdateUploadBtn").hide();
      var name = $("#name").val();
      var description = $("#description").val();
      var file_data = $('input[name="filename"]')[0].files;
      $("input[type=file]").on("change", function () {
        var filelenght = file_data.length;
        if (filelenght === 0) {
        } else {
          $("#confirmUpdateUploadBtn").show();
          document.getElementById("confirmUpdateUploadBtn").innerHTML =
            "Updating Document Please Wait ...";
          document.getElementById("confirmUpdateUploadBtn").disabled = true;
          var url =
            serverURL +
            "globalDocument/updateGlobalDocument?description=" +
            description +
            "&documentUploadType_id=0&globalDocument_id=" +
            ID +
            "&name=" +
            name +
            "&recordId=" +
            saveobj.recordId +
            "&tableRegisterId=" +
            saveobj.tableRegister.tableRegister_id;
          var formData2 = new FormData();
          formData2.append("file", file_data[0]);
          $.ajax({
            url: url,
            headers: {
              Authorization: userObj.tokenType + " " + userObj.accessToken,
            },
            async: true,
            type: "post",
            data: formData2,
            processData: false,
            contentType: false,
            success: function (data, textStatus, xhr) {
              if (xhr.status == 200) {
                $(".reportAttachmentUpload").modal("hide");
                $("#confirmUpdateUploadBtn").hide();
                document.getElementById("name").value = null;
                document.getElementById("description").value = null;
                document.getElementById("filename").value = null;
                controller.showToastMsg(
                  "Document Updated Successfully",
                  "#1a5589"
                );
                document.getElementById("confirmUpdateUploadBtn").innerHTML =
                  "Update Document";
                document.getElementById(
                  "confirmUpdateUploadBtn"
                ).disabled = false;
                controller.refreshCrudTables(this);
              }
            },
            fail: function (xhr, textStatus) {
              controller.showToastMsg("Not uploaded", "#ff6666");
              document.getElementById("confirmUpdateUploadBtn").innerHTML =
                "Update Document";
              document.getElementById("confirmUpdateUploadBtn").disabled = false;
              $(".reportAttachmentUpload").modal("hide");
              controller.refreshCrudTables(this);
            },
            error: function (xhr, textStatus) {
              controller.showToastMsg("Not uploaded", "#ff6666");
              document.getElementById("confirmUpdateUploadBtn").innerHTML =
                "Update Document";
              document.getElementById("confirmUpdateUploadBtn").disabled = false;
              $(".reportAttachmentUpload").modal("hide");
              controller.refreshCrudTables(this);
            },
          });
        }
      });
    },
    urlAddExorter: function () {
      var url = "https://195.202.65.231:8080/kephis-ui/#app/importer_exporter";
      window.open(url);
      return false;
    },
    showExporterModal: function () {
      controller.getexporterdetails();
      $(".modal.fade.addexporter").modal("show");
      $("#exporterbutton").click(function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();
  
        var url = serverURL + "importerExporter/importerExporter";
        var formJson = $("#addexporterform").serializeObject();
        if (
          formJson.name == null ||
          (formJson.name == "" && formJson.email == null) ||
          (email == "" && formJson.tel == null) ||
          (formJson.tel == "" && formJson.postalCode == null) ||
          (formJson.postalCode == "" && formJson.postalAddress == null) ||
          (formJson.postalAddress == "" && formJson.streetName == null) ||
          (formJson.streetName == "" && formJson.town == null) ||
          (formJson.town == "" && formJson.contactPerson == null) ||
          formJson.contactPerson == ""
        ) {
          controller.showToastMsg("Fill all Fields to Proceed", "#ff6666");
        } else {
          document.getElementById("exporterbutton").disabled = true;
          $("#exporterbutton").html("Saving... Please Wait!");
          setTimeout(function () {
            $("#exporterbutton").html("Save Exporter");
            document.getElementById("exporterbutton").disabled = false;
          }, 2500);
          controller.allPostRequest(url, formJson, "", function (data, status) {
            $("#addexporterform").get(0).reset();
            $("#addexporterform")[0].reset();
            $(".modal.fade.addexporter").modal("hide");
            controller.refreshExportersData();
          });
        }
      });
    },
    requiresSamplingModal: function () {
      $(".modal.fade.requiresSampling").modal("show");
      $("#requiresSamplingbtn").click(function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();
        $(".modal.fade.requiresSampling").modal("hide");
      });
    },
    showConModal: function () {
      controller.getconsigneedetailsOnModal();
      $(".modal.fade.addConsignee").modal("show");
      $("#confirmSaveBtnConsgnee").click(function (e) {
        e.stopImmediatePropagation();
        e.stopPropagation();
        e.preventDefault();
        var form = $("#addCons");
        var formData = form.serialize();
        var consigneename = $("#consignee_Name").val();
        var emailaddress = $("#emailAddress").val();
        var tel = $("#telphone").val();
        var postalAddress = $("#postalAddressval").val();
        var streetName = $("#consigneestreetName").val();
        var town = $("#consigneetown").val();
        var country_id = $("#countryid").val();
        var physicalAddress = $("#physicalAddress").val();
        var exporterID = $("#exporter_id").val();
        if (consigneename == null || consigneename == "") {
          controller.showToastMsg("Consignee Name Required", "#ff6666");
        } else if (emailaddress == null || emailaddress == "") {
          controller.showToastMsg("Email Address Required", "#ff6666");
        } else if (tel == null || tel == "") {
          controller.showToastMsg("Telephone Required", "#ff6666");
        } else if (streetName == null || streetName == "") {
          controller.showToastMsg("Street Name Required", "#ff6666");
        } else if (town == null || town == "") {
          controller.showToastMsg("Town Required", "#ff6666");
        } else if (physicalAddress == null || physicalAddress == "") {
          controller.showToastMsg("Physical Address Required", "#ff6666");
        } else {
          controller.addConsigneeDetails(
            consigneename,
            emailaddress,
            tel,
            postalAddress,
            streetName,
            town,
            country_id,
            physicalAddress,
            exporterID
          );
          $(".modal.fade.addConsignee").modal("hide");
        }
      });
    },
    refreshConsigneeData: function () {
      controller.requestWithToken(
        serverURL + "exporter/getExporterByCompanyID",
        function (data1, status) {
          var exporterID = data1[0].exporterID;
          var url =
            serverURL +
            "consignee/getConsigneeByExporter?exporterID=" +
            exporterID;
          var option = "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = $("<option>--Select Option--</option>");
            option +=
              "<option value=" + "" + ">" + "--Select Consignee--" + "</option>";
            $("#consigneeID").html();
            for (var i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].consigneeID +
                ">" +
                data[i].name +
                "</option>";
              $("#consigneeID").html(option);
            }
          });
        }
      );
    },
    refreshExportersData: function () {
      controller.requestWithToken(
        serverURL + "importer/getImporterByCompanyID",
        function (data1, status) {
          var importerID = data1[0].importerID;
          var url =
            serverURL +
            "importerExporter/getImporterExporterByImporterID?importerID=" +
            importerID;
          var option = "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = $("<option>--Select Option--</option>");
            option += '<option value="0">' + "Select Exporter" + "</option>";
            $("#importer_exporterid").html();
            for (var i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].importerExporterID +
                ">" +
                data[i].name +
                "</option>";
              $("#importer_exporterid").html(option);
            }
          });
        }
      );
    },
    previewDocument: function (x, e) {
      $("#myfile").html("");
      $(".modal.fade.document").modal("show");
      for (var key in x) {
        if (x.hasOwnProperty(key)) {
          if (key == "docStatus") {
            $("#" + key + "_name").val(x[key].name);
          }
          $("#" + key).val(x[key]);
        } else {
          $("#" + key).val(x[key]);
        }
      }
      var formObj_ = allFormObj["documents_reports"];
      var selectParentID = controller.getPrimaryValueByName(
        formObj_["parentTable"]
      );
      $("#" + formObj_["parentTable"] + "globalDocument_id").val(
        x[formObj_["parentTable"] + "globalDocument_id"]
      );
      $("#globalDocument_id").val(x.documentUploadType_id);
      var imageURL = formObj_["getDocImageUrl"] + "" + x.name;
      $("#myfile").html("Attachment Preview Loading.. Please Wait");
      controller.getFile(imageURL, function (response) {
        var path = x.path;
        var ext = path.split(".").pop();
        if (ext == "pdf") {
          PDFObject.embed(response, "#myfile");
        } else {
          $("#myfile").html(
            "<img style='width:100%;height:100%;' src='" + response + "'>"
          );
        }
      });
      $(".delete").show();
    },
    previousCommentsDisplay: function (comments, message) {
      if (comments == "") {
        comments = "No previous Comments";
      } else {
      }
      var htmlview = "";
      var tableHTML = $("#previousapproversremarks");
  
      htmlview +=
        '<div class="ibox-body" style="border-top: 0.2em solid #eea236; margin: 16px; width: 100%; border-radius: 8px;">';
      htmlview +=
        "<table class='table table-striped table-bordered table-hover' id='commodities_sectiontbl' cellspacing='0' width='100%'>";
      htmlview += "  <thead>";
      htmlview += "   <tr>";
      htmlview += '  <a class="ui olive ribbon label">Previous Remarks</a>';
      htmlview += "   </tr>";
      htmlview += " </thead>";
      htmlview += "<tbody>";
  
      htmlview =
        htmlview +
        "<table class='table table-bordered'><tr style='background: #3543B3'></tr>";
      htmlview = htmlview + "<tr>";
      htmlview = htmlview + "<td>Remarks: " + comments + "</td>";
      htmlview = htmlview + "</tr>";
      htmlview = htmlview + "<tr>";
      htmlview = htmlview + "<td>Message: " + message + "</td>";
      htmlview = htmlview + "</tr>";
      htmlview = htmlview + "</table>";
      tableHTML.html(htmlview);
    },
    editDocumentRow: function (x, e) {
      $("#myfile").html("");
      $(".modal.fade.document").modal("show");
      for (var key in x) {
        if (x.hasOwnProperty(key)) {
          if (key == "docStatus") {
            $("#" + key + "_name").val(x[key].name);
          }
          $("#" + key).val(x[key]);
        } else {
          $("#" + key).val(x[key]);
        }
      }
      var formObj_ = allFormObj["documents"];
      var selectParentID = controller.getPrimaryValueByName(
        formObj_["parentTable"]
      );
      $("#" + formObj_["parentTable"] + "Document_id").val(
        x[formObj_["parentTable"] + "Document_id"]
      );
      $("#documentUploadType_id").val(x.documentUploadType.documentUploadType_id);
      $("#documentDocStatus_id").val(x.docStatus.docStatus_id);
      var imageURL = formObj_["getDocImageUrl"] + "" + x.name;
      $("#myfile").html("Attachment Preview Loading.. Please Wait");
      controller.getFile(imageURL, function (response) {
        var path = x.path;
        var ext = path.split(".").pop();
        if (ext == "pdf") {
          PDFObject.embed(response, "#myfile");
        } else {
          $("#myfile").html(
            "<img style='width:100%;height:100%;' src='" + response + "'>"
          );
        }
      });
      $(".delete").show();
    },
  
    // previewDocumentsByApprover: function(x, e) {
    //     console.log("x.namex.name", x.name)
    //     $('#myfile').html("");
    //     $('.modal.fade.document').modal('show');
    //     var imageURL = serverURL + "exporterDocument/downloadFile/" + x.name;
    //     $('#myfile').html("Attachment Preview Loading.. Please Wait");
    //     controller.getFile(imageURL,
    //         function(response) {
    //             var path = x.path;
    //             var ext = path.split('.').pop();
    //             if (ext == "pdf") {
    //                 PDFObject.embed(response, "#myfile");
    //             } else {
    //                 $('#myfile').html("<img style='width:100%;height:100%;' src='" + response + "'>");
    //             }
    //         });
    //     $(".delete").show();
    // },
  
    previewDocumentsByApprover: function (x, e) {
      $("#donwloadAttachment").html("");
      $(".modal.fade.document").modal("show");
      for (var key in x) {
        if (x.hasOwnProperty(key)) {
          if (key == "docStatus") {
            $("#" + key + "_name").val(x[key].name);
          }
          $("#" + key).val(x[key]);
        } else {
          $("#" + key).val(x[key]);
        }
      }
      var imageURL = serverURL + "paymentDocument/downloadFile/" + x.name;
      $("#myfile").html("Attachment Preview Loading.. Please Wait");
      controller.getFile(imageURL, function (response) {
        var path = x.path;
        var ext = path.split(".").pop();
        if (ext == "pdf") {
          PDFObject.embed(response, "#myfile");
        } else {
          $("#myfile").html(
            "<img style='width:100% !important;min-height: 500px !important; height:100%;' src='" +
              response +
              "'>"
          );
        }
      });
      $(".delete").show();
    },
  
    addDocument: function (typeId) {
      var identifier_ = $("#" + this.myFormObj.formIdentifierID).val();
      var identifier = this.myFormObj.formName;
      $("#documentUploadType_id").val(typeId);
      $("#" + identifier + "Document_id").val("");
      if (identifier_ == "") {
        alert("First Save Main Record to Proceed");
      } else {
        $(".modal.fade.document").modal("show");
        $("#documentUploadType_id").css("pointer-events", "none");
        $("#myfile").html("");
        $("#file").val("");
      }
    },
    printEntity: function () {
      var url =
        printURL +
        this.myFormObj.formIdentifierID +
        "&formType_ID=" +
        this.myFormObj.formType_id;
      crud.getPDFFile(url, function (response) {
        window.open(response);
      });
    },
    closeModal: function () {
      $(".ui.basic.modal.relation").modal("hide");
      $(".modal.fade.document").modal("hide");
      $(".ui.basic.modal.document-relation").modal("hide");
    },
    clearFields: function () {
      $("#" + this.myFormObj.htmlFormID)[0].reset();
      $(".delete").hide();
      $(".new").removeClass("disabled");
    },
    disableForm: function (status) {
      $(".save").prop("disabled", status);
      $(".delete").prop("disabled", status);
      $(".row-button").prop("disabled", status);
      if (status == true) {
        $("input").css("pointer-events", "none");
        $("select").css("pointer-events", "none");
        $("#file").css("pointer-events", "none");
        $(".upload_btn").prop("disabled", true);
      } else {
        $("input").css("pointer-events", "all");
        $("select").css("pointer-events", "all");
        $("#file").css("pointer-events", "all");
        $(".upload_btn").prop("disabled", false);
        $("#staffRelationship_id").css("pointer-events", "all");
      }
    },
    getFormData: function (formName) {
      var recId = this.windowId;
      var url = this.myFormObj["getRecUrl"] + "?id=" + recId;
      jsonData = {
        id: recId,
      };
      var dates = this.myFormObj.dateFields;
      var formData = JSON.stringify(jsonData);
      controller.getWindowDetails(formData, url, function (output) {
        controller.renderEditForm(output, formName, "", "", function (response) {
          controller.initActions();
        });
      });
    },
    disableForm: function (status) {
      $(".save").prop("disabled", status);
      $(".delete").prop("disabled", status);
      $(".row-button").prop("disabled", status);
      if (status == true) {
        $("input").css("pointer-events", "none");
        $("select").css("pointer-events", "none");
        $("#file").css("pointer-events", "none");
        $(".upload_btn").prop("disabled", true);
      } else {
        $("input").css("pointer-events", "all");
        $("select").css("pointer-events", "all");
        $("#file").css("pointer-events", "all");
        $(".upload_btn").prop("disabled", false);
        $("#staffRelationship_id").css("pointer-events", "all");
      }
    },
    getFormData: function (formName) {
      var recId = this.windowId;
      var url = this.myFormObj["getRecUrl"] + "?id=" + recId;
      jsonData = {
        id: recId,
      };
      var dates = this.myFormObj.dateFields;
      var formData = JSON.stringify(jsonData);
      controller.getWindowDetails(formData, url, function (output) {
        controller.renderEditForm(output, formName);
      });
    },
    getWindowDetails: function (formData, url, handleData) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        contentType: "application/json",
        success: function (data, textStatus, xhr) {
          handleData(data);
          if (xhr.status == 200) {
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created", "#ff6666");
          } else if (xhr.status == 400) {
            controller.showToastMsg("Error! Fields are empty", "#ff6666");
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized", "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden", "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found", "#ff6666");
          } else if (xhr.status == 500) {
            controller.showToastMsg("Error! Duplicate, Record Exists", "#ff6666");
          }
        },
        fail: function (xhr, textStatus) {
          if (xhr.status == 200) {
            controller.showToastMsg("Updated Successfully", "#1a5589");
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
          } else if (xhr.status == 400) {
            var t = xhr.responseText;
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
          } else if (xhr.status == 500) {
            var errorMsg = xhr.responseJSON.message;
            controller.showToastMsg("Error!" + errorMsg, "#ff6666");
          }
          $(".save").removeClass("loading");
        },
        error: function (xhr, textStatus) {
          if (xhr.status == 200) {
            controller.showToastMsg("Updated Successfully", "#1a5589");
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
          } else if (xhr.status == 400) {
            var t = xhr.responseText;
            var obj = JSON.parse(t);
            var errorArr = obj.errors;
            var errorMsg = "";
            for (var i in errorArr) {
              errorMsg = errorMsg + "</br>" + errorArr[i].defaultMessage;
            }
            controller.showToastMsg(
              "Error! Fields are empty" + errorMsg,
              "#ff6666"
            );
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
          } else if (xhr.status == 500) {
            var errorMsg = xhr.responseJSON.message;
            controller.showToastMsg("Error!" + errorMsg, "#ff6666");
          }
          $(".save").removeClass("loading");
        },
      });
    },
    deleteEntity: function (e) {
      var url = "";
      var form = $(e).closest("form");
      var form_identifier = form.attr("form_identifier");
      var primaryName = form_identifier;
      var identifier = form_identifier + "_id";
      var formID = "#" + primaryName + "_form";
      var formJson = $(formID).serializeObject();
      url = primaryName + "_" + deleteUrl;
      var formData = JSON.stringify(formJson);
      crud.saveFormDetails(formData, url, function (output) {});
    },
    saveFormDetails: function (
      formData,
      url,
      handleData,
      buttonClass = "save",
      actionMsg = "Saved Successfully"
    ) {
      $("." + buttonClass).addClass("loading");
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        contentType: "application/json",
        success: function (data, textStatus, xhr) {
          if (xhr.status == 200) {
            controller.showToastMsg(actionMsg, "#1a5589");
            handleData(data);
            try {
              $(".saveRecord").html("Update");
              $(".saveRecord").prop("disabled", false);
            } catch (error) {}
          } else {
            controller.showToastMsg(data, "#1a5589");
          }
          $("." + buttonClass).removeClass("loading");
        },
        fail: function (xhr, textStatus) {
          var errorMSG = "Error";
          try {
            errorMSG = xhr.responseJSON.data;
            JSON.parse(xhr.responseText).data;
          } catch (e) {}
          controller.showToastMsg(errorMSG, "#ff6666");
          handleData("error");
          $(".save").removeClass("loading");
          try {
            setTimeout(() => {
              $(".saveRecord").html("Save");
              $(".saveRecord").prop("disabled", false);
            }, 2000);
          } catch (error) {}
        },
        error: function (xhr, textStatus) {
          var errorMSG = "Error";
          try {
            errorMSG = JSON.parse(xhr.responseText).data;
            JSON.parse(xhr.responseText).data;
          } catch (e) {}
          controller.showToastMsg(errorMSG, "#ff6666");
          handleData("error");
          $(".save").removeClass("loading");
          try {
            setTimeout(() => {
              $(".saveRecord").html("Save");
              $(".saveRecord").prop("disabled", false);
            }, 2000);
          } catch (error) {}
        },
      });
    },
    deactivateUserDetails: function (
      formData,
      url,
      handleData,
      buttonClass = "save",
      actionMsg = "Updated Successfully"
    ) {
      $("." + buttonClass).addClass("loading");
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        contentType: "application/json",
        success: function (data, textStatus, xhr) {
          if (xhr.status == 200) {
            controller.showToastMsg(actionMsg, "#1a5589");
            handleData(data);
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created", "#ff6666");
          } else if (xhr.status == 400) {
            controller.showToastMsg(data.message, "#ff6666");
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized", "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden", "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found", "#ff6666");
          } else if (xhr.status == 500) {
            controller.showToastMsg("Error! Duplicate, Record Exists", "#ff6666");
          }
          $("." + buttonClass).removeClass("loading");
        },
        fail: function (xhr, textStatus) {
          if (xhr.status == 200) {
            controller.showToastMsg(actionMsg, "#1a5589");
            handleData(xhr.responseText);
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
          } else if (xhr.status == 400) {
            var errorData = "";
            try {
              var errorData = xhr.responseJSON.data;
            } catch (e) {}
            controller.showToastMsg("Error 400! - " + errorData, "#ff6666");
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
          } else if (xhr.status == 500) {
            var errorMsg = xhr.responseJSON.message;
            try {
              var error = errorMsg.substring(1, 9);
              if (errorMsg == "could not") {
                controller.showToastMsg(
                  "Error! Duplicate record exists" + errorMsg,
                  "#ff6666"
                );
              } else {
                controller.showToastMsg("Error!" + errorMsg, "#ff6666");
              }
            } catch (e) {}
          }
          $(".save").removeClass("loading");
        },
        error: function (xhr, textStatus) {
          if (xhr.status == 200) {
            handleData(xhr.responseText);
            controller.showToastMsg(actionMsg, "#1a5589");
          } else if (xhr.status == 201) {
            controller.showToastMsg("Error! Created" + errorMsg, "#ff6666");
          } else if (xhr.status == 400) {
            var errorData = "";
            try {
              var errorData = xhr.responseJSON.data;
            } catch (e) {}
            controller.showToastMsg("Error 400! " + errorData, "#ff6666");
          } else if (xhr.status == 401) {
            controller.showToastMsg("Error! Unauthorized" + errorMsg, "#ff6666");
          } else if (xhr.status == 403) {
            controller.showToastMsg("Error! Forbidden" + errorMsg, "#ff6666");
          } else if (xhr.status == 404) {
            controller.showToastMsg("Error! Not found" + errorMsg, "#ff6666");
          } else if (xhr.status == 500) {
            var errorMsg = xhr.responseJSON.message;
            controller.showToastMsg("Error!" + errorMsg, "#ff6666");
          }
          $(".save").removeClass("loading");
        },
      });
    },
    show_progress: function () {
      // $(".xcrud-overlay").show();
      // controller.displayLoading();
    },
    hide_progress: function () {
      $(".xcrud-overlay").hide();
    },
    editDocument: function (x) {
      $("#myfile").html("");
      $(".modal.fade.document").modal("show");
      $("#diplomatDocument_id").val(x[formIdentifierDocumentID]);
      $("#documentUploadType_id").val(x.documentUploadType.documentUploadType_id);
      $("#documentDocStatus_id").val(x.docStatus.docStatus_id);
      var imageURL = getDocImageUrl + "" + x.name;
      $("#myfile").html("Attachment Preview Loading.. Please Wait");
      controller.getFile(imageURL, function (response) {
        var path = x.path;
        var ext = path.split(".").pop();
        if (ext == "pdf") {
          PDFObject.embed(response, "#myfile");
        } else {
          $("#myfile").html(
            "<img style='width:100%;height:100%;' src='" + response + "'>"
          );
        }
      });
      $(".delete").show();
    },
    editRow: function (x, e, formName = "") {
      isreadOnly = false;
  
      isCrudAttachmentview = true;
      $(".btnvalidatsr14_holder").hide();
      try {
        var myevent = document.getElementById("attachdocumentglobal");
        myevent.style.display = "block";
        $("#attachdocumentglobal").show();
        show(document.querySelector("#attachdocumentglobal"));
      } catch (error) {}
      if (formName != "") {
        formName = formName;
      } else {
        formName = $(e).attr("form-name");
      }
      var exclusionTab = [];
      try {
        $("#listings_" + formName).hide();
      } catch (error) {}
      try {
        $(".crud_section_lines").hide();
      } catch (error) {}
      if (
        formName == "quarantineRequesteProduct" ||
        formName == "onetime_export"
      ) {
        setTimeout(function () {
          $(".save").hide();
        }, 400);
      }
      if (formName == "petRiskAnalysisRequest" || formName == "consignee") {
        var url = serverURL + "countries/countryList?pageNo=0&pageSize=100000";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.length > 0) {
            var option = "";
            option +=
              "<option selected value=" +
              x.country.country_id +
              ">" +
              x.country.name +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].country_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            }
            $("#country_id").html();
            $("#country_id").html(option);
          } else {
            option += "<option>-Select Option-</option>";
            $("#country_id").html(option);
          }
        });
      }
  
      if (formName == "exporterLowRiskCommodity") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            var length = data1.length;
            var exporterID = data1[0].exporterID;
            var url =
              serverURL +
              "exporterProduct/getExporterProductByExporter?exporterID=" +
              exporterID;
            controller.requestWithToken(url, function (data1, status) {
              var option = "";
              option += "<option selected>-Select Commodity-</option>";
              if (data1.length > 0) {
                for (let i = 0; i < data1.length; i++) {
                  option +=
                    "<option value=" +
                    data1[i].products.products_id +
                    ">" +
                    data1[i].products.name +
                    "</option>";
                }
              }
              $("#products_id").html();
              $("#products_id").html(option);
            });
          }
        );
      }
  
      if (formName == "exporterConsignment") {
        try {
          controller.requestWithToken(
            serverURL + "api/validateuser",
            function (data1, status) {
              var company_id = data1.company.company_id;
              controller.requestWithToken(
                serverURL + "agent/getAgentByCompany",
                function (data1, status) {
                  if (data1.length > 1) {
                    var agents_id = data1[0].agents_id;
  
                    var url =
                      serverURL +
                      "agentManagement/getByAgent?agentID=" +
                      agents_id; //consignee/getConsigneeByExporter?exporterID=
                    controller.setUpObjInitializeSpecificOneWithCallBack(
                      url,
                      "company",
                      function (data) {
                        if (data.length > 0) {
                          var option = "";
                          option +=
                            "<option selected value=" +
                            x.company.company_id +
                            ">" +
                            x.company.name +
                            "</option>";
                          if (data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                              option +=
                                "<option value=" +
                                data[i].company.company_id +
                                ">" +
                                data[i].company.name +
                                "</option>";
                            }
                          }
                          $("#company_id").html();
                          $("#company_id").html(option);
                        } else {
                          option += "<option>-Select Option-</option>";
                          $("#company_id").html(option);
                        }
                      }
                    );
                  } else {
                  }
                }
              );
            }
          );
  
          var url = serverURL + "countries/countryList?pageNo=0&pageSize=100000";
          controller.getAuthRequest(url, true, function (data, status) {
            if (data.length > 0) {
              var option = "";
              option +=
                "<option selected value=" +
                x.countryOfOrigin.country_id +
                ">" +
                x.countryOfOrigin.name +
                "</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              }
              $("#countryOfOrigin_id").html();
              $("#countryOfOrigin_id").html(option);
            } else {
              option += "<option>-Select Option-</option>";
              $("#countryOfOrigin_id").html(option);
            }
          });
  
          var url2 =
            serverURL +
            "consignee/getConsigneeByCompany?companyID=" +
            x.company.company_id +
            "&pageNo=0&pageSize=100";
          controller.getAuthRequest(url2, true, function (data, status) {
            var option = "";
            if (data.length > 0) {
              option +=
                "<option selected value=" +
                x.consignee.consigneeID +
                ">" +
                x.consignee.name +
                "</option>";
              $("#consigneeID").html();
              for (var i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].consigneeID +
                  ">" +
                  data[i].name +
                  "</option>";
                $("#consigneeID").html(option);
              }
            } else {
              option +=
                "<option selected value=" +
                "" +
                ">" +
                "--No Consignee found--" +
                "</option>";
            }
          });
        } catch (error) {}
      }
  
      if (formName == "onetime_export") {
        crudsaveLinesInspection = false;
        crudOnetimeExportImportLineeSaveInspection = true;
        crudeImportConsLineSaveInspection = false;
        crudexportLineSaveInspection = false;
      }
      if (formName == "onetime_import") {
        crudsaveLinesInspection = false;
        crudOnetimeExportImportLineeSaveInspection = false;
        crudeImportConsLineSaveInspection = true;
        crudexportLineSaveInspection = false;
      }
      if (formName == "exporterFarm") {
        controller.getSelectedSubCountyByID(
          x.county.county_id,
          x.subCounty.subcounty_id,
          "exporterFarm"
        );
        controller.getselectedwardBySubCounty(
          x.subCounty.subcounty_id,
          "exporterFarm",
          x.ward.ward_id
        );
        controller.getselectedCountry();
      }
  
      if (formName == "exporterLowRiskCommodity") {
        var option = "";
        option += "<option>-Select Option-</option>";
        $("#products_id").html(option);
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            var exporterID = data1[0].exporterID;
            var url =
              serverURL +
              "exporterProduct/getExporterProductByExporter?exporterID=" +
              exporterID;
            controller.getAuthRequest(url, true, function (data, status) {
              var option = "";
              if (data.length > 0) {
                option +=
                  "<option selected value=" +
                  x.products.products_id +
                  ">" +
                  x.products.name +
                  "</option>";
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].products.products_id +
                    ">" +
                    data[i].products.name +
                    "</option>";
                  $("#products_id").html(option);
                }
              }
              var option4 = "";
              option4 +=
                "<option selected value=" +
                x.country.country_id +
                ">" +
                x.country.name +
                "</option>";
              $("#country_id").html(option4);
            });
          }
        );
      }
      if (
        formName == "exporterFirm" ||
        formName == "importerExporter" ||
        formName == "evaluation_application"
      ) {
        var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option selected value=" +
                x.country.country_id +
                ">" +
                x.country.name +
                "</option>";
              option +=
                "<option value=" +
                data[i].country_id +
                ">" +
                data[i].name +
                "</option>";
              $("#country_id").html(option);
            }
          }
        });
      }
      if (formName == "consignmentInspectionRequest") {
        controller.requestWithToken(
          serverURL + "importer/getImporterByCompanyID",
          function (data1, status) {
            var importerID = data1[0].importerID;
            var url =
              serverURL +
              "pipApplication/getApprovedPIPApplicationByImporter?importerID=" +
              importerID;
            controller.getAuthRequest(url, true, function (data, status) {
              var option = "";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].pipApplication.pipApplicationID +
                    ">" +
                    data[i].pipApplication.pipApplicationID +
                    "</option>";
                  $("#pip_application_id").html(option);
                }
              }
            });
          }
        );
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        var option = "";
        option +=
          "<option selected value=" +
          x.products.products_id +
          ">" +
          x.products.name +
          "</option>";
        $("#products_id").html(option);
      }
      if (formName == "pipApplicationVarietyRequest") {
        var importpurpose = x.importPurpose.importPurposeID;
        var country = x.pipApplicationRequest.countryOfOrigin.country_id;
        var url =
          serverURL +
          "importRequirement/findProductByImportRequiremntCountryAndImportPupose?countryId=" +
          country +
          "&importPurposeId=" +
          importpurpose +
          "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.length > 0) {
            var option = "";
            option +=
              "<option selected value=" +
              x.product.products_id +
              ">" +
              x.product.name +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].products_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            }
            $("#products_id").html();
            $("#products_id").html(option);
          } else {
            option += "<option>-Select Option-</option>";
            $("#products_id").html(option);
          }
        });
        var option2 = "";
        option2 +=
          "<option selected value=" +
          x.importCondition.import_condition_id +
          ">" +
          x.importCondition.name +
          "</option>";
        $("#importConditionID").html(option2);
        var option3 = "";
        option3 +=
          "<option selected value=" +
          x.productFamily.product_family_id +
          ">" +
          x.productFamily.name +
          "</option>";
        $("#productFamilyId").html(option3);
        var option4 = "";
        option4 +=
          "<option selected value=" +
          x.productCategory.product_category_id +
          ">" +
          x.productCategory.name +
          "</option>";
        $("#product_category_id").html(option4);
        var option5 = "";
        option5 +=
          "<option selected value=" +
          x.packagingType.packaging_type_id +
          ">" +
          x.packagingType.name +
          "</option>";
        $("#packagingTypeID").html(option5);
        var option6 = "";
        option6 +=
          "<option selected value=" +
          x.siUnit.sIUnit_id +
          ">" +
          x.siUnit.name +
          "</option>";
        $("#siUnitID").html(option6);
        var option9 = "";
        option9 +=
          "<option selected value=" +
          x.productForm.product_form_id +
          ">" +
          x.productForm.name +
          "</option>";
        $("#productFormID").html(option9);
      }
      if (formName == "pipApplicationVarietyRequest") {
        var products_id = x.product.products_id;
        controller.getBotanicalNameVariety(products_id);
      }
      if (formName == "exporterConsignment") {
        setTimeout(function () {
          $(".buttonAddConsignee_holder").show();
          $(".btnvalidatsr14_holder").show();
          $(".btnucrvalidations_holder").show();
        }, 500);
      }
      if (
        formName == "tradingBlock" ||
        formName == "pip_applicationrequest" ||
        formName == "quarantineFacility" ||
        formName == "exporter" ||
        formName == "agents"
      ) {
        setTimeout(function () {
          $(".save").hide();
        }, 400);
      }
      if (formName == "exporterConsignment") {
        setTimeout(function () {
          $(".save").hide();
        }, 300);
      }
      if (formName == "facilitycommodities") {
        setTimeout(function () {
          $(".quarantineFacility_id_holder").hide();
        }, 100);
      }
      if (
        formName == "exporterConsignment" ||
        formName == "exporter" ||
        formName == "importer" ||
        formName == "pip_application" ||
        formName == "printout_replacement" ||
        formName == "quarantine_facility_product_request"
      ) {
        setTimeout(function () {
          $("#uploadDocumentReportsdiv").css("visibility", "visible");
          $("#uploadDocumentReportsdiv").css("display", "block");
          $("#updatecolumnVisisbility").css("visibility", "visible");
          $("#updatecolumnVisisbility").css("display", "block");
          $("#btnupdatedocuments").css("visibility", "visible");
          $("#btnupdatedocuments").css("display", "block");
        }, 3000);
      } else {
        setTimeout(function () {
          $("#uploadDocumentReportsdiv").css("visibility", "hidden");
          $("#uploadDocumentReportsdiv").css("display", "none");
          $("#updatecolumnVisisbility").css("visibility", "hidden");
          $("#updatecolumnVisisbility").css("display", "none");
          $("#btnupdatedocuments").css("visibility", "hidden");
          $("#btnupdatedocuments").css("display", "none");
        }, 3000);
      }
      if (formName == "users") {
        try {
          controller.requestWithToken(
            serverURL + "api/validateuser",
            function (data1, status) {
              var company_id = data1.company.company_id;
              var link = formObj2.listUrl;
              link = link.split("=")[0];
              link = link + "=" + company_id;
              controller.refreshCrudTables("userlocationdetails");
              controller.renderCRUDForm(
                "crud_section_2",
                formObj2,
                function () {}
              );
            }
          );
        } catch (error) {}
      }
      if (formName == "consignmentInspectionRequest") {
        controller.requestWithToken(
          serverURL + "importer/getImporterByCompanyID",
          function (data1, status) {
            var importerID = data1[0].importerID;
            var url =
              serverURL +
              "pipApplication/getApprovedPIPApplicationByImporter?importerID=" +
              importerID;
            controller.setUpObjInitializeSpecificOne(url, "pipApplication");
          }
        );
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            if (
              data1[0].isResearcher == "true" ||
              data1[0].isResearcher == true
            ) {
              $(".firms_holder").hide();
              $(".farms_holder").hide();
              $(".sourcesResearcher_holder").show();
              $("#sourcesResearcher").val(data1[0].researchInstitute.name);
              document
                .getElementById("firms")
                .setAttribute("data-parsley-required", "false");
              document
                .getElementById("farms")
                .setAttribute("data-parsley-required", "false");
            } else {
              $(".firms_holder").show();
              $(".farms_holder").show();
              $(".sourcesResearcher_holder").hide();
              $("#sourcesResearcher").val("None");
            }
            var exporterID = data1[0].exporterID;
            if (
              data1[0].isExportConsolidator == "true" ||
              data1[0].isExportConsolidator == true
            ) {
              $(".farms_holder").hide();
            } else {
            }
          }
        );
      }
      if (formName == "pipApplicationVarietyRequest") {
        try {
          var expportervarietyid =
            allFormObj["selected"]["pipApplicationRequestID"];
          if (expportervarietyid == undefined) {
            $("#pipApplicationVarietyRequest_form #pipApplicationRequestID").val(
              allFormObj["parent_selected"]["pipApplicationRequest"][
                "pipApplicationRequestID"
              ]
            );
          } else {
            $("#pipApplicationVarietyRequest_form #country_of_origin_id").val(
              allFormObj["selected"]["countryOfOrigin"]["country_id"]
            );
            $("#pipApplicationVarietyRequest_form #pipApplicationRequestID").val(
              allFormObj["selected"]["pipApplicationRequestID"]
            );
          }
        } catch (error) {}
      }
  
      if (formName == "exporterFirm") {
        if (!x.newfarm) {
          exclusionTab.push("OwnFarms");
        }
      }
      if (formName == "assignedPhytoInspections") {
        if (!x.farms) {
          exclusionTab.push("Inspections2");
        }
      }
      if (formName == "users") {
        $("#phoneNo").attr("data-parsley-maxlength", "10");
      }
      if (
        formName == "exporter" ||
        formName == "assignInspection" ||
        formName == "assignedInspection"
      ) {
        if (!x.isOwnFarmExporter) {
          exclusionTab.push("OwnFarms");
          exclusionTab.push("OwnFarmsDestination");
        }
        if (!x.isExportConsolidator) {
          exclusionTab.push("Firms");
        }
        if (!x.isDryCommodityExporter) {
          exclusionTab.push("LowRiskCommoditiesRegistration");
        }
      }
      if (allFormObj["pipApplicationVariety"]) {
        allFormObj["pipApplicationVariety"]["crudAdd"] = true;
        allFormObj["pipApplicationVariety"]["crudEdit"] = true;
      }
      if (allFormObj["consolidatedPhyto"]) {
        allFormObj["exporterConsignmentVarietyDetailsconsignmnet"][
          "crudAdd"
        ] = false;
        allFormObj["consolidatedExportConsignmentLines"]["crudEdit"] = true;
        allFormObj["consolidatedExportConsignmentLines"]["crudAdd"] = true;
      }
      if (allFormObj["tradingBlock"]) {
        allFormObj["tradingcountry"]["crudAdd"] = true;
        allFormObj["tradingcountry"]["crudEdit"] = true;
      }
      if (allFormObj["quarantineFacility"]) {
        allFormObj["facilitycommodities"]["crudAdd"] = true;
      }
      // if (allFormObj['onetime_export_variety_details']) {
      //     allFormObj['onetime_export_variety_details']['crudAdd'] = true;
      //     allFormObj['onetime_export_variety_details']['crudEdit'] = true;
      // }
      if (allFormObj["onetime_import_variety_details"]) {
        allFormObj["onetime_import_variety_details"]["crudAdd"] = true;
        allFormObj["onetime_import_variety_details"]["crudEdit"] = true;
      }
      if (allFormObj["consolidatedPhyto"]) {
        allFormObj["exporterConsignmentVarietyDetailsconsignmnet"][
          "crudAdd"
        ] = false;
      }
      if (allFormObj["importer"]) {
        allFormObj["documents"]["crudAdd"] = false;
        allFormObj["documents"]["crudEdit"] = false;
      }
      if (allFormObj["clients"]) {
        allFormObj["staffProfile"]["crudAdd"] = true;
        allFormObj["staffProfile"]["crudEdit"] = true;
      }
      if (allFormObj["pip_applicationrequest"]) {
        allFormObj["pipApplicationVarietyRequest"]["crudAdd"] = true;
        allFormObj["pipApplicationVarietyRequest"]["crudEdit"] = true;
      }
      if (allFormObj["exporter"]) {
        allFormObj["exporterFarm"]["crudAdd"] = true;
        allFormObj["exporterFarm"]["crudEdit"] = true;
        allFormObj["exporterFirm"]["crudAdd"] = true;
        allFormObj["exporterFirm"]["crudEdit"] = true;
        allFormObj["exporterLowRiskCommodity"]["crudAdd"] = true;
        allFormObj["exporterLowRiskCommodity"]["crudEdit"] = true;
        allFormObj["exporterProduct"]["crudAdd"] = true;
        allFormObj["exporterProduct"]["crudEdit"] = true;
      }
      if (allFormObj["exporterFarm"]) {
        allFormObj["exporterFarmproducts"]["crudAdd"] = true;
        allFormObj["exporterFarmproducts"]["crudEdit"] = true;
      }
      if (allFormObj["split_export_consignment"]) {
        allFormObj["exporterConsignment"]["crudAdd"] = false;
      }
      if (formName == "lab_analysis_technician") {
      }
      if (
        formName == "wfWorkflow" ||
        formName == "wFDepartment" ||
        formName == "wFDepartment" ||
        formName == "wFNode" ||
        formName == "wFTransition"
      ) {
        controller.renderEditFormTabsEnabled(
          x,
          formName,
          true,
          exclusionTab,
          function (response) {
            var formHTML = response;
            $("#listings_edit_" + formName).show();
            $("#listings_edit_" + formName)
              .html(formHTML)
              .promise()
              .done(function () {
                controller.initActions();
                controller.initializeTabs();
                controller.initializeDateFields(formName);
                controller.validateOnView_Edit(x, formName);
                var currentObj = allFormObj[formName];
                tab = currentObj.Mytabs;
                tabLength = tab.length;
                if (tabLength > 0) {
                  var cnt = 0;
                  $("*[data-tab]").each(function () {
                    cnt++;
                    var val = $(this).attr("data-tab");
                    if (cnt > 1) {
                      setTimeout(function () {
                        var t = cnt - 1;
                        try {
                          controller.manualTabClick(val, cnt);
                        } catch (e) {}
                      }, 1500);
                    }
                  });
                }
              });
          }
        );
      } else {
        controller.renderEditForm(
          x,
          formName,
          true,
          exclusionTab,
          function (response) {
            var formHTML = response;
            $("#listings_edit_" + formName).show();
            $("#listings_edit_" + formName)
              .html(formHTML)
              .promise()
              .done(function () {
                controller.initActions();
                controller.initializeTabs();
                controller.initializeDateFields(formName);
                controller.initializeExporterRegistrationTabs();
                controller.validateOnView_Edit(x, formName);
                try {
                  var currentObj = allFormObj[formName];
                  tab = currentObj.Mytabs;
                  tabLength = tab.length;
                  if (tabLength > 0) {
                    var cnt = 0;
                    $("*[data-tab]").each(function () {
                      cnt++;
                      var val = $(this).attr("data-tab");
                      if (cnt > 1) {
                        setTimeout(function () {
                          var t = cnt - 1;
                          try {
                            controller.manualTabClick(val, cnt);
                          } catch (e) {}
                        }, 500);
                      }
                    });
                  }
                } catch (error) {}
              });
          }
        );
      }
    },
    initializeVerticalForm: function (formName) {
      var currentObj = allFormObj[formName];
      try {
        if (currentObj.url_id != "tab") {
          var tab_this = $("li.active.item");
          var tabPos = tab_this.attr("data-tab");
          allFormObj["tab_" + formName] = obj;
          try {
            allFormObj["parent_selected"] = obj;
            allFormObj["selected"] = obj;
            allFormObj["parent_selected"] = obj;
          } catch (e) {}
        } else {
          try {
            allFormObj["selected"] = "";
            allFormObj["selected"] = obj;
            allFormObj["parent_selected"] = obj;
          } catch (e) {}
        }
      } catch (e) {}
      var tab = "";
      try {
        tab = currentObj.Mytabs;
      } catch (e) {}
      var tabLength = 0;
      try {
        tabLength = tab.length;
      } catch (e) {}
      if (tabLength > 0) {
      }
    },
    validateOnAdd: function (formName) {
      $(".viewCertBtn_holder").hide();
      $(".shippingOrderNumber_holder").hide();
      $(".AttacvalidateOnAddhments_tab_link").hide();
      $(".documents_reports_tab_link").hide();
      if (formName == "onetime_import_variety_details") {
        $(".containerType_holder").hide();
      }
      if (formName == "clients") {
        controller.getuserRoles();
      }
      if (formName == "onetime_export_variety_details") {
        var url = serverURL + "product/productList?pageNo=0&pageSize=10000";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          option += "<option selected disabled >--Select Commodity--</option>";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].products_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            controller.showToastMsg(
              "Selected Country Of Destination Has No Export Requirements",
              "#ff6666"
            );
          }
          $("#productsID").html();
          $("#productsID").html(option);
        });
      }
      if (formName == "consignmentInspectionRequest") {
        controller.requestWithToken(
          serverURL + "importer/getImporterByCompanyID",
          function (data1, status) {
            var importerID = data1[0].importerID;
            var url =
              serverURL +
              "pipApplication/getApprovedPIPApplicationByImporter?importerID=" +
              importerID;
            controller.setUpObjInitializeSpecificOne(url, "pipApplication");
          }
        );
      }
      if (formName == "exporterProduct") {
        $(".exporterLicenseNo_holder").hide();
        $(".licensingBodyID_holder").hide();
      }
      if (formName == "tradingcountry") {
        var tradingcountry = localStorage.getItem("tradingcountry");
        $("#trading_block_id").val(tradingcountry);
      }
      if (formName == "exporterFarmproducts") {
        var epid = localStorage.getItem("exporterFarmId");
        $("#exporterFarmId").val(epid);
      }
      if (formName == "exporterFarm") {
        var select = $("#no_of_seasons");
        var newOptions = {
          "": "-Select Number of Seasons-",
          1: "1",
          2: "2",
          3: "3",
          4: "4",
          5: "5",
          6: "6",
          7: "7",
          8: "8",
          9: "9",
          10: "10",
          11: "11",
          12: "12",
          Continous: "Continous",
          "N/A": "N/A",
        };
        $.each(newOptions, function (text, key) {
          var option = new Option(key, text);
          select.append($(option));
        });
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        $(".netWeight_holder").hide();
        $(".grossWeight_holder").hide();
        try {
          var countryid =
            allFormObj["selected"]["countryOfDestination"]["country_id"];
          var url =
            serverURL +
            "exportRequirement/findProductByExportRequiremntCountry?countryId=" +
            countryid +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = "";
            option += "<option selected disabled >--Select Commodity--</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].products_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            } else {
            }
            $("#products_id").html();
            $("#products_id").html(option);
          });
        } catch (error) {}
        try {
          var countryoforigin =
            allFormObj["selected"]["countryOfOrigin"]["country_id"];
          if (countryoforigin == 1) {
            setTimeout(function () {
              $(".firms_holder").show();
              $(".farms_holder").show();
            }, 500);
          } else {
            setTimeout(function () {
              $(".firms_holder").hide();
              $(".farms_holder").hide();
            }, 500);
          }
        } catch (error) {
          var countryoforigin =
            allFormObj["selected"]["exporterConsignment"]["countryOfOrigin"][
              "country_id"
            ];
          if (countryoforigin == 1) {
            setTimeout(function () {
              $(".firms_holder").show();
              $(".farms_holder").show();
            }, 500);
          } else {
            setTimeout(function () {
              $(".firms_holder").hide();
              $(".farms_holder").hide();
            }, 500);
          }
        }
        try {
          var countryoforigin =
            allFormObj["selected"]["exporterConsignment"]["countryOfOrigin"][
              "country_id"
            ];
          if (countryoforigin == 1) {
            $(".firms_holder").show();
            $(".farms_holder").show();
          } else {
            $(".firms_holder").hide();
            $(".farms_holder").hide();
          }
        } catch (error) {}
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        $(".netWeight_holder").hide();
        $(".grossWeight_holder").hide();
        try {
          var countryid =
            allFormObj["selected"]["exporterConsignment"]["countryOfDestination"][
              "country_id"
            ];
          var url =
            serverURL +
            "exportRequirement/findProductByExportRequiremntCountry?countryId=" +
            countryid +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = "";
            option += "<option selected disabled >--Select Commodity--</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].products_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            } else {
            }
            $("#products_id").html();
            $("#products_id").html(option);
          });
        } catch (error) {}
      }
      if (formName == "exporter") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            if (
              data1[0].isResearcher == "true" ||
              data1[0].isResearcher == true
            ) {
              $(".isOwnFarmExporter_holder").hide();
              $(".isExportConsolidator_holder").hide();
              $(".isDryCommodityExporter_holder").hide();
              $(".isResearcher_holder").hide();
            } else {
              $(".isOwnFarmExporter_holder").show();
              $(".isExportConsolidator_holder").show();
              $(".isDryCommodityExporter_holder").show();
              $(".isResearcher_holder").show();
            }
            if (
              data1[0].isOwnFarmExporter == "true" ||
              data1[0].isOwnFarmExporter == true
            ) {
              $(".OwnFarms_tab_link").show();
              $(".OwnFarmsDestination_tab_link").show();
              $(".ExporterDetails_tab_link").show();
              $(".isResearcher_holder").hide();
              $(".isExportConsolidator_holder").hide();
              document.getElementById("isExportConsolidator").value == "false";
            } else {
              $(".ExporterDetails_tab_link").hide();
              $(".OwnFarms_tab_link").hide();
              $(".OwnFarmsDestination_tab_link").hide();
              $(".isExportConsolidator_holder").show();
              $(".isResearcher_holder").show();
            }
            if (
              data1[0].isExportConsolidator == "true" ||
              data1[0].isExportConsolidator == true
            ) {
              $(".Firms_tab_link").hide();
              $(".OwnFarms_tab_link").hide();
              $(".isOwnFarmExporter_holder").hide();
              $(".OwnFarmsDestination_tab_link").hide();
              $(".isResearcher_holder").hide();
            } else {
              $(".isOwnFarmExporter_holder").show();
              $(".isResearcher_holder").show();
            }
            if (
              data1[0].isDryCommodityExporter == "true" ||
              data1[0].isDryCommodityExporter == true
            ) {
              $(".LowRiskCommoditiesRegistration_tab_link").show();
            } else {
              $(".LowRiskCommoditiesRegistration_tab_link").hide();
            }
          }
        );
      }
      if (formName == "exporterLowRiskCommodity") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            document.getElementById("print-btn").style =
              "display:block; margin-left: 3px";
            var exporterID = data1[0].exporterID;
            var length = data1.length;
            if (length > 0) {
              document.getElementById("print-btn").style =
                "display:none;margin-left: 3px";
            } else if (length < 0) {
              document.getElementById("print-btn").style =
                "display:block;margin-left: 3px";
            }
            var url =
              serverURL +
              "exporterProduct/getExporterProductByExporter?exporterID=" +
              exporterID;
            controller.setUpObjInitializeSpecificOne(
              url,
              "productss",
              function () {}
            );
          }
        );
      }
      if (formName == "exporterLowRiskCommodity") {
        var select = $("#capacity");
        var newOptions = {
          "Small (less than 3000m3": "Small (less than 3000m3",
          "Medium (3000m3 -5000m3)": "Medium (3000m3 -5000m3)",
          "Large (more than 5000m3)": "Large (more than 5000m3)",
        };
        $.each(newOptions, function (text, key) {
          var option = new Option(key, text);
          select.append($(option));
        });
      }
      if (formName == "onetime_import") {
        $(".fumgCertificateNo_holder").hide();
        if ($("#fumigation").val() == true) {
          $(".fumgCertificateNo_holder").show();
        } else {
          $(".fumgCertificateNo_holder").hide();
        }
      }
      if (formName == "onetime_import") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyanceMeansID").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyanceMeansID").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName").show();
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 204) {
          $(".vesselName_holder").show();
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if (formName == "consignmentInspectionRequest") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyance_means_id").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyance_means_id").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#manifestNo").val("");
          $(".vesselName_holder").show();
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 204) {
          $(".vesselName_holder").show();
          $(".shippingOrderNumber_holder").show();
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
          document
            .getElementById("shippingOrderNumber")
            .setAttribute("data-parsley-required", "false");
        } else {
          $(".vesselName_holder").show();
          $(".shippingOrderNumber_holder").show();
        }
      }
      if (formName == "pip_application" || formName == "pip_applicationrequest") {
        try {
          controller.requestWithToken(
            serverURL + "importer/getImporterByCompanyID",
            function (data1, status) {
              try {
                var importerID = data1[0].importerID;
                var url =
                  serverURL +
                  "importerExporter/getImporterExporterByImporterID?importerID=" +
                  importerID;
                var option = "";
                controller.getAuthRequest(url, true, function (data, status) {
                  if (data.length > 0) {
                    option += "<option value='0'>Select Exporter</option>";
                    for (let i = 0; i < data.length; i++) {
                      option +=
                        "<option value=" +
                        data[i].importerExporterID +
                        ">" +
                        data[i].name +
                        "</option>";
                    }
                  } else {
                  }
                  $("#importer_exporterid").html();
                  $("#importer_exporterid").html(option);
                });
              } catch (error) {}
            }
          );
        } catch (error) {}
      }
      if (formName == "exporterConsignment") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            try {
              var exporterID = data1[0].exporterID;
              var url =
                serverURL +
                "consignee/getConsigneeByExporter?exporterID=" +
                exporterID;
              var option = "";
              controller.getAuthRequest(url, true, function (data, status) {
                if (data.length > 0) {
                  option += "<option>-Select Consignee-</option>";
                  for (let i = 0; i < data.length; i++) {
                    option +=
                      "<option value=" +
                      data[i].consigneeID +
                      ">" +
                      data[i].name +
                      "</option>";
                  }
                } else {
                  option +=
                    "<option selected disabled >Select Consignee</option>";
                }
                $("#consigneeID").html();
                $("#consigneeID").html(option);
              });
            } catch (error) {}
          }
        );
      }
      if (formName == "consignmentInspectionRequest") {
        if (
          $("#packagingMaterial").val() == 3 ||
          $("#packagingMaterial").val() == "3"
        ) {
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
          $(".containerType_holder").show();
        } else {
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
          $(".containerType_holder").hide();
        }
      }
      if (formName == "exporterConsignment" || formName == "consolidatedPhyto") {
        $(".repackaged_holder").hide();
        $(".oldContainer_holder").hide();
        $(".repckagingTypeID_holder").hide();
        if (
          $("#countryOfOrigin_id").val() == "1" ||
          $("#countryOfOrigin_id").val() == 1
        ) {
          var option = $(
            '<option value="1016">' + "Phytosanitary Certificate" + "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").hide();
          $(".oldContainer_holder").hide();
          $(".repckagingTypeID_holder").hide();
        } else {
          var option = $(
            '<option value="52">' +
              "Re-Export Phytosanitary Certificate" +
              "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").show();
          $(".oldContainer_holder").show();
          $(".repckagingTypeID_holder").show();
        }
      }
      if (formName == "consolidatedPhyto") {
        $(".btnvalidatsr14_holder").hide();
      }
      if (formName == "pip_application") {
        $(".numberOfPackages_holder").hide();
        $(".btnvalidatsr14_holder").show();
        if (
          $("#packaging_type_id").val() == 5 ||
          $("#packaging_type_id").val() == "5"
        ) {
          $(".numberOfPackages_holder").show();
        } else {
          $(".numberOfPackages_holder").hide();
        }
      }
      if (formName == "exporterConsignment") {
        document.getElementsByClassName("crud_section_lines")[0].style.display =
          "none";
        document.getElementsByClassName("crud_section_2")[0].style.display =
          "none";
      }
      if (formName == "exportLowRiskCommodity" || formName == "exporterFirm") {
        controller.requestWithToken(
          serverURL + "api/validateuser",
          function (data1, status) {
            var select = $("#capacity");
            var newOptions = {
              "Small (less than 3000m3": "Small (less than 3000m3",
              "Medium (3000m3 -5000m3)": "Medium (3000m3 -5000m3)",
              "Large (more than 5000m3)": "Large (more than 5000m3)",
            };
            $.each(newOptions, function (text, key) {
              var option = new Option(key, text);
              select.append($(option));
            });
          }
        );
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            if (
              data1[0].isResearcher == "true" ||
              data1[0].isResearcher == true
            ) {
              $(".firms_holder").hide();
              $(".farms_holder").hide();
              $(".sourcesResearcher_holder").show();
              $("#sourcesResearcher").val(data1[0].researchInstitute.name);
              document
                .getElementById("firms")
                .setAttribute("data-parsley-required", "false");
              document
                .getElementById("farms")
                .setAttribute("data-parsley-required", "false");
            } else {
              $(".firms_holder").show();
              $(".farms_holder").show();
              $(".sourcesResearcher_holder").hide();
              $("#sourcesResearcher").val("None");
              document
                .getElementById("firms")
                .setAttribute("data-parsley-required", "false");
              document
                .getElementById("farms")
                .setAttribute("data-parsley-required", "false");
            }
            var exporterID = data1[0].exporterID;
            if (
              data1[0].isExportConsolidator == "true" ||
              data1[0].isExportConsolidator == true
            ) {
              $(".farms_holder").hide();
            } else {
            }
          }
        );
      }
      if (formName == "pipApplicationVarietyRequest") {
        $(".sr14Number_holder").hide();
        if ($("#seed").val() == "true") {
          document
            .getElementById("sr14Number")
            .setAttribute("data-parsley-required", "true");
          $(".sr14Number_holder").show();
        } else if ($("#seed").val() == "false") {
          $(".sr14Number_holder").hide();
          document
            .getElementById("sr14Number")
            .setAttribute("data-parsley-required", "false");
          document.getElementById("sr14Number").value = "N/A";
        }
      }
      if (formName == "exporterConsignment") {
        $(".sr14_no_holder").hide();
        $(".btnvalidatsr14_holder").hide();
        $(".btnucrvalidations_holder").hide();
        localStorage.removeItem("isseed");
        if ($("#seedApplication").val() == "true") {
          document
            .getElementById("sr14_no")
            .setAttribute("data-parsley-required", "true");
          $(".sr14_no_holder").show();
          $(".btnvalidatsr14_holder").show();
          $(".sr14_no_holder").show();
        } else if ($("#seedApplication").val() == "false") {
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#sr14_no").val() == "";
          $("#sr14_no").val("");
          document.getElementById("sr14_no").value = "";
          document.getElementById("consignmentWeight").value = "";
        } else {
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#sr14_no").val() == "";
          $("#sr14_no").val("");
        }
      }
      if (formName == "importerInspectionRequest") {
        $(".quarantineFacilityID_holder").hide();
        $(".quarantineFacilityProposedInspectionDate_holder").hide();
      }
      if (formName == "exporterConsignment") {
        $(".certificateNumber_holder").hide();
      }
      if (formName == "onetime_import_variety_details") {
        $(".sr14Number_holder").hide();
      }
      if (formName == "exporter" || formName == "importer_product") {
      }
      if (formName == "pip_application") {
        $(".sr14_number_holder").hide();
        $(".btnvalidatsr14_holder").hide();
      }
      if (formName == "consolidatedPhyto") {
        $(".sr14_no_holder").hide();
        $(".vesselName_holder").hide();
        $(".certificateNumber_holder").hide();
      }
      if (formName == "exporter") {
        $(".researchInstituteID_holder").hide();
        $(".researcherCategoryID_holder").hide();
      }
      if (formName == "exporterFarm") {
        $("#previousCropsID").multiselect("rebuild");
        $("#previousCropsID option:selected").prop("selected", false);
        $("#previousCropsID").multiselect("rebuild");
        $("#previousCropsID").multiselect("refresh");
        $("#tradingblocks").multiselect("rebuild");
        $("#tradingblocks option:selected").prop("selected", false);
        $("#tradingblocks").multiselect("rebuild");
        $("#tradingblocks").multiselect("refresh");
      }
      if (formName == "exporterFarm") {
        $("#tradingcountries").multiselect("rebuild");
        $("#tradingcountries option:selected").prop("selected", false);
        $("#tradingcountries").multiselect("rebuild");
        $("#tradingcountries").multiselect("refresh");
      }
      if (formName == "clients") {
        $("#roleName").multiselect("rebuild");
        $("#roleName option:selected").prop("selected", false);
        $("#roleName").multiselect("rebuild");
        $("#roleName").multiselect("refresh");
      }
      if (formName == "menu") {
        $("#formTypes").multiselect("rebuild");
        $("#formTypes option:selected").prop("selected", false);
        $("#formTypes").multiselect("rebuild");
        $("#formTypes").multiselect("refresh");
      }
    },
    validateOnView_Edit: function (x, formName) {
      $(".btnvalidatsr14_holder").hide();
      $(".viewCertBtn_holder").hide();
      $(".btnucrvalidations_holder").hide();
      if (formName == "pip_application") {
        var pipApplicationID = x.pipApplicationID;
        var url =
          serverURL +
          "pipApplicationVariety/getPIPApplicationVarietyByPIPApplication?pipApplicationID=" +
          pipApplicationID;
        controller.requestWithToken(url, function (data1, status) {
          if (data1.length > 0) {
            try {
              if (data1[0].importCondition.code == "QR") {
                $(".pipApplicationQuarantineFacility_tab_link").show();
              } else {
                $(".pipApplicationQuarantineFacility_tab_link").hide();
              }
            } catch (error) {}
          }
        });
      }
      if (formName == "pipApplicationVarietyRequest") {
        var option3 = "";
        option3 +=
          "<option selected value=" +
          x.productFamily.product_family_id +
          ">" +
          x.productFamily.name +
          "</option>";
        $("#productFamilyId").html(option3);
      }
      if (formName == "onetime_import") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyanceMeansID").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyanceMeansID").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 204) {
          $(".vesselName_holder").show();
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
        } else if ($("#conveyanceMeansID").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName").show();
          $(".vesselName_holder").hide();
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if (formName == "exporterProduct") {
        if (
          x.licensingBody.name == undefined ||
          x.licensingBody.name == "undefined"
        ) {
          $(".exporterLicenseNo_holder").hide();
          $(".licensingBody_id_holder").hide();
        } else {
          $(".exporterLicenseNo_holder").show();
          $(".licensingBody_id_holder").show();
        }
      }
      if (formName == "clients") {
        controller.getuserRoles();
      }
      if (formName == "tradingcountry") {
        var tradingcountry = localStorage.getItem("tradingcountry");
        $("#trading_block_id").val(tradingcountry);
      }
      if (formName == "exporterFarmproducts") {
        var epid = localStorage.getItem("exporterFarmId");
        $("#exporterFarmId").val(epid);
      }
      if (formName == "onetime_export_variety_details") {
        // var countryid = allFormObj["selected"]["countryOfDestination"]["country_id"];
        var url = serverURL + "product/productList?pageNo=0&pageSize=10000";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          option += "<option selected disabled >--Select Commodity--</option>";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].products_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            controller.showToastMsg(
              "Selected Country Of Destination Has No Export Requirements",
              "#ff6666"
            );
          }
          $("#productsID").html();
          $("#productsID").html(option);
        });
      }
      if (formName == "consolidatedPhyto") {
        var countryid = localStorage.setItem(
          "country_id",
          x.countryOfDestination.country_id
        );
      }
      if (formName == "exporterFarm") {
        var lat = x.latitude;
        var lng = x.longtitude;
        localStorage.setItem("lat", lat);
        localStorage.setItem("lng", lng);
        setTimeout(function () {
          $(".latitude_holder").hide();
          $(".longtitude_holder").hide();
        }, 100);
      }
      if (
        formName == "exporterConsignment" ||
        formName == "assignPhytoInspections" ||
        formName == "assignedPhytoInspections" ||
        formName == "consolidatedPhyto"
      ) {
        setTimeout(function () {
          $(".certificate_type_id_holder").show();
          $(".inspection_location_id_holder").show();
          $(".certtype_holder").hide();
          $(".vesselName_holder").show();
          $(".btnvalidatsr14_holder").hide();
          if (x.countryOfOrigin.country_id == 1) {
            var option = $(
              '<option value="1016">' + "Phytosanitary Certificate" + "</option>"
            );
            $("#certificate_type_id").html(option);
            $(".inspection_location_id_holder").show();
          } else {
            var option = $(
              '<option value="52">' +
                "Re-Export Phytosanitary Certificate" +
                "</option>"
            );
            $("#certificate_type_id").html(option);
          }
          if (x.conveyanceMeans.conveyance_means_id == 202) {
            $(".vesselName_holder .control-label").html("Vessel Name");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 153) {
            $(".vesselName_holder .control-label").html("Reg Number");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 152) {
            $(".vesselName_holder .control-label").html("Flight Number");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 204) {
            $(".vesselName_holder").show();
            $(".shippingOrderNumber_holder").show();
            $(".vesselName_holder .control-label").html("Vessel Name");
          } else {
            $(".vesselName_holder").show();
            $(".shippingOrderNumber_holder").show();
          }
        }, 1000);
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        $(".netWeight_holder").hide();
        $(".grossWeight_holder").hide();
        var option5 = "";
        option5 +=
          "<option selected value=" +
          x.productCategory.product_category_id +
          ">" +
          x.productCategory.name +
          "</option>";
        $("#product_category_id").html(option5);
        $(".product_class_id_holder").hide();
        try {
          var countryid = x.exporterConsignment.countryOfDestination.country_id;
          var url =
            serverURL +
            "exportRequirement/findProductByExportRequiremntCountry?countryId=" +
            countryid +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = "";
            option +=
              "<option selected disabled value=" +
              x.products.products_id +
              ">" +
              x.products.name +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].products_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            } else {
            }
            $("#products_id").html();
            $("#products_id").html(option);
          });
        } catch (error) {}
        try {
          var countryoforigin =
            allFormObj["selected"]["exporterConsignment"]["countryOfOrigin"][
              "country_id"
            ];
          if (countryoforigin == 1) {
            setTimeout(function () {
              $(".firms_holder").show();
              $(".farms_holder").show();
            }, 500);
          } else {
            setTimeout(function () {
              $(".firms_holder").hide();
              $(".farms_holder").hide();
            }, 500);
          }
        } catch (error) {}
        var product_form_id = x.productForm.product_form_id;
        var countryid = localStorage.getItem("countryid");
        var products_id = x.products.products_id;
        var url =
          serverURL +
          "exportRequirement/getExportRequirement?country_id=" +
          countryid +
          "&product_form_id=" +
          product_form_id +
          "&products_id=" +
          products_id +
          "";
        $.ajax({
          url: url,
          contentType: "application/json",
          headers: {
            Authorization: userObj.tokenType + " " + userObj.accessToken,
          },
          type: "post",
          data: "",
          success: function (data) {
            if (data) {
              try {
                if (data.isCOC == true || data.isCOC == "true") {
                  $(".netWeight_holder").show();
                  $(".grossWeight_holder").show();
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "true");
                  $("#netWeight").attr("data-required", "true");
                  $("#grossWeight").attr("data-required", "true");
                } else if (data.isCOC == false || data.isCOC == "false") {
                  $(".netWeight_holder").hide();
                  $(".grossWeight_holder").hide();
                  $("#netWeight").attr("data-required", "false");
                  $("#grossWeight").attr("data-required", "false");
                  $("#product_class_id").attr("data-required", "false");
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "false");
                }
              } catch (error) {}
            }
          },
          fail: function (e) {},
          error: function (XMLHttpRequest, textStatus, errorThrown) {},
        });
      }
      if (formName == "exporterFarm") {
        var select = $("#no_of_seasons");
        var newOptions = {
          "": "-Select Numner of Seasons-",
          1: "1",
          2: "2",
          3: "3",
          4: "4",
          5: "5",
          6: "6",
          7: "7",
          8: "8",
          9: "9",
          10: "10",
          11: "11",
          12: "12",
          Continous: "Continous",
          "N/A": "N/A",
        };
        $.each(newOptions, function (text, key) {
          var option = new Option(key, text);
          select.append($(option));
        });
      }
      if (formName == "exporterLowRiskCommodity") {
        var select = $("#capacity");
        var newOptions = {
          "Small (less than 3000m3": "Small (less than 3000m3",
          "Medium (3000m3 -5000m3)": "Medium (3000m3 -5000m3)",
          "Large (more than 5000m3)": "Large (more than 5000m3)",
        };
        $.each(newOptions, function (text, key) {
          var option = new Option(key, text);
          select.append($(option));
        });
      }
      if (formName == "pip_application" || formName == "pip_applicationrequest") {
        controller.requestWithToken(
          serverURL + "importer/getImporterByCompanyID",
          function (data1, status) {
            var importerID = data1[0].importerID;
            var url =
              serverURL +
              "importerExporter/getImporterExporterByImporterID?importerID=" +
              importerID;
            var option = "";
            controller.getAuthRequest(url, true, function (data, status) {
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].importerExporterID +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              } else {
              }
              $("#importer_exporterid").html();
              $("#importer_exporterid").html(option);
            });
          }
        );
      }
      if (formName == "consignmentInspectionRequest") {
        if (
          $("#packagingMaterial").val() == 3 ||
          $("#packagingMaterial").val() == "3"
        ) {
          $(".containerType_holder").show();
        } else {
          $(".containerType_holder").hide();
        }
      }
      if (formName == "onetime_import_variety_details") {
        $(".containerType_holder").hide();
        if (
          $("#packagingTypeID").val() == 3 ||
          $("#packagingTypeID").val() == "3"
        ) {
          $(".containerType_holder").show();
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "true");
        } else {
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
          $(".containerType_holder").hide();
        }
      }
      if (formName == "exporter") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            if (
              data1[0].isResearcher == "true" ||
              data1[0].isResearcher == true
            ) {
              $(".isOwnFarmExporter_holder").hide();
              $(".isExportConsolidator_holder").hide();
              $(".isDryCommodityExporter_holder").hide();
            } else {
              $(".isOwnFarmExporter_holder").show();
              $(".isExportConsolidator_holder").show();
              $(".isDryCommodityExporter_holder").show();
            }
          }
        );
      }
      if (formName == "pip_application") {
        $(".numberOfPackages_holder").hide();
        if (
          $("#packaging_type_id").val() == 3 ||
          $("#packaging_type_id").val() == "3"
        ) {
          $(".numberOfPackages_holder").show();
        } else {
          $(".numberOfPackages_holder").hide();
        }
      }
      if (formName == "officeLocation ") {
        $(".validateUCR_holder").show();
      }
      if (
        formName == "exporterConsignment" ||
        formName == "exporterConsignmentVarietyDetails"
      ) {
        $(".crud_section_2").hide();
        $(".crud_section_3").hide();
      }
      if (formName == "exporterConsignment" || formName == "consolidatedPhyto") {
        if (
          $("#countryOfOrigin_id").val() == "1" ||
          $("#countryOfOrigin_id").val() == 1
        ) {
          var option = $(
            '<option value="1016">' + "Phytosanitary Certificate" + "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").hide();
          $(".oldContainer_holder").hide();
          $(".repckagingTypeID_holder").hide();
        } else {
          var option = $(
            '<option value="52">' +
              "Re-Export Phytosanitarycertificate" +
              "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").show();
          $(".oldContainer_holder").show();
          $(".repckagingTypeID_holder").show();
        }
      }
      if (formName == "onetime_import") {
        $(".crud_section_2").hide();
        $(".crud_section_3").hide();
      }
      if (formName == "exporterConsignment") {
        $(".crud_section_2").hide();
        $(".crud_section_3").hide();
      }
      if (formName == "exportLowRiskCommodity") {
        controller.requestWithToken(
          serverURL + "api/validateuser",
          function (data1, status) {
            var select = $("#capacity");
            var newOptions = {
              "Small (less than 3000m3": "Small (less than 3000m3",
              "Medium (3000m3 -5000m3)": "Medium (3000m3 -5000m3)",
              "Large (more than 5000m3)": "Large (more than 5000m3)",
            };
            $.each(newOptions, function (text, key) {
              var option = new Option(key, text);
              select.append($(option));
            });
          }
        );
      }
      if (formName == "consignmentInspectionRequest") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        if ($("#conveyance_means_id").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyance_means_id").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
        } else if ($("#conveyance_means_id").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#manifestNo").val("");
        } else {
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      try {
        if (formName == "exporterConsignmentVarietyDetails") {
          controller.requestWithToken(
            serverURL + "exporter/getExporterByCompanyID",
            function (data1, status) {
              if (
                data1[0].isResearcher == "true" ||
                data1[0].isResearcher == true
              ) {
                $(".firms_holder").hide();
                $(".farms_holder").hide();
                $(".sourcesResearcher_holder").show();
                $("#sourcesResearcher").val(data1[0].researchInstitute.name);
              } else {
                $(".firms_holder").show();
                $(".farms_holder").show();
                $(".sourcesResearcher_holder").hide();
                $("#sourcesResearcher").val("None");
              }
              var exporterID = data1[0].exporterID;
              if (
                data1[0].isExportConsolidator == "true" ||
                data1[0].isExportConsolidator == true
              ) {
                $(".farms_holder").hide();
              } else {
              }
            }
          );
        }
      } catch (error) {}
      if (formName == "exporterConsignment") {
        setTimeout(function () {
          if (x.seedApplication == "true") {
            $(".sr14_no_holder").show();
            $(".sr14_no_holder").show();
          } else {
            $(".sr14_no_holder").show();
            $(".sr14_no_holder").hide();
          }
          if (x.countryOfOrigin.country_id == 1) {
            $(".originalIssuingCountry_id_holder").hide();
            $(".certificateNumber_holder").hide();
          } else {
            $(".originalIssuingCountry_id_holder").show();
            $(".certificateNumber_holder").show();
          }
        }, 500);
      }
      if (formName == "exporter") {
        $(".crud_section_lines").hide();
        $(".crud_section_2").hide();
        $(".crud_section_3").hide();
      }
      if (formName == "pip_application") {
        $(".crud_section_lines").hide();
        $(".crud_section_3").hide();
      }
      if (formName == "pip_application") {
        $(".btnvalidatsr14_holder").show();
        $(".getCondition_holder").hide();
        setTimeout(function () {
          if (x.seedApplication == "true") {
            $(".sr14_no_holder").show();
            $(".btnvalidatsr14_holder").show();
          } else {
            $(".sr14_no_holder").hide();
            $(".btnvalidatsr14_holder").hide();
          }
          $(".getCondition_holder").show();
        }, 600);
      }
      if (formName == "consolidatedPhyto") {
        setTimeout(function () {
          if (x.seedApplication == "true") {
            $(".sr14_no_holder").show();
          } else {
            $(".sr14_no_holder").hide();
          }
          if (x.conveyanceMeans_id == 202) {
            $(".vesselName_holder").show();
          } else {
            $(".vesselName_holder").hide();
          }
          if (x.countryOfOrigin.country_id == 1) {
            $(".originalIssuingCountry_id_holder").hide();
            $(".certificateNumber_holder").hide();
          } else {
            $(".originalIssuingCountry_id_holder").show();
            $(".certificateNumber_holder").show();
          }
        }, 800);
      }
      if (formName == "exporter") {
        setTimeout(function () {
          if (!x.isResearcher) {
            $(".researchInstitute_id_holder").hide();
            $(".researcherCategory_id_holder").hide();
            $(".researchInstituteID_holder").hide();
            $(".researcherCategoryID_holder").hide();
          } else {
            $(".researchInstituteID_holder").show();
            $(".researcherCategory_id_holder").show();
            $(".researchInstituteID_holder").show();
            $(".researcherCategoryID_holder").show();
          }
          if (x.isOwnFarmExporter) {
            $(".isExportConsolidator_holder").hide();
          } else {
            $(".isExportConsolidator_holder").show();
          }
        }, 100);
      }
      if (formName == "assignInspection" || formName == "assignedInspection") {
        setTimeout(function () {
          if (!x.researcher) {
            $(".researchInstitute_id_holder").hide();
            $(".researcherCategory_id_holder").hide();
            $(".researchInstituteID_holder").hide();
            $(".researcherCategoryID_holder").hide();
          } else {
            $(".researchInstitute_id_holder").show();
            $(".researcherCategory_id_holder").show();
            $(".researchInstituteID_holder").show();
            $(".researcherCategoryID_holder").show();
          }
        }, 500);
      }
    },
    getCountriesView: function () {
      var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000000";
      controller.requestWithToken(url, function (data, status) {
        var option = "";
        $("#country_id").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option selected value=" +
            data[i].country_id +
            ">" +
            data[i].name +
            "</option>";
        }
      });
    },
    viewRow: function (x, e) {
      isreadOnly = true;
      var formName = $(e).attr("form-name");
      var exclusionTab = [];
      $(".validateUCR_holder").show();
      try {
        setTimeout(function () {
          $(".viewCertBtn_holder").hide();
          $(".getCondition_holder").hide();
          $(".validucr_holder").hide();
          $(".btnAddExporter_holder").hide();
          $(".btnucrvalidations_holder").hide();
          $("#upload-document").css("display", "none");
          $("#document-setup_").css("display", "none");
          $(".btnAddExporter_holder").css("display", "none");
          $(".crud_section_lines").hide();
        }, 500);
      } catch (error) {}
      try {
        setTimeout(function () {
          $(".saveRecord").hide();
        }, 200);
      } catch (error) {}
      try {
        $("#listings_" + formName).hide();
      } catch (error) {}
      try {
        $(".crud_section_lines").hide();
      } catch (error) {}
      try {
        loaddpreviousApproversremarks();
      } catch (error) {}
  
      if (formName == "exporterFirm") {
        if (x.market == true) {
          setTimeout(function () {
            $(".fullName_holder").hide();
            $(".email_holder").hide();
            $(".pin_holder").hide();
            $(".country_id_holder").hide();
            $(".postalAddress_holder").hide();
            $(".postalCode_holder").hide();
            $(".streetName_holder").hide();
            $(".telephone_holder").hide();
            $(".town_holder").hide();
            $(".farms_holder").hide();
          }, 400);
        } else {
        }
      }
      if (formName == "assignedInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterID +
          "&tableName=exporter";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignImporterInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterID +
          "&tableName=exporter";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedPhytoInspections") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterConsignmentID +
          "&tableName=exporter_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsignmentInspectionRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.consignmentInspectionRequestID +
          "&tableName=consignment_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedExporterFarm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFarmID +
          "&tableName=exporter_farm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsignmentInspectionRequestLabanalysis") {
        controller.previousCommentsDisplay(x.reason, x.reason);
      }
      if (formName == "exporter_firm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFirmID +
          "&tableName=exporter_firm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterID +
          "&tableName=exporter";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedPIPReprint") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.reprint_application_id +
          "&tableName=reprint_application";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedStorageLocation") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.storage_location_id +
          "&tableName=storage_location";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignStorageLocation") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.storage_location_id +
          "&tableName=storage_location";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignQuarantineFacilityProductsRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.quarantine_facility_product_request_id +
          "&tableName=quarantine_facility_product_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedQuarantineFacilityProductsRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.quarantine_facility_product_request_id +
          "&tableName=quarantine_facility_product_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignPhytoInspections") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterConsignmentID +
          "&tableName=exporter_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignEvaluationRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.evaluation_application_id +
          "&tableName=evaluation_application";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsignmentInspectionRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.consignmentInspectionRequestID +
          "&tableName=consignment_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsignmentInspectionLabAnalysis") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.lab_analysis_id +
          "&tableName=consignment_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedEvaluationRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.evaluation_application_id +
          "&tableName=evaluation_application";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedExporterRequirements") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.export_requirement_id +
          "&tableName=export_requirement";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedImportRequirements") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.import_requirement_id +
          "&tableName=import_requirement";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignPIPInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.pipApplicationID +
          "&tableName=pipapplication";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedPIPInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.pipApplicationID +
          "&tableName=pipapplication";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignConsignmentInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.consignmentInspectionRequestID +
          "&tableName=consignment_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsignmentInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.consignmentInspectionRequestID +
          "&tableName=consignment_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedImporterInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.importerID +
          "&tableName=importer";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignInspectionRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterInspectionRequestID +
          "&tableName=exporter_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "exporterFarmInspection") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterInspectionRequestID +
          "&tableName=exporter_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedInspectionRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterInspectionRequestID +
          "&tableName=exporter_inspection_request";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignQuarantineFacility") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.quarantineFacilityID +
          "&tableName=quarantine_facility";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedQuarantineFacility") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.quarantineFacilityID +
          "&tableName=quarantine_facility";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignExporterFarm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFarmID +
          "&tableName=exporter_farm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedExporterFarm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFarmID +
          "&tableName=exporter_farm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignAgentRegistration") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.agents_id +
          "&tableName=agent";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedAgentRegistration") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.agents_id +
          "&tableName=agent";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignExporterFirm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFirmID +
          "&tableName=exporter_firm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedExporterFirm") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterFirmID +
          "&tableName=exporter_firm";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignExporterLowRisk") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exportLowRiskCommodityID +
          "&tableName=exporter_low_risk_commodity";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignConsolidatedPhyto") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterConsignmentID +
          "&tableName=exporter_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignSplitConsignment") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.split_export_consignment_id +
          "&tableName=split_export_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignPhytoReplacement") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.printout_replacement_id +
          "&tableName=printout_replacement";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedSplitConsignment") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.split_export_consignment_id +
          "&tableName=split_export_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedPhytoReplacement") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.printout_replacement_id +
          "&tableName=printout_replacement";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedConsolidatedPhyto") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exporterConsignmentID +
          "&tableName=exporter_consignment";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedExporterLowRisk") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.exportLowRiskCommodityID +
          "&tableName=exporter_low_risk_commodity";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignedPestRiskAnalysisRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.pestRiskAnalysisRequest_id +
          "&tableName=pest_risk_analysis_request_list";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "assignPestRiskAnalysisRequest") {
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          x.pestRiskAnalysisRequest_id +
          "&tableName=pest_risk_analysis_request_list";
        controller.requestWithToken(url, function (output, status) {
          for (let i = 0; i < output.length; i++) {
            controller.previousCommentsDisplay(
              output[i].previousRemarks,
              output[i].message
            );
          }
        });
      }
      if (formName == "exporterFirm" || formName == "importerExporter") {
        var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option selected value=" +
                x.country.country_id +
                ">" +
                x.country.name +
                "</option>";
              option +=
                "<option value=" +
                data[i].country_id +
                ">" +
                data[i].name +
                "</option>";
              $("#country_id").html(option);
            }
          }
        });
      }
      if (formName == "exporterConsignment") {
        if (x.isRepackaged == "true" || x.isRepackaged == true) {
          setTimeout(function () {
            $(".repckagingTypeID_holder").show();
          }, 200);
        } else {
          setTimeout(function () {
            $(".repckagingTypeID_holder").hide();
          }, 200);
        }
      }
      if (
        formName == "consignmentInspectionRequest" ||
        formName == "assignedConsignmentInspectionRequest"
      ) {
        if (x.awbNumber == "") {
          setTimeout(function () {
            $(".awbNumber_holder").hide();
          }, 100);
        } else {
          setTimeout(function () {
            $(".awbNumber_holder").show();
          }, 100);
        }
        if (x.billOfLading == "") {
          setTimeout(function () {
            $(".billOfLading_holder").hide();
          }, 100);
        } else {
          setTimeout(function () {
            $(".billOfLading_holder").show();
          }, 100);
        }
        if (x.manifestNo == "") {
          setTimeout(function () {
            $(".manifestNo_holder").hide();
          }, 100);
        } else {
          setTimeout(function () {
            $(".manifestNo_holder").show();
          }, 100);
        }
        if (x.vesselName == "") {
          setTimeout(function () {
            $(".vesselName_holder").hide();
          }, 100);
        } else {
          setTimeout(function () {
            $(".vesselName_holder").show();
          }, 100);
        }
        if (x.containerType == "") {
          setTimeout(function () {
            $(".containerType_holder").hide();
          }, 100);
        } else {
          setTimeout(function () {
            $(".containerType_holder").show();
          }, 100);
        }
        var url =
          serverURL +
          "pipApplication/pipApplicationList?pageNo=0&pageSize=1000000";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.length > 0) {
            var option = "";
            option +=
              "<option selected value=" +
              x.pipApplication.pipApplicationID +
              ">" +
              x.pipApplication.documentNumber +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].pipApplicationID +
                  ">" +
                  data[i].documentNumber +
                  "</option>";
                $("#pip_application_id").html(option);
              }
            }
          }
        });
      }
      if (
        formName == "consignmentInspectionRequest" ||
        formName == "assignedConsignmentInspectionRequest"
      ) {
        var url =
          serverURL +
          "pipApplication/pipApplicationList?pageNo=0&pageSize=1000000";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.length > 0) {
            var option = "";
            option +=
              "<option selected value=" +
              x.pipApplication.pipApplicationID +
              ">" +
              x.pipApplication.documentNumber +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].pipApplicationID +
                  ">" +
                  data[i].documentNumber +
                  "</option>";
                $("#pip_application_id").html(option);
              }
            }
          }
        });
      }
      if (formName == "evaluation_application") {
        var option = "";
        option +=
          "<option selected value=" +
          x.country.country_id +
          ">" +
          x.country.country_id +
          "</option>";
        $("#country_id").html(option);
      }
      if (
        formName == "assignedInspection" ||
        formName == "assignedExporterFirm" ||
        formName == "assignedExporterLowRisk" ||
        formName == "assignConsignmentInspection" ||
        formName == "assignedQuarantineFacility" ||
        formName == "assignedInspectionRequest" ||
        formName == "assignExporterFarm" ||
        formName == "assignQuarantineFacility" ||
        formName == "assignedInspectionRequest" ||
        formName == "assignedExporterFarm"
      ) {
        crudsaveLinesInspection = true;
        crudOnetimeExportImportLineeSaveInspection = false;
        crudeImportConsLineSaveInspection = false;
        crudexportLineSaveInspection = false;
      }
      if (
        formName == "onetime_export" ||
        formName == "assignedPhytoInspections"
      ) {
        crudsaveLinesInspection = false;
        crudOnetimeExportImportLineeSaveInspection = true;
        crudeImportConsLineSaveInspection = false;
        crudexportLineSaveInspection = false;
      }
      if (formName == "onetime_export") {
        crudsaveLinesInspection = false;
        crudOnetimeExportImportLineeSaveInspection = false;
        crudeImportConsLineSaveInspection = false;
        crudexportLineSaveInspection = false;
      }
      if (
        formName == "onetime_import" ||
        formName == "assignedConsignmentInspectionRequest"
      ) {
        crudsaveLinesInspection = false;
        crudOnetimeExportImportLineeSaveInspection = false;
        crudeImportConsLineSaveInspection = true;
        crudexportLineSaveInspection = false;
      }
      if (formName == "pipApplicationVarietyRequest") {
        var importpurpose = x.importPurpose.importPurposeID;
        var country = x.pipApplicationRequest.countryOfOrigin.country_id;
        var url =
          serverURL +
          "importRequirement/findProductByImportRequiremntCountryAndImportPupose?countryId=" +
          country +
          "&importPurposeId=" +
          importpurpose +
          "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.length > 0) {
            var option = "";
            option +=
              "<option selected value=" +
              x.product.products_id +
              ">" +
              x.product.name +
              "</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].products_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            }
            $("#products_id").html();
            $("#products_id").html(option);
            option += "<option>-Select Option-</option>";
            $("#products_id").html(option);
          }
        });
        var option2 = "";
        option2 +=
          "<option selected value=" +
          x.importCondition.import_condition_id +
          ">" +
          x.importCondition.name +
          "</option>";
        $("#importConditionID").html(option2);
        var option3 = "";
        option3 +=
          "<option selected value=" +
          x.productFamily.product_family_id +
          ">" +
          x.productFamily.name +
          "</option>";
        $("#productFamilyId").html(option3);
        var option4 = "";
        option4 +=
          "<option selected value=" +
          x.productCategory.product_category_id +
          ">" +
          x.productCategory.name +
          "</option>";
        $("#product_category_id").html(option4);
        var option5 = "";
        option5 +=
          "<option selected value=" +
          x.packagingType.packaging_type_id +
          ">" +
          x.packagingType.name +
          "</option>";
        $("#packagingTypeID").html(option5);
        var option6 = "";
        option6 +=
          "<option selected value=" +
          x.siUnit.sIUnit_id +
          ">" +
          x.siUnit.name +
          "</option>";
        $("#siUnitID").html(option6);
        var option9 = "";
        option9 +=
          "<option selected value=" +
          x.productForm.product_form_id +
          ">" +
          x.productForm.name +
          "</option>";
        $("#productFormID").html(option9);
        var option7 = "";
        option7 +=
          "<option selected value=" +
          x.pipApplicationRequest.importer.importerID +
          ">" +
          x.pipApplicationRequest.importer.company.name +
          "</option>";
        $("#importerID").html(option7);
        setTimeout(function () {
          $(".importerID_holder").hide();
        }, 300);
      }
      if (formName == "banned_list") {
        var option = "";
        option +=
          "<option selected value=" +
          x.products.products_id +
          ">" +
          x.products.name +
          "</option>";
        $("#products_id").html(option);
      }
      if (
        formName == "assigned_printout_replacement" ||
        formName == "assignedInspection"
      ) {
        $(".crud_section_3").hide();
      }
      if (formName == "consignmentInspectionRequest") {
        var option;
        option +=
          "<option selected value=" +
          x.pipApplication.pipApplicationID +
          "></option>";
        $("#pip_application_id").html(option);
      }
      if (formName == "assigned_printout_replacement") {
        $(".crud_section_3").hide();
      }
      if (formName == "pipApplicationVarietyRequest") {
        setTimeout(function () {
          $(".importerID_holder").hide();
        }, 300);
        var products_id = x.product.products_id;
        controller.getBotanicalNameVariety(products_id);
      }
      if (formName == "usersStakeholders") {
        if (x.nationalIDNo == null || x.nationalIDNo == "null") {
          setTimeout(function () {
            document.getElementById("nationalIDNo").value = "N/A";
            $("#nationalIDNo").val("N/A");
          }, 3000);
        } else {
          setTimeout(function () {
            document.getElementById("nationalIDNo").value = "N/A";
          }, 3000);
        }
      }
      if (
        formName == "assignedConsignmentInspectionRequestLabanalysis" ||
        formName == "assignedQuarantineFacility" ||
        formName == "assignedExporterLowRisk" ||
        formName == "assignInspection" ||
        formName == "assignedInspection" ||
        formName == "evaluation_application" ||
        formName == "assignedPhytoInspections" ||
        formName == "assignConsignmentInspection" ||
        formName == "assignedPIPInspection" ||
        formName == "pip_application" ||
        formName == "assignedExporterFarm" ||
        formName == "printout_replacement" ||
        formName == "quarantine_facility_product_request"
      ) {
        isCrudAttachmentview = true;
      } else {
        isCrudAttachmentview = false;
      }
      if (formName == "documents_reports") {
        setTimeout(function () {
          $("#btnupdatedocuments").hide();
        }, 3000);
      }
      if (formName == "pip_application") {
        var pipApplicationID = x.pipApplicationID;
        var url =
          serverURL +
          "pipApplicationVariety/getPIPApplicationVarietyByPIPApplication?pipApplicationID=" +
          pipApplicationID;
        controller.requestWithToken(url, function (data1, status) {
          if (data1[0].importCondition.code == "QR") {
            $(".pipApplicationQuarantineFacility_tab_link").hide();
          } else {
            $(".pipApplicationQuarantineFacility_tab_link").show();
          }
        });
      }
      if (formName == "exporterConsignmentVarietyDetailsconsignmnet") {
        $("#listings_edit_exporterConsignmentVarietyDetailsconsignmnet").css({
          width: 911 + "px",
        });
        $("#listings_edit_exporterConsignmentVarietyDetailsconsignmnet").css({
          height: 262 + "px",
        });
      }
      if (formName == "exporterFarm") {
        var lat = x.latitude;
        var lng = x.longtitude;
        localStorage.setItem("lat", lat);
        localStorage.setItem("lng", lng);
        setTimeout(function () {
          $(".latitude_holder").hide();
          $(".longtitude_holder").hide();
        }, 100);
      }
      if (formName == "exporterProduct") {
        if (x.products.products_id) {
          var productsID = x.products.products_id;
          controller.getproductbyviewID(productsID);
        }
      }
      if (
        formName == "exporterConsignment" ||
        formName == "consolidatedPhyto" ||
        formName == "assignConsolidatedPhyto" ||
        formName == "allPhytolicationreports" ||
        formName == "assignedConsolidatedPhyto"
      ) {
        setTimeout(function () {
          $(".certificate_type_id_holder").hide();
          $(".btnucrvalidations_holder").hide();
        }, 800);
      }
      if (formName == "exporterFarm") {
        setTimeout(function () {
          $(".btnfarmlocation_holder").hide();
        }, 600);
      }
      if (
        formName == "exporterConsignment" ||
        formName == "assignPhytoInspections" ||
        formName == "allPhytolicationreports" ||
        formName == "consolidatedPhyto" ||
        formName == "assignConsolidatedPhyto" ||
        formName == "assignedConsolidatedPhyto" ||
        formName == "allPhytolicationreports" ||
        formName == "assignedPhytoInspections"
      ) {
        setTimeout(function () {
          $(".certificate_type_id_holder").hide();
          $(".vesselName_holder").show();
          if (x.conveyanceMeans.conveyance_means_id == 202) {
            $(".vesselName_holder .control-label").html("Vessel Name");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 153) {
            $(".vesselName_holder .control-label").html("Reg Number");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 152) {
            $(".vesselName_holder .control-label").html("Flight Number");
            $(".shippingOrderNumber_holder").hide();
          } else if (x.conveyanceMeans.conveyance_means_id == 204) {
            $(".vesselName_holder .control-label").html("Vessel Name");
            $(".vesselName_holder").show();
            $(".shippingOrderNumber_holder").show();
          }
        }, 1500);
      }
      if (
        formName == "exporterConsignment" ||
        formName == "assignPhytoInspections" ||
        formName == "consolidatedPhyto" ||
        formName == "assignConsolidatedPhyto" ||
        formName == "assignedConsolidatedPhyto"
      ) {
        setTimeout(function () {
          $(".buttonAddConsignee_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $(".btnucrvalidations_holder").hide();
        }, 600);
      }
      if (formName == "officeLocation ") {
        $(".validateUCR_holder").show();
      }
      if (formName == "pip_application") {
        $(".getCondition_holder").hide();
        $(".validucr_holder").hide();
        $(".btnAddExporter_holder").hide();
      }
      if (formName == "assignInspection" || formName == "assignedInspection") {
        setTimeout(function () {
          if (x.researcher == "true" || x.researcher == true) {
            $(".Inspections_tab_link").hide();
            $(".Firms_tab_link").hide();
            $(".OwnFarms_tab_link").hide();
            $(".exporterFarmproducts_tab_link").hide();
            $(".isOwnFarmExporter_holder").hide();
            $(".OwnFarmsDestination_tab_link").hide();
            $(".LowRiskCommoditiesRegistration_tab_link").hide();
          } else {
          }
        }, 500);
      }
      if (formName == "exporter") {
        $(".viewCertBtn_holder").hide();
        if (!x.isOwnFarmExporter) {
          exclusionTab.push("OwnFarms");
          exclusionTab.push("OwnFarmsDestination");
        }
        if (!x.isExportConsolidator) {
          exclusionTab.push("Firms");
        }
        if (!x.isDryCommodityExporter) {
          exclusionTab.push("LowRiskCommoditiesRegistration");
        }
      }
      if (formName == "exporterFirm") {
        if (!x.newfarm) {
          exclusionTab.push("OwnFarms");
        }
      }
      if (formName == "exporterConsignment") {
        $(".btnvalidatsr14_holder").hide();
        $(".btnucrvalidations_holder").hide();
      }
      if (formName == "exporter") {
        $(".licensingBody_holder").show();
      }
      if (formName == "pip_application") {
        $(".getCondition_holder").hide();
      }
      if (formName == "assignInspection" || formName == "assignedInspection") {
        setTimeout(function () {
          if (x.ownFarmExporter == true || x.ownFarmExporter == "true") {
            $(".OwnFarms_tab_link").show();
          } else if (x.ownFarmExporter == false || x.ownFarmExporter == "false") {
            $(".OwnFarms_tab_link").hide();
          }
          if (x.exportConsolidator == true || x.exportConsolidator == "true") {
            $(".Firms_tab_link").show();
          } else if (
            x.exportConsolidator == false ||
            x.exportConsolidator == "false"
          ) {
            $(".Firms_tab_link").hide();
          }
          if (
            x.dryCommodityExporter == true ||
            x.dryCommodityExporter == "true"
          ) {
            $(".LowRiskCommoditiesRegistration_tab_link").show();
          } else if (
            x.dryCommodityExporter == false ||
            x.dryCommodityExporter == "false"
          ) {
            $(".LowRiskCommoditiesRegistration_tab_link").hide();
          }
        }, 500);
      }
      if (formName == "pip_application") {
        setTimeout(function () {
          if (x.seedApplication == "true") {
            $(".sr14_no_holder").show();
          } else {
            $(".sr14_no_holder").hide();
          }
        }, 500);
      }
      if (
        formName == "assignInspectionRequest" ||
        formName == "assignedInspectionRequest" ||
        formName == "exporterFarmInspection" ||
        formName == "exporterLowRiskInspection" ||
        formName == "quarantineFacilityInspection"
      ) {
        setTimeout(function () {
          if (x.exporterFirm !== undefined) {
            $(".inspectionTypeID_holder").hide();
            $(".exporterConsignmentID_holder").hide();
            $(".proposedInspectionDate_holder").show();
            $(".exporterFarmID_holder").hide();
            $(".exporterFirmID_holder").show();
            $(".exporterID_holder").hide();
            $(".exporterLowRiskCommodityID_holder").hide();
            $(".otherInfo_holder").hide();
            $(".importerID_holder").hide();
            $(".requestDate_holder").hide();
            $(".requestDate_holder").hide();
            $(".quarantineFacilityID_holder").hide();
          } else if (x.exporterFarm !== undefined) {
            $(".inspectionTypeID_holder").hide();
            $(".exporterConsignmentID_holder").hide();
            $(".proposedInspectionDate_holder").show();
            $(".exporterFarmID_holder").show();
            $(".exporterFirmID_holder").hide();
            $(".exporterID_holder").hide();
            $(".exporterLowRiskCommodityID_holder").hide();
            $(".otherInfo_holder").hide();
            $(".importerID_holder").hide();
            $(".requestDate_holder").hide();
            $(".requestDate_holder").hide();
            $(".quarantineFacilityID_holder").hide();
          } else if (x.exporterLowRiskCommodity !== undefined) {
            $(".inspectionTypeID_holder").hide();
            $(".exporterConsignmentID_holder").hide();
            $(".proposedInspectionDate_holder").show();
            $(".exporterFarmID_holder").hide();
            $(".exporterFirmID_holder").hide();
            $(".exporterID_holder").hide();
            $(".exporterLowRiskCommodityID_holder").show();
            $(".otherInfo_holder").hide();
            $(".requestDate_holder").hide();
            $(".requestDate_holder").hide();
            $(".importerID_holder").hide();
            $(".quarantineFacilityID_holder").hide();
          } else if (x.quarantineFacility !== undefined) {
            $(".quarantineFacilityID_holder").show();
            $(".inspectionTypeID_holder").hide();
            $(".exporterConsignmentID_holder").hide();
            $(".proposedInspectionDate_holder").show();
            $(".exporterFarmID_holder").hide();
            $(".exporterFirmID_holder").hide();
            $(".exporterID_holder").hide();
            $(".importerID_holder").hide();
            $(".exporterLowRiskCommodityID_holder").hide();
            $(".otherInfo_holder").hide();
            $(".requestDate_holder").hide();
            $(".requestDate_holder").hide();
          }
        }, 100);
      }
      // if (allFormObj['onetime_export_variety_details']) {
      //     allFormObj['onetime_export_variety_details']['crudAdd'] = false;
      //     allFormObj['onetime_export_variety_details']['crudEdit'] = false;
      // }
      if (allFormObj["onetime_import_variety_details"]) {
        allFormObj["onetime_import_variety_details"]["crudAdd"] = false;
        allFormObj["onetime_import_variety_details"]["crudEdit"] = false;
      }
      if (allFormObj["exporterConsignmentVarietyDetails"]) {
        allFormObj["exporterConsignmentVarietyDetails"]["crudAdd"] = false;
      }
      if (allFormObj["pipApplicationVariety"]) {
        allFormObj["pipApplicationVariety"]["crudAdd"] = false;
        allFormObj["pipApplicationVariety"]["crudEdit"] = false;
      }
      if (allFormObj["consolidatedPhyto"]) {
        allFormObj["exporterConsignmentVarietyDetailsconsignmnet"][
          "crudAdd"
        ] = false;
        allFormObj["consolidatedExportConsignmentLines"]["crudEdit"] = false;
        allFormObj["consolidatedExportConsignmentLines"]["crudAdd"] = false;
      }
      if (allFormObj["quarantineFacility"]) {
        try {
          allFormObj["facilitycommodities"]["crudAdd"] = true;
          allFormObj["facilitycommodities"]["crudEdit"] = false;
          allFormObj["facilitycommodities"]["crudDeleteRecord"] = false;
        } catch (error) {}
      }
      if (allFormObj["tradingBlock"]) {
        allFormObj["tradingcountry"]["crudAdd"] = false;
        allFormObj["tradingcountry"]["crudEdit"] = false;
      }
      if (allFormObj["importer"]) {
      }
      if (allFormObj["region"]) {
        allFormObj["regionCounty"]["crudAdd"] = false;
        allFormObj["regionCounty"]["crudEdit"] = false;
      }
  
      if (allFormObj["products"]) {
        allFormObj["inspectionRequirements"]["crudAdd"] = false;
        allFormObj["inspectionRequirements"]["crudEdit"] = false;
      }
      if (allFormObj["clients"]) {
        allFormObj["staffProfile"]["crudAdd"] = false;
        allFormObj["staffProfile"]["crudEdit"] = false;
      }
      if (allFormObj["pip_applicationrequest"]) {
        allFormObj["pipApplicationVarietyRequest"]["crudAdd"] = false;
        allFormObj["pipApplicationVarietyRequest"]["crudEdit"] = false;
      }
      // if (allFormObj['exporterFarm']) {
      //     try {
      //         allFormObj['exporterFarm']['crudEdit'] = false;
      //         allFormObj['exporterFarm']['crudAddproductsbtn'] = false;
      //     } catch (error) { }
      // }
      if (allFormObj["exporter"]) {
        allFormObj["exporterFarm"]["crudAdd"] = false;
        allFormObj["exporterFarm"]["crudEdit"] = false;
        // allFormObj['exporterFarm']['crudAddproductsbtn'] = false;
        allFormObj["exporterFarm"]["crudviewProducts"] = true;
        allFormObj["exporterFarmproducts"]["crudDeleteRecord"] = false;
        allFormObj["exporterFarm"]["crudDeleteRecord"] = false;
        allFormObj["exporterFarmproducts"]["crudEdit"] = false;
        allFormObj["exporterFarmproducts"]["crudAdd"] = false;
        allFormObj["exporterFarmproducts"]["crudDeleteRecord"] = false;
        allFormObj["exporterFirm"]["crudAdd"] = false;
        allFormObj["exporterFirm"]["crudEdit"] = false;
        allFormObj["exporterLowRiskCommodity"]["crudAdd"] = false;
        allFormObj["exporterLowRiskCommodity"]["crudEdit"] = false;
        allFormObj["exporterLowRiskCommodity"]["crudDeleteRecord"] = false;
        allFormObj["exporterFarmproducts"]["crudAdd"] = false;
        allFormObj["exporterFarmproducts"]["crudEdit"] = false;
        allFormObj["exporterFarmproducts"]["crudEdit"] = false;
        allFormObj["exporterProduct"]["crudAdd"] = false;
        allFormObj["exporterProduct"]["crudEdit"] = false;
        allFormObj["exporterProduct"]["crudDeleteRecord"] = false;
      }
      if (allFormObj["exporterFarm"]) {
        try {
          allFormObj["exporterFarmproducts"]["crudAdd"] = false;
          allFormObj["exporterFarmproducts"]["crudEdit"] = false;
        } catch (error) {}
      }
      if (allFormObj["split_export_consignment"]) {
        allFormObj["exporterConsignment"]["crudAdd"] = false;
      }
      controller.validateOnView_Edit(x, formName);
      controller.renderEditForm(
        x,
        formName,
        false,
        exclusionTab,
        function (response) {
          var formHTML = response;
          $("#listings_edit_" + formName).show();
          $("#listings_edit_" + formName).html(formHTML);
          controller.initActions();
          controller.initializeDateFields(formName);
          controller.initializeExporterRegistrationTabs();
          var cnt = 0;
          var currentObj = allFormObj[formName];
          tab = currentObj.Mytabs;
          tabLength = tab.length;
          if (tabLength > 0) {
            var cnt = 0;
            $("*[data-tab]").each(function () {
              cnt++;
              var val = $(this).attr("data-tab");
              if (cnt > 1) {
                setTimeout(function () {
                  var t = cnt - 1;
                  try {
                    controller.manualTabClick(val, cnt);
                  } catch (e) {}
                }, 1500);
              }
            });
          }
        }
      );
    },
    addRecord: function (e) {
      var formName = $(e).attr("form-name");
      var formHTML = "";
      var loadTableobj = "";
      if (
        formName == "exporterConsignment" ||
        formName == "assignPhytoInspections" ||
        formName == "allPhytolicationreports" ||
        formName == "consolidatedPhyto" ||
        formName == "assignedPhytoInspections"
      ) {
        setTimeout(function () {}, 100);
      }
      try {
        $("#listings_" + formName).hide();
      } catch (error) {}
  
      try {
        $(".crud_section_lines").hide();
      } catch (error) {}
  
      if (formName == "pip_applicationrequest") {
        try {
          var url = serverURL + "countries/countryList?pageNo=0&pageSize=100000";
          controller.getAuthRequest(url, true, function (data, status) {
            if (data.length > 0) {
              var option = "";
              option += "<option>-Select Option-</option>";
  
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              }
  
              $("#country_of_origin_id").html();
              $("#country_of_origin_id").html(option);
            } else {
              option += "<option>-Select Option-</option>";
              $("#country_of_origin_id").html(option);
            }
          });
  
          controller.requestWithToken(
            serverURL + "api/validateuser",
            function (data1, status) {
              var company_id = data1.company.company_id;
              controller.requestWithToken(
                serverURL + "agent/getAgentByCompany",
                function (data1, status) {
                  try {
                    var agents_id = data1[0].agents_id;
  
                    var url =
                      serverURL +
                      "agentManagement/getByAgent?agentID=" +
                      agents_id; //consignee/getConsigneeByExporter?exporterID=
                    controller.setUpObjInitializeSpecificOneWithCallBack(
                      url,
                      "importer",
                      function (data) {
                        if (data.length > 0) {
                          var option = "";
                          option += "<option selected>-Select Company-</option>";
                          if (data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                              option +=
                                "<option value=" +
                                data[i].company.company_id +
                                ">" +
                                data[i].company.name +
                                "</option>";
                            }
                          }
                          $("#importerid").html();
                          $("#importerid").html(option);
                        } else {
                          option += "<option>-Select Company-</option>";
                          $("#importerid").html(option);
                        }
                      }
                    );
                  } catch (error) {}
                }
              );
            }
          );
        } catch (error) {}
      }
  
      if (formName == "exporterLowRiskCommodity") {
        controller.requestWithToken(
          serverURL + "exporter/getExporterByCompanyID",
          function (data1, status) {
            var length = data1.length;
            var exporterID = data1[0].exporterID;
            var url =
              serverURL +
              "exporterProduct/getExporterProductByExporter?exporterID=" +
              exporterID;
            controller.requestWithToken(url, function (data1, status) {
              var option = "";
              option += "<option selected>-Select Commodity-</option>";
              if (data1.length > 0) {
                for (let i = 0; i < data1.length; i++) {
                  option +=
                    "<option value=" +
                    data1[i].products.products_id +
                    ">" +
                    data1[i].products.name +
                    "</option>";
                }
              }
              $("#products_id").html();
              $("#products_id").html(option);
            });
          }
        );
      }
  
      if (formName == "exporterConsignment") {
        try {
          controller.requestWithToken(
            serverURL + "api/validateuser",
            function (data1, status) {
              var company_id = data1.company.company_id;
              controller.requestWithToken(
                serverURL + "agent/getAgentByCompany",
                function (data1, status) {
                  if (data1.length > 1) {
                    var agents_id = data1[0].agents_id;
  
                    var url =
                      serverURL +
                      "agentManagement/getByAgent?agentID=" +
                      agents_id; //consignee/getConsigneeByExporter?exporterID=
                    controller.setUpObjInitializeSpecificOneWithCallBack(
                      url,
                      "company",
                      function (data) {
                        if (data.length > 0) {
                          var option = "";
                          option += "<option selected>-Select Company-</option>";
                          if (data.length > 0) {
                            for (let i = 0; i < data.length; i++) {
                              option +=
                                "<option value=" +
                                data[i].company.company_id +
                                ">" +
                                data[i].company.name +
                                "</option>";
                            }
                          }
                          $("#company_id").html();
                          $("#company_id").html(option);
                        } else {
                          option += "<option>-Select Company-</option>";
                          $("#company_id").html(option);
                        }
                      }
                    );
                  } else {
                  }
                }
              );
            }
          );
  
          var url = serverURL + "countries/countryList?pageNo=0&pageSize=100000";
          controller.getAuthRequest(url, true, function (data, status) {
            if (data.length > 0) {
              var option = "";
              option += "<option>-Select Option-</option>";
  
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              }
  
              // $('#countryOfTransit_id').html();
              // $('#countryOfTransit_id').html(option);
  
              $("#countryOfDestination_id").html();
              $("#countryOfDestination_id").html(option);
  
              $("#countryOfOrigin_id").html();
              $("#countryOfOrigin_id").html(option);
            } else {
              option += "<option>-Select Option-</option>";
              $("#countryOfOrigin_id").html(option);
  
              $("#countryOfDestination_id").html(option);
              // $('#countryOfTransit_id').html(option);
            }
          });
        } catch (error) {}
      }
  
      if (formName == "exporterFarm") {
        setTimeout(function () {
          $(".buttonshowMapdiv_holder").hide();
        }, 100);
      }
      if (formName == "facilitycommodities") {
        $(".quarantineFacility_id_holder").hide();
      }
      if (
        formName == "quarantineRequesteProduct" ||
        formName == "tradingBlock" ||
        formName == "quarantineFacility" ||
        formName == "exporterConsignment" ||
        formName == "onetime_export" ||
        formName == "onetime_import" ||
        formName == "pip_applicationrequest" ||
        formName == "quarantineFacility"
      ) {
        setTimeout(function () {
          $(".save").hide();
        }, 400);
      }
      if (
        formName == "wfWorkflow" ||
        formName == "wFDepartment" ||
        formName == "wFDepartment" ||
        formName == "wFNode" ||
        formName == "wFTransition"
      ) {
        controller.renderAddFormTabsEnabled(formName, function (response) {
          formHTML = response[0];
          loadTableobj = response[1];
          $("#listings_edit_" + formName).show();
          $(".crud_form." + formName).append($("#listings_edit_" + formName));
          $("#listings_edit_" + formName).html(formHTML);
          controller.initActions();
          controller.initializeDateFields(formName);
          controller.validateOnAdd(formName);
          var currentObj = allFormObj[formName];
          tab = currentObj.Mytabs;
          tabLength = tab.length;
          if (tabLength > 0) {
            var cnt = 0;
            $("*[data-tab]").each(function () {
              cnt++;
              var val = $(this).attr("data-tab");
              if (cnt > 1) {
                var t = cnt - 1;
                controller.manualTabClick(val, cnt);
              }
            });
          }
          if (formName == "pipApplicationVarietyRequest") {
            try {
              var expportervarietyid =
                allFormObj["selected"]["pipApplicationRequestID"];
              if (expportervarietyid == undefined) {
                $(
                  "#pipApplicationVarietyRequest_form #pipApplicationRequestID"
                ).val(
                  allFormObj["parent_selected"]["pipApplicationRequest"][
                    "pipApplicationRequestID"
                  ]
                );
              } else {
                $("#pipApplicationVarietyRequest_form #country_of_origin_id").val(
                  allFormObj["selected"]["countryOfOrigin"]["country_id"]
                );
                $(
                  "#pipApplicationVarietyRequest_form #pipApplicationRequestID"
                ).val(allFormObj["selected"]["pipApplicationRequestID"]);
              }
            } catch (error) {}
          }
          if (formName == "exporterConsignmentVarietyDetails") {
            localStorage.removeItem("countryid");
            var countryid;
            try {
              countryid =
                allFormObj["selected"]["exporterConsignment"][
                  "countryOfDestination"
                ]["country_id"];
            } catch (error) {
              countryid =
                allFormObj["selected"]["countryOfDestination"]["country_id"];
            }
            $("#countryofdestination_id").val(countryid);
            localStorage.setItem("countryid", countryid);
          }
          if (formName == "tradingcountry") {
            var tradingcountry;
            try {
              tradingcountry = allFormObj["selected"]["trading_block_id"];
              localStorage.setItem("tradingcountry", tradingcountry);
            } catch (error) {
              tradingcountry = allFormObj["selected"]["trading_block_id"];
              localStorage.setItem("tradingcountry", tradingcountry);
            }
            $("#trading_block_id").val(tradingcountry);
          }
          if (formName == "facilitycommodities") {
            $("#facilitycommodities_form #quarantineFacilityId").val(
              allFormObj["selected"]["quarantineFacilityID"]
            );
          }
          if (formName == "exporterFarmproducts") {
            $("#exporterFarmproducts_form #exporterFarmId").val(
              allFormObj["selected"]["exporterFarm"]["exporterFarmID"]
            );
          }
          if (formName == "exporterFarmproducts") {
            $("#exporterFarmproducts_form #exporterFarmId").val(
              allFormObj["selected"]["exporterFarmID"]
            );
          }
          if (formName == "exporterFarmproducts") {
            var expoertfamid = allFormObj["selected"]["exporterFarmID"];
            $("#exporterFarmId").val(expoertfamid);
          }
          if (formName == "facilitycommoditiesrequest") {
            $(
              "#facilitycommoditiesrequest_form #quarantineFacilityProductRequestId"
            ).val(
              allFormObj["selected"]["quarantine_facility_product_request_id"]
            );
          }
        });
      } else {
        if ($(e).parents(".vertical-form-layout").length) {
        } else {
          try {
            allFormObj["parent_selected"] = "{}";
            delete allFormObj["parent_selected"];
          } catch (e) {}
        }
        controller.renderAddForm(formName, function (response) {
          formHTML = response[0];
          loadTableobj = response[1];
          $("#listings_edit_" + formName).show();
          $(".crud_form." + formName).append($("#listings_edit_" + formName));
          $("#listings_edit_" + formName).html(formHTML);
          controller.initActions();
          controller.initializeDateFields(formName);
          controller.validateOnAdd(formName);
          var currentObj = allFormObj[formName];
          tab = currentObj.Mytabs;
          tabLength = tab.length;
          if (tabLength > 0) {
            var cnt = 0;
            $("*[data-tab]").each(function () {
              cnt++;
              var val = $(this).attr("data-tab");
              if (cnt > 1) {
                var t = cnt - 1;
                controller.manualTabClick(val, cnt);
              }
            });
          }
          if (formName == "exporter") {
            try {
              $("#company\\.name").val(userObj.company.name);
              $("#company\\.email").val(userObj.company.email);
              $("#company\\.PIN").val(userObj.company.pin);
              $("#company\\.companyRegistratioNo").val(
                userObj.company.companyRegistratioNo
              );
              $("#company\\.entityType\\.name").val(
                userObj.company.entityType.name
              );
              $("#company\\.registrationDate").val(
                userObj.company.registrationDate
              );
              controller.requestWithToken(
                serverURL + "api/validateuser",
                function (data1, status) {
                  $("#address\\.buildingName").val(data1.address.buildingName);
                  $("#address\\.city").val(data1.address.city);
                  $("#address\\.plotNo").val(data1.address.plotNo);
                  $("#address\\.postalAddress").val(data1.address.postalAddress);
                  $("#address\\.postalCode").val(data1.address.postalCode);
                  $("#address\\.subCounty\\.county\\.name").val(
                    data1.address.subCounty.county.name
                  );
                  $("#address\\.subCounty\\.name").val(
                    data1.address.subCounty.name
                  );
                  $("#address\\.ward\\.name").val(data1.address.ward.name);
                }
              );
            } catch (e) {}
          }
          if (formName == "pipApplicationVarietyRequest") {
            try {
              var expportervarietyid =
                allFormObj["selected"]["pipApplicationRequestID"];
              if (expportervarietyid == undefined) {
                $(
                  "#pipApplicationVarietyRequest_form #pipApplicationRequestID"
                ).val(
                  allFormObj["parent_selected"]["pipApplicationRequest"][
                    "pipApplicationRequestID"
                  ]
                );
              } else {
                $("#pipApplicationVarietyRequest_form #country_of_origin_id").val(
                  allFormObj["selected"]["countryOfOrigin"]["country_id"]
                );
                $(
                  "#pipApplicationVarietyRequest_form #pipApplicationRequestID"
                ).val(allFormObj["selected"]["pipApplicationRequestID"]);
              }
            } catch (error) {}
          }
          if (formName == "consignmentInspectionRequest") {
            controller.requestWithToken(
              serverURL + "importer/getImporterByCompanyID",
              function (data1, status) {
                var importerID = data1[0].importerID;
                var url =
                  serverURL +
                  "pipApplication/getApprovedPIPApplicationByImporter?importerID=" +
                  importerID;
                controller.setUpObjInitializeSpecificOne(url, "pipApplication");
              }
            );
          }
          if (formName == "exporterConsignmentVarietyDetails") {
            var countryid;
            try {
              countryid =
                allFormObj["selected"]["exporterConsignment"][
                  "countryOfDestination"
                ]["country_id"];
              $("#countryofdestination_id").val(countryid);
              localStorage.setItem("countryid", countryid);
            } catch (error) {}
          }
          if (formName == "consolidatedExportConsignmentLines") {
            var countryID = localStorage.getItem("country_id");
            var url =
              serverURL +
              "exporterConsignment/getIssuedExporterConsignmentByCountryOfDestination?countryID=" +
              countryID +
              "";
            controller.setUpObjInitializeSpecificOne(
              url,
              "exporterConsignment",
              function () {}
            );
          }
          if (formName == "tradingcountry") {
            var tradingcountry;
            try {
              tradingcountry = allFormObj["selected"]["trading_block_id"];
              $("#trading_block_id").val(tradingcountry);
              localStorage.setItem("tradingcountry", tradingcountry);
            } catch (error) {}
          }
          if (formName == "tradingcountry") {
            var tradingcountry;
            try {
              tradingcountry =
                allFormObj["selected"]["tradingBlock"]["trading_block_id"];
              $("#trading_block_id").val(tradingcountry);
              localStorage.setItem("tradingcountry", tradingcountry);
            } catch (error) {}
          }
          if (formName == "exporterFarmproducts") {
            var exporterFarmId;
            try {
              exporterFarmId = allFormObj["selected"]["exporterFarmID"];
              $("#exporterFarmId").val(exporterFarmId);
              localStorage.setItem("exporterFarmId", exporterFarmId);
            } catch (error) {}
          }
          if (formName == "exporterFarmproducts") {
            var exporterFarmId;
            try {
              exporterFarmId =
                allFormObj["selected"]["exporterFarm"]["exporterFarmID"];
              $("#exporterFarmId").val(exporterFarmId);
              localStorage.setItem("exporterFarmId", exporterFarmId);
            } catch (error) {}
          }
          if (formName == "facilitycommodities") {
            $("#facilitycommodities_form #quarantineFacilityId").val(
              allFormObj["selected"]["quarantineFacilityID"]
            );
          }
          if (formName == "facilitycommoditiesrequest") {
            $(
              "#facilitycommoditiesrequest_form #quarantineFacilityProductRequestId"
            ).val(
              allFormObj["selected"]["quarantine_facility_product_request_id"]
            );
          }
        });
      }
    },
    initializeDateFields: function (formName) {
      var currentObj = allFormObj[formName];
      var dates = currentObj.dateFields;
      if (formName == "agent_mgt") {
        for (x in dates) {
          var dateInputID = "#" + dates[x];
          if (dates[x] == "start_date" || dates[x] == "end_date") {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID)
              .datepicker({
                dateFormat: "yy-mm-dd",
                changeMonth: true,
                changeYear: true,
                minDate: "today",
                defaultDate: "today",
                minDate: new Date(),
              })
              .datepicker("setDate", "now");
          } else {
            try {
              var formattedDate = controller.formatDate($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datepicker({
              changeMonth: true,
              changeYear: true,
              dateFormat: "yy-mm-dd",
              minDate: "today",
              minDate: new Date(),
            });
          }
          if (dates[x] == "end_date") {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datepicker({
              dateFormat: "yy-mm-dd",
            });
          } else {
            try {
              var formattedDate = controller.formatDate($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datepicker({
              dateFormat: "yy-mm-dd",
            });
          }
        }
      } else {
        for (x in dates) {
          var dateInputID = "#" + dates[x];
          if (dates[x] == "departureDate") {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              timeFormat: "hh:mm tt",
              changeYear: true,
              minDate: 0,
              timeFormat: "HH:mm tt",
            });
          } else if (dates[x] == "proposedInspectionDate") {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datepicker({
              changeMonth: true,
              changeYear: true,
              dateFormat: "yy-mm-dd",
              minDate: "today",
              minDate: new Date(),
            });
          } else if (dates[x] == "company.registrationDate") {
            var dateInputID = "#" + dates[x];
            try {
              var formattedDate = controller.formatDate($(dateInputID).html());
              $(dateInputID).html(formattedDate);
            } catch (e) {}
            try {
              var formattedDate = controller.formatDate($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
          } else if (
            dates[x] == "treatmentDate" ||
            dates[x] == "treatmentDate_2"
          ) {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              timeFormat: "hh:mm tt",
              changeYear: true,
            });
          } else if (
            dates[x] == "preferedInspectionDate" ||
            dates[x] == "preferedInspectionDate_2" ||
            dates[x] == "preferedInspectionDate_val" ||
            dates[x] == "preferedInspectionDateval"
          ) {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
  
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              timeFormat: "HH:mm tt",
              changeYear: true,
              minDate: 0,
            });
          } else if (
            dates[x] == "departureDate" ||
            dates[x] == "departureDate_2"
          ) {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              timeFormat: "HH:mm tt",
              changeYear: true,
              minDate: 0,
            });
          } else if (
            dates[x] == "start_date" ||
            dates[x] == "end_date" ||
            dates[x] == "start_date_2" ||
            dates[x] == "end_date_2"
          ) {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            var dateNow = new Date();
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              changeYear: true,
              minDate: 0,
              maxDate: new Date("2099-12-31"),
            });
          } else if (dates[x] == "end_date") {
            try {
              var formattedDate = controller.formatDateTime($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datetimepicker({
              dateFormat: "yy-mm-dd",
              timeFormat: "hh:mm tt",
              changeYear: true,
              minDate: 0,
              defaultDate: "2021-10-19 11:23 am",
              disabled: true,
            });
          } else {
            try {
              var formattedDate = controller.formatDate($(dateInputID).val());
              $(dateInputID).val(formattedDate);
            } catch (e) {}
            $(dateInputID).datepicker({
              dateFormat: "yy-mm-dd",
              changeYear: true,
              yearRange: "1900:2099",
            });
          }
        }
      }
    },
    initActions: function () {
      $(".save").click(function (event) {
        $(".save").prop("disabled", true);
        $(".save").attr("disabled", true);
        $(".save").html("Saving Record... Please Wait!");
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        if (!event.detail || event.detail == 1) {
          if (!clicked) {
            clicked = true;
            controller.save(this);
            setTimeout(function () {
              clicked = false;
              $(".save").attr("disabled", false);
              $(".save").html("Save");
            }, 1000);
          } else {
            $(".save").attr("disabled", false);
            $(".save").html("Save");
          }
        } else {
          $(".save").attr("disabled", false);
          $(".save").html("Save");
        }
      });
      $(".saveRecord").click(function (event) {
        $(".saveRecord").prop("disabled", true);
        $(".saveRecord").attr("disabled", true);
        $(".saveRecord").html("Saving Record... Please Wait!");
        event.stopImmediatePropagation();
        event.stopPropagation();
        event.preventDefault();
        if (!event.detail || event.detail == 1) {
          if (!clicked) {
            clicked = true;
            controller.save(this);
            setTimeout(function () {
              clicked = false;
              $(".saveRecord").attr("disabled", false);
              $(".saveRecord").html("Save");
            }, 2000);
          } else {
            $(".saveRecord").attr("disabled", false);
            $(".saveRecord").html("Save");
          }
        } else {
          $(".saveRecord").attr("disabled", false);
          $(".saveRecord").html("Save");
        }
      });
      $(".crudAddreprintbtn")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            controller.show_progress();
            controller.getPipreprintDetails();
            $(".crudAddReprint").modal("show");
            $("#crudAddReprintbtn").click(function (event) {
              event.stopImmediatePropagation();
              event.stopPropagation();
              event.preventDefault();
              var pipApplicationID =
                document.getElementById("pipApplicationID").value;
              var reason = document.getElementById("reasonForreprint").value;
              if (
                pipApplicationID == null ||
                (pipApplicationID == "" && reason == null) ||
                reason == ""
              ) {
                controller.showToastMsg(
                  "Kindly Select Document Number And Add Reason",
                  "#ff6666"
                );
              } else {
                controller.addPipReprintRecord(pipApplicationID, reason);
                $(".modal.fade.crudAddReprint").modal("hide");
                $("#raise_reprint_form").get(0).reset();
                $("#raise_reprint_form")[0].reset();
              }
            });
          }
        });
      $(".crudAddPhytoreprintbtn")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            controller.getPhytopreprintDetails();
            $(".crudAddReprint").modal("show");
            $("#crudAddReprintbtn").click(function (event) {
              event.stopImmediatePropagation();
              event.stopPropagation();
              event.preventDefault();
              var exporterConsignmentID =
                document.getElementById("pipApplicationID").value;
              var reason = document.getElementById("reasonForreprint").value;
              if (
                exporterConsignmentID == null ||
                (exporterConsignmentID == "" && reason == null) ||
                reason == ""
              ) {
                controller.showToastMsg(
                  "Kindly Select Document Number And Add Reason",
                  "#ff6666"
                );
              } else {
                controller.addphytoReprintRecord(exporterConsignmentID, reason);
                $(".modal.fade.crudAddReprint").modal("hide");
                $("#raise_reprint_form").get(0).reset();
                $("#raise_reprint_form")[0].reset();
              }
            });
          }
        });
      $(".crudAddPhytoreprintByUserbtn")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            controller.getPhytopreprintDetailsByExporter();
            $(".crudAddReprint").modal("show");
            $("#crudAddReprintbtn").click(function (event) {
              event.stopImmediatePropagation();
              event.stopPropagation();
              event.preventDefault();
              var exporterConsignmentID =
                document.getElementById("pipApplicationID").value;
              var reason = document.getElementById("reasonForreprint").value;
              if (
                exporterConsignmentID == null ||
                (exporterConsignmentID == "" && reason == null) ||
                reason == ""
              ) {
                controller.showToastMsg(
                  "Kindly Select Document Number And Add Reason",
                  "#ff6666"
                );
              } else {
                controller.addphytoReprintRecord(exporterConsignmentID, reason);
                $(".modal.fade.crudAddReprint").modal("hide");
                $("#raise_reprint_form").get(0).reset();
                $("#raise_reprint_form")[0].reset();
              }
            });
          }
        });
      $(".crudAddImportConsReprintbtn")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            controller.getImportConsignmentReprintDetails();
            $(".crudAddReprint").modal("show");
            $("#crudAddReprintbtn").click(function (event) {
              event.stopImmediatePropagation();
              event.stopPropagation();
              event.preventDefault();
              var recordID = document.getElementById("pipApplicationID").value;
              var reason = document.getElementById("reasonForreprint").value;
              if (
                recordID == null ||
                (recordID == "" && reason == null) ||
                reason == ""
              ) {
                controller.showToastMsg(
                  "Kindly Select Document Number And Add Reason",
                  "#ff6666"
                );
              } else {
                controller.addImporterConsigmentReprintRecord(recordID, reason);
                $(".modal.fade.crudAddReprint").modal("hide");
                $("#raise_reprint_form").get(0).reset();
                $("#raise_reprint_form")[0].reset();
              }
            });
          }
        });
      $(".addRecord")
        .off("click")
        .on("click", function (event) {
          if (!event.detail || event.detail == 1) {
            if ($(this).parents(".new-form-identifier").length) {
              $(".main-form-action .save").click();
            } else {
              var formName = $(this).attr("form-name");
              if (formName == "exporterFarm") {
                document.getElementsByClassName(
                  "crud_section_lines"
                )[0].style.display = "none";
              }
              controller.addRecord(this);
            }
          }
        });
      $(".upload-document")
        .off("click")
        .on("click", function (event) {
          $(".paymentInitiatorAttachment").modal("show");
        });
      $(".filterinspectionsRecords")
        .off("click")
        .on("click", function (event) {
          $(".filterinspectionsRecordss").modal("show");
          var listUrlLink = null;
          var fmurl = serverURL + "exporterFarm/search?";
          $("#selectinspectionfilter").change(function () {
            var selectfilter = document.getElementById(
              "selectinspectionfilter"
            ).value;
            var select;
            var status;
            var docstatus;
            var dateselect;
            var datevalidityselect;
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docstatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatus").html(option);
                  $("#docstatus").html(option);
                }
              });
            }
            if (selectfilter == "10001") {
              $("#inspectionStatusdiv").show();
            }
            if (selectfilter == "10003") {
              $("#createddatediv").show();
              $("#createddateoperator").show();
            }
            if (selectfilter == "10004") {
              $("#validitydiv").show();
              $("#validityinpudatediv").show();
            }
            $("#docstatus").change(function () {
              select = document.getElementById("docstatus");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#dateselect").change(function () {
              select = document.getElementById("dateselect");
              var date = document.getElementById("createddate").value;
              dateselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(date);
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "&createdAt" + date;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#datevalidselect").change(function () {
              select = document.getElementById("datevalidselect");
              var datevalidity = document.getElementById("validity").value;
              datevalidityselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(datevalidity);
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "&createdAt" + datevalidity;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#btnFilter").click(function (e) {
              $(".filterinspectionsRecords").modal("hide");
              listUrlLink = fmurl;
              var docstatus = $("#docstatus :selected").text();
              var date = document.getElementById("createddate").value;
              var datevalidity = document.getElementById("validity").value;
              if (
                docstatus != null ||
                (docstatus != "" && date != null) ||
                date != ""
              ) {
                formObj.listUrl = listUrlLink +=
                  "docStatus.name=" + docstatus + "&createdAt=" + date;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              } else {
                var docstatuss = "docStatus.name" + docstatus;
                var dateselectss = "&createdAt=" + date;
                formObj.listUrl = listUrlLink += docstatuss || dateselectss;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              }
            });
          });
        });
      $(".filterexporterFirmRecords")
        .off("click")
        .on("click", function (event) {
          $(".filterFirmsRecordss").modal("show");
          var listUrlLink = null;
          var fmurl = serverURL + "exporterFirm/search?";
          $("#selectinspectionfilter").change(function () {
            var selectfilter = document.getElementById(
              "selectinspectionfilter"
            ).value;
            var select;
            var status;
            var docstatus;
            var dateselect;
            var datevalidityselect;
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docstatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatus").html(option);
                  $("#docstatus").html(option);
                }
              });
            }
            if (selectfilter == "10001") {
              $("#inspectionStatusdiv").show();
            }
            if (selectfilter == "10003") {
              $("#createddatediv").show();
              $("#createddateoperator").show();
            }
            if (selectfilter == "10004") {
              $("#validitydiv").show();
              $("#validityinpudatediv").show();
            }
            $("#docstatus").change(function () {
              select = document.getElementById("docstatus");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#dateselect").change(function () {
              select = document.getElementById("dateselect");
              var date = document.getElementById("createddate").value;
              dateselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(date);
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "&createdAt" + date;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#datevalidselect").change(function () {
              select = document.getElementById("datevalidselect");
              var datevalidity = document.getElementById("validity").value;
              datevalidityselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(datevalidity);
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "&createdAt" + datevalidity;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#btnFilter").click(function (e) {
              $(".filterinspectionsRecords").modal("hide");
              listUrlLink = fmurl;
              var docstatus = $("#docstatus :selected").text();
              var date = document.getElementById("createddate").value;
              var datevalidity = document.getElementById("validity").value;
              if (
                docstatus != null ||
                (docstatus != "" && date != null) ||
                date != ""
              ) {
                formObj.listUrl = listUrlLink +=
                  "docStatus.name=" + docstatus + "&createdAt=" + date;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              } else {
                var docstatuss = "docStatus.name" + docstatus;
                var dateselectss = "&createdAt=" + date;
                formObj.listUrl = listUrlLink += docstatuss || dateselectss;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              }
            });
          });
        });
      $(".filterinLRCRecords")
        .off("click")
        .on("click", function (event) {
          $(".filterLRCRecordss").modal("show");
          var listUrlLink = null;
          var urllrc = serverURL + "exporterLowRiskCommodity/search?";
          $("#selectinspectionfilter").change(function () {
            var selectfilter = document.getElementById(
              "selectinspectionfilter"
            ).value;
            var select;
            var status;
            var docstatus;
            var dateselect;
            var datevalidityselect;
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docstatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatus").html(option);
                  $("#docstatus").html(option);
                }
              });
            }
            if (selectfilter == "10001") {
              $("#inspectionStatusdiv").show();
            }
            if (selectfilter == "10003") {
              $("#createddatediv").show();
              $("#createddateoperator").show();
            }
            if (selectfilter == "10004") {
              $("#validitydiv").show();
              $("#validityinpudatediv").show();
            }
            $("#docstatus").change(function () {
              select = document.getElementById("docstatus");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#dateselect").change(function () {
              select = document.getElementById("dateselect");
              var date = document.getElementById("createddate").value;
              dateselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(date);
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "=createdAt" + dateselect + date;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#datevalidselect").change(function () {
              select = document.getElementById("datevalidselect");
              var datevalidity = document.getElementById("validity").value;
              datevalidityselect = select.options[select.selectedIndex].value;
              controller.formatDateFilter(datevalidity);
              listUrlLink = fmurl;
              formObj.listUrl =
                listUrlLink + "=createdAt" + dateselect + datevalidity;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#btnFilter").click(function (e) {
              $(".filterinspectionsRecords").modal("hide");
              listUrlLink = fmurl;
              var docstatus = $("#docstatus :selected").text();
              var date = document.getElementById("createddate").value;
              var datevalidity = document.getElementById("validity").value;
              if (
                docstatus != null ||
                (docstatus != "" && date != null) ||
                (date != "" && datevalidity != "")
              ) {
                formObj.listUrl = listUrlLink +=
                  "=docStatus.name=" +
                  docstatus +
                  "and" +
                  "createdAt" +
                  dateselect +
                  date +
                  "and" +
                  "validUntil" +
                  datevalidityselect +
                  datevalidity;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              } else {
                var docstatuss = "&docStatus.name" + docstatus;
                var dateselectss = "&createdAt" + dateselect;
                var dateselectss = "&createdAt" + dateselect;
                formObj.listUrl = listUrlLink += docstatuss || dateselectss;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              }
            });
          });
        });
      $(".filterImportConsignmentRecords")
        .off("click")
        .on("click", function (event) {
          $(".filterConsignmentInspectionRecordss").modal("show");
          var listUrlLink = null;
          var urlimpcons = serverURL + "consignmentInspectionRequest/search?";
          $("#selectphytofilter").change(function () {
            var selectfilter = document.getElementById("selectphytofilter").value;
            var select;
            var placeofissue;
            var docstatus;
            var desistantion;
            var inspectionLocation;
            var require_lab;
            if (selectfilter == "10001") {
              var url =
                serverURL +
                "officeLocation/officeLocationList?pageNo=0&pageSize=100";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Option--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].office_location_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#placeofissue").html(option);
                  $("#placeofissue").html(option);
                }
              });
            }
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docStatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatusslect").html();
                  $("#docstatusslect").html(option);
                }
              });
            }
            if (selectfilter == "10005") {
              var url =
                serverURL +
                "inspectionLocation/inspectionLocationList?pageNo=0&pageSize=10000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Option--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].inspection_location_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#inspectionLocation").html(option);
                  $("#inspectionLocation").html(option);
                }
              });
            }
            if (selectfilter == "10004") {
              $("#desistantiondvv").show();
            }
            if (selectfilter == "10003") {
              var url =
                serverURL + "countries/countryList?pageNo=0&pageSize=100000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Country--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#desistantion").html(option);
                  $("#desistantion").html(option);
                }
              });
            }
            $("#placeofissue").change(function () {
              select = document.getElementById("placeofissue");
              placeofissue = select.options[select.selectedIndex].text;
              listUrlLink = urlimpcons;
              formObj.listUrl = listUrlLink +=
                "officeLocation.name=" + placeofissue;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#inspectionLocation").change(function () {
              select = document.getElementById("inspectionLocation");
              inspectionLocation = select.options[select.selectedIndex].text;
              listUrlLink = urlimpcons;
              formObj.listUrl = listUrlLink +=
                "inspectionLocation.name=" + inspectionLocation;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#docstatusslect").change(function () {
              select = document.getElementById("docstatusslect");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = urlimpcons;
              formObj.listUrl = listUrlLink + "&docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#require_lab").change(function () {
              select = document.getElementById("require_lab");
              require_lab = select.options[select.selectedIndex].value;
              listUrlLink = urlimpcons;
              formObj.listUrl = listUrlLink += "require_lab=" + require_lab;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
          });
        });
      $(".filterphytoRecord")
        .off("click")
        .on("click", function (event) {
          $(".filterphytobyParameters").modal("show");
          var listUrlLink = null;
          var fmurl = serverURL + "exporterConsignment/searchConsignment?";
          $("#selectphytofilter").change(function () {
            var selectfilter = document.getElementById("selectphytofilter").value;
            var select;
            var placeofissue;
            var docstatus;
            var desistantion;
            var originalcountry;
            var seed;
            if (selectfilter == "10001") {
              var url =
                serverURL +
                "officeLocation/officeLocationList?pageNo=0&pageSize=100";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Option--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].office_location_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#placeofissue").html(option);
                  $("#placeofissue").html(option);
                }
              });
            }
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docstatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatus").html(option);
                  $("#docstatus").html(option);
                }
              });
            }
            if (selectfilter == "10004") {
              $("#desistantiondvv").show();
            }
            if (selectfilter == "10003") {
              var url =
                serverURL + "countries/countryList?pageNo=0&pageSize=100000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Country--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#desistantion").html(option);
                  $("#desistantion").html(option);
                }
              });
            }
            if (selectfilter == "10005") {
              $("#consignmentWeightdiv").show();
            }
            $("#placeofissue").change(function () {
              select = document.getElementById("placeofissue");
              placeofissue = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink +=
                "placeOfIssue.name=" + placeofissue;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#docstatus").change(function () {
              select = document.getElementById("docstatus");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#desistantion").change(function () {
              select = document.getElementById("desistantion");
              desistantion = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink +=
                "countryOfDestination.name=" + desistantion;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#seedApplication").change(function () {
              select = document.getElementById("seedApplication");
              seed = select.options[select.selectedIndex].value;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink += "seedApplication=" + seed;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#btnFilter").click(function (e) {
              $(".filterbyParameters").modal("hide");
              $("#quantityselectdiv").hide();
              var consweight = document.getElementById("consignmentWeight").value;
              listUrlLink = fmurl;
              var placeofissue = $("#placeofissue :selected").text();
              var desistantion = $("#desistantion :selected").text();
              var docstatus = $("#docstatus :selected").text();
              var seed = $("#seedApplication :selected").value();
              if (
                placeofissue != null ||
                (placeofissue != "" && docstatus != null) ||
                (docstatus != "" && seed != null) ||
                (seed != "" && desistantion != null) ||
                desistantion != ""
              ) {
                formObj.listUrl = listUrlLink +=
                  "placeOfIssue.name=" +
                  placeofissue +
                  "&docStatus.name=" +
                  docstatus +
                  "&countryOfDestination.name=" +
                  desistantion +
                  "&seedApplication=" +
                  seed +
                  "&consignmentWeight=" +
                  consweight;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              } else {
                var placeofIssue = "&placeOfIssue.name=" + placeofissue;
                var docstatuss = "&docStatus.name" + docstatus;
                var desistantionn = "&countryOfDestination.name=" + desistantion;
                var seed = "&seedApplication=" + seed;
                var consweightt = "&consignmentWeight=" + consweight;
                formObj.listUrl = listUrlLink +=
                  placeofIssue ||
                  docstatuss ||
                  seed ||
                  desistantionn ||
                  consweightt;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              }
            });
          });
        });
      $(".filterRecord")
        .off("click")
        .on("click", function (event) {
          $(".filterbyParameters").modal("show");
          var listUrlLink = null;
          var fmurl = serverURL + "pipApplication/searchPip?";
          $("#selectfilter").change(function () {
            var selectfilter = document.getElementById("selectfilter").value;
            var select;
            var placeofissue;
            var docstatus;
            var desistantion;
            var originalcountry;
            var product;
            if (selectfilter == "10001") {
              var url =
                serverURL +
                "officeLocation/officeLocationList?pageNo=0&pageSize=100";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Option--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].office_location_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#placeofissue").html(option);
                  $("#placeofissue").html(option);
                }
              });
            }
            if (selectfilter == "10002") {
              var url =
                serverURL + "docStatus/docStatusList?pageNo=0&pageSize=1000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Status--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].docstatus_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#docstatus").html(option);
                  $("#docstatus").html(option);
                }
              });
            }
            if (selectfilter == "10003") {
              var url =
                serverURL + "countries/countryList?pageNo=0&pageSize=100000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Country--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].country_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#desistantion").html(option);
                  $("#desistantion").html(option);
                }
              });
            }
            if (selectfilter == "10004") {
              var url =
                serverURL + "product/productList?pageNo=0&pageSize=100000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Product--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].products_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#producst").html(option);
                  $("#producst").html(option);
                }
              });
            }
            if (selectfilter == "10005") {
              var url =
                serverURL + "countries/countryList?pageNo=0&pageSize=100000";
              controller.getAuthRequest(url, true, function (data, status) {
                var option = $("<option>--Select Origin--</option>");
                for (var i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].products_id +
                    ">" +
                    data[i].name +
                    "</option>";
                  $("#originalcountry").html(option);
                  $("#originalcountry").html(option);
                }
              });
            }
            $("#placeofissue").change(function () {
              select = document.getElementById("placeofissue");
              placeofissue = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink +=
                "placeOfIssue.name=" + placeofissue;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#docstatus").change(function () {
              select = document.getElementById("docstatus");
              docstatus = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink + "docStatus.name=" + docstatus;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#desistantion").change(function () {
              select = document.getElementById("desistantion");
              desistantion = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink +=
                "countryOfDestination.name=" + desistantion;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#originalcountry").change(function () {
              select = document.getElementById("originalcountry");
              originalcountry = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink +=
                "countryOfOrigin.name=" + originalcountry;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#producst").change(function () {
              select = document.getElementById("producst");
              Commodity = select.options[select.selectedIndex].text;
              listUrlLink = fmurl;
              formObj.listUrl = listUrlLink += "product.name=" + product;
              controller.renderCRUDForm("crud_section", formObj, function () {});
            });
            $("#btnFilter").click(function (e) {
              $(".filterbyParameters").modal("hide");
              $("#quantityselectdiv").hide();
              listUrlLink = fmurl;
              var placeofissue = $("#placeofissue :selected").text();
              var desistantion = $("#desistantion :selected").text();
              var docstatus = $("#docstatus :selected").text();
              var producst = $("#producst :selected").text();
              if (
                placeofissue != null ||
                (placeofissue != "" && docstatus != null) ||
                (docstatus != "" && producst != null) ||
                (producst != "" && desistantion != null) ||
                desistantion != ""
              ) {
                formObj.listUrl = listUrlLink +=
                  "placeOfIssue.name=" +
                  placeofissue +
                  "&docStatus.name=" +
                  docstatus +
                  "&countryOfDestination.name=" +
                  desistantion +
                  "&product.name=" +
                  producst;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              } else {
                var placeofIssue = "&placeOfIssue.name=" + placeofissue;
                var docstatuss = "&docStatus.name" + docstatus;
                var desistantionn = "&countryOfDestination.name=" + desistantion;
                var producstt = "&product.name=" + producst;
                formObj.listUrl = listUrlLink +=
                  placeofIssue || docstatuss || producstt || desistantionn;
                controller.renderCRUDForm(
                  "crud_section",
                  formObj,
                  function () {}
                );
                return listUrlLink;
              }
            });
          });
        });
      $(".addChildRecord").on("click", function () {
        controller.addChildRecord(this);
      });
      $(".return").on("click", function () {
        if ($(this).parents(".main-form-action").length) {
        } else {
          if ($(this).parents(".new-form-identifier").length) {
          } else {
          }
        }
        var formName = $(this).attr("form-name");
        var form_identifier = formName;
        $("#listings_edit_" + formName).hide();
        controller.refreshCrudTables(form_identifier);
        try {
          $("#listings_" + formName).show();
          controller.refreshCrudTables(form_identifier);
          if (formName.startsWith("assign") || formName.startsWith("assigned")) {
            $(".crud_section_2").show();
          }
          $("#BtnuploadDocumentReports").css("visibility", "hidden");
          $("#BtnuploadDocumentReports").css("display", "none");
          $(".documents_reports_tab_link").hide();
          if (formName == "importer") {
            $(".tabulator-footer").hide();
          }
          if (formName == "assignedConsignmentInspectionRequest") {
            controller.refreshCrudTables(form_identifier);
          }
          if (formName == "exporter") {
            window.location.reload();
            $(".crud_section_2").show();
            $(".tabulator-footer").hide();
            controller.refreshExporterTable();
          } else if (formName == "exporterConsignment") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "block";
            document.getElementsByClassName("crud_section_2")[0].style.display =
              "block";
            $(".crud_section_2").show();
          }
          if (formName == "users") {
            $(".tabulator-footer").hide();
          }
          if (
            formName == "assiLowgnExporterLowRisk" ||
            formName == "assignAgentRegistration" ||
            formName == "pipapplicationreports" ||
            formName == "omassignedPIPInspection" ||
            formName == "assignQuarantineFacility" ||
            formName == "assignConsolidatedPhyto" ||
            formName == "assignedConsolidatedPhyto"
          ) {
            $(".crud_section_2").show();
          }
          if (
            formName == "assiLowgnExporterLowRisk" ||
            formName == "assignedPIPReplacementPrint"
          ) {
            $(".crud_section_2").show();
          }
          if (
            formName == "assignExporterFarm" ||
            formName == "printout_replacement" ||
            formName == "quarantine_facility_product_request" ||
            formName == "assignedQuarantineFacility"
          ) {
            $(".crud_section_2").show();
          }
          if (formName == "users") {
            $(".crud_section_2").show();
          }
          if (formName == "assignedExporterLowRisk") {
            $(".crud_section_2").show();
          }
          if (formName == "agents") {
            $(".tabulator-footer").hide();
          }
          if (
            formName == "pip_application" ||
            formName == "assignConsignmentInspection" ||
            formName == "assignedConsignmentInspectionRequest"
          ) {
            $(".crud_section_2").show();
          }
          if (formName == "assignAgentRegistration" || formName == "agents") {
            $(".crud_section_2").show();
          }
          if (formName == "quarantineFacility") {
            $(".crud_section_2").show();
          }
          if (
            formName == "assignInspection" ||
            formName == "assignPIPInspection" ||
            formName == "assignedPIPInspection" ||
            formName == "assignedPIPprinting" ||
            formName == "assignImporterInspection"
          ) {
            $(".crud_section_2").show();
          }
          if (formName == "assignedExporterFarm") {
            $(".crud_section_2").show();
          }
          if (formName == "assignedInspection") {
            $(".crud_section_3").hide();
          }
          if (formName == "exporter") {
            $(".crud_section_2").show();
          }
          if (
            formName == "assignedInspection" ||
            formName == "assignedConsignmentInspection" ||
            formName == "assignConsignmentInspection" ||
            formName == "assignedConsignmentInspectionRequest" ||
            formName == "assignConsignmentInspectionRequest" ||
            formName == "assignInspection" ||
            formName == "assignPhytoInspections" ||
            formName == "assignedPhytoInspections"
          ) {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
            $(".crud_section_2").show();
            $(".crud_section_3").show();
          } else if (formName == "assignInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignExporterFirm") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignedExporterFirm") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignExporterFarm") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignedExporterFarm") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignedExporterLowRisk") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignExporterLowRisk") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignedPhytoInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "assignPhytoInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "onetime_import") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "onetime_export") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "exporter") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
          } else if (
            formName == "assignQuarantineFacility" ||
            formName == "assignedQuarantineFacility"
          ) {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
          } else if (formName == "assignConsignmentInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
          } else if (formName == "assignInspectionRequest") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
          } else if (formName == "exporterFarmInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "quarantineFacilityInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          } else if (formName == "exporterLowRiskInspection") {
            document.getElementsByClassName(
              "crud_section_lines"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "approve_btn_inspection"
            )[0].style.display = "block";
          }
          getElementsByClassName("crud_section_lines")[0].style.display = "none";
        } catch (error) {}
      });
      $(".print_note").on("click", function () {
        controller.printNote(this);
      });
      $(".print_form").on("click", function () {
        controller.printEntity(this);
      });
      try {
        $(".multi-select").multiselect({
          includeSelectAllOption: true,
          enableFiltering: true,
          enableCaseInsensitiveFiltering: true,
        });
      } catch (e) {}
      $(".multi-select").click(function () {});
      var url = "vendor/parsleyjs/parsley.js";
      jQuery.loadScript = function (url, callback) {
        jQuery.ajax({
          url: "vendor/parsleyjs/parsley.js",
          dataType: "script",
          success: callback,
          async: true,
        });
      };
    },
    forwardBulkPayment: function (phoneNumber, action, tableRegisterId) {
      var dataActivity = stkPushRecords;
      if (action == "proceedPay") {
        for (var i = 0; i < dataActivity.length; i++) {
          dataActivity[i]["phoneNumber"] = phoneNumber;
          dataActivity[i]["recordId"] = dataActivity[i].recordId;
          dataActivity[i]["tableRegisterId"] = tableRegisterId;
        }
        var formJson = JSON.stringify(dataActivity);
        var url = serverURL + "payment/STKPush";
        var async_status = true;
        controller.mpesaRequest(
          url,
          formJson,
          async_status,
          function (data, status) {}
        );
      }
    },
  
    forwardMany: function (approver, reason) {
      var requireauditvalue;
      var remark = $("#approversremarks").val();
      var approversremarks = $.trim($("#approversremarks").val());
  
      $("#requiresfarmaudit").change(function () {
        requireauditvalue = $("#requiresfarmaudit :selected").attr("value");
      });
      var remark = $("#activityMany-setup").serializeObject();
      var remark_reject = $("#reject_activityMany-setup").serializeObject();
      $(".modal.fade.approve_Confirm_Many_form").modal("hide");
      $(".modal.fade.reject_Confirm_Many_form").modal("hide");
      var dataActivity = toBeApprovedActivity;
      if (reason == "approve") {
        for (i in dataActivity) {
          dataActivity[i].docStatus = 24;
          dataActivity[i].wfActivityID = 24;
          dataActivity[i].target_user_id = approver;
          dataActivity[i].approved = true;
          dataActivity[i].rejected = false;
          dataActivity[i].ammend = false;
          dataActivity[i].initaitor_id = dataActivity[i]["initiator_id"].users_id;
          dataActivity[i].users_id = dataActivity[i]["user"].users_id;
          dataActivity[i].wFNode_id = dataActivity[i]["wFNode"].wFNode_id;
          dataActivity[i].wfWorkflow_id =
            dataActivity[i]["wfWorkflow"].wfWorkflow_id;
          dataActivity[i].role_id = dataActivity[i]["role"].role_id;
          dataActivity[i].tableRegister_id =
            dataActivity[i]["tableRegister"].tableRegister_id;
          dataActivity[i].remarks = approversremarks;
        }
      } else if (reason == "reject") {
        var remarksforrejection = $.trim($("#remarks_value").val());
  
        console.log(
          "remarksforrejectionremarksforrejection",
          remarksforrejection
        );
  
        for (i in dataActivity) {
          dataActivity[i].docStatus = 24;
          dataActivity[i].target_user_id = approver;
          dataActivity[i].approved = false;
          dataActivity[i].rejected = true;
          dataActivity[i].ammend = false;
          dataActivity[i].initaitor_id = dataActivity[i]["initiator_id"].users_id;
          dataActivity[i].users_id = dataActivity[i]["user"].users_id;
          dataActivity[i].wFNode_id = dataActivity[i]["wFNode"].wFNode_id;
          dataActivity[i].wfWorkflow_id =
            dataActivity[i]["wfWorkflow"].wfWorkflow_id;
          dataActivity[i].role_id = dataActivity[i]["role"].role_id;
          dataActivity[i].tableRegister_id =
            dataActivity[i]["tableRegister"].tableRegister_id;
          dataActivity[i]["remarks"] = remarksforrejection;
          dataActivity[i]["rejectedWeight"] = remark_reject.rejectedWeight;
          dataActivity[i]["requiresFarmAudit"] = remark_reject.requiresfarmaudit;
          dataActivity[i]["proposedInspectionDate"] =
            remark_reject.proposedInspectionDateinput;
        }
      } else if (reason == "amend") {
        for (i in dataActivity) {
          dataActivity[i].docStatus = 24;
          dataActivity[i].target_user_id = approver;
          dataActivity[i].approved = false;
          dataActivity[i].rejected = false;
          dataActivity[i].ammend = true;
          dataActivity[i].initaitor_id = dataActivity[i]["initiator_id"].users_id;
          dataActivity[i].users_id = dataActivity[i]["user"].users_id;
          dataActivity[i].wFNode_id = dataActivity[i]["wFNode"].wFNode_id;
          dataActivity[i].wfWorkflow_id =
            dataActivity[i]["wfWorkflow"].wfWorkflow_id;
          dataActivity[i].role_id = dataActivity[i]["role"].role_id;
          dataActivity[i].tableRegister_id =
            dataActivity[i]["tableRegister"].tableRegister_id;
          dataActivity[i]["remarks"] = approversremarks;
        }
      }
      workflow.forwardWorkflow(dataActivity, function (output) {
        controller.hide_progress();
        var outputMessage = controller.sanitizeErrorMessage(output);
        var outputData = controller.sanitizeErrorData(output);
        $(".modal.fade.approve_Confirm_Many_form").modal("hide");
        $(".modal.fade.approve_Confirm_Many_form").trigger("reset");
        try {
          if (outputMessage == "SUCCESS") {
            controller.showToastMsg(outputData, "#1a5589");
            toBeApprovedActivity = [];
            document.getElementById("remarks").value = "";
          } else if (outputMessage == "EMPTY ACTIVITY") {
            controller.showToastMsg(
              "Kindly Select the record and try again",
              "#ff6666"
            );
          } else {
            controller.showToastMsg(outputData, "#ff6666");
          }
        } catch (e) {}
        controller.refreshCrudTables();
      });
    },
    renderEditFormTabsEnabled: function (
      obj,
      formName,
      editable = true,
      tabExclusion = [],
      callback
    ) {
      var currentObj = allFormObj[formName];
      try {
        if (currentObj.url_id != "tab") {
          var tab_this = $("li.active.item");
          var tabPos = tab_this.attr("data-tab");
          allFormObj["tab_" + formName] = obj;
          try {
            allFormObj["parent_selected"] = obj;
            allFormObj["selected"] = obj;
          } catch (e) {}
        } else {
          try {
            allFormObj["selected"] = "";
            allFormObj["selected"] = obj;
          } catch (e) {}
        }
      } catch (e) {}
      var tabHeaders = "";
      var mainFormHTML = "";
      var tabsFormHTML = "";
      var subTabHeaders = "";
      var mainSubFormHTML = "";
      var tab = "";
      try {
        tab = currentObj.Mytabs;
      } catch (e) {}
      var fields = "";
      try {
        fields = currentObj.fields;
      } catch (e) {}
      var dates = "";
      try {
        dates = currentObj.dateFields;
      } catch (e) {}
      var tabLength = 0;
      try {
        tabLength = tab.length;
      } catch (e) {}
      if (tabLength > 0) {
        for (i = 0; i < tab.length; i++) {
          var isActive = "";
          if (i == 0) {
            isActive = "active in";
          } else {
            isActive = "";
          }
          var enabledElem = "";
          var n = tabExclusion.includes(tab[i]["tabName"]);
          if (n) {
            enabledElem = "style='display:none;'";
          }
          tabHeaders +=
            "<li " +
            enabledElem +
            ' tab-position= "' +
            i +
            '" class="item ' +
            tab[i]["tabName"] +
            '_tab_link"' +
            isActive +
            '" data-tab="' +
            tab[i]["entityName"] +
            '"><a data-toggle="tab" href="#' +
            tab[i]["tabName"] +
            '">' +
            tab[i]["tabTitle"] +
            "</a></li>";
          let uniqueGroupNames = [
            ...new Set(fields.map((item) => item.groupName)),
          ];
          for (groupIndex in uniqueGroupNames) {
            var hasGroupField = false;
            var displayGroupName = uniqueGroupNames[groupIndex];
            if (
              displayGroupName == undefined ||
              displayGroupName == "undefined"
            ) {
              displayGroupName = "";
            }
            var subTabHeadersTmp = "";
            for (a = 0; a < fields.length; a++) {
              var fieldGroupName = fields[a]["groupName"];
              if (
                uniqueGroupNames[groupIndex] == fieldGroupName ||
                (displayGroupName == "" && uniqueGroupNames.length == 1)
              ) {
                var fieldName = fields[a]["field"];
                var fieldTitle = fields[a]["title"];
                var fieldType = fields[a]["type"];
                var fieldRelation = fields[a]["relation"];
                var fieldOptionID = fields[a]["option_id"];
                var fieldEditingID = fields[a]["editing_id"];
                if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                  fieldOptionID = "";
                }
                if (fields[a]["tab"] == tab[i]["tabName"]) {
                  hasGroupField = true;
                  if (fieldName in obj) {
                    key = fieldName;
                    subTabHeadersTmp += controller.renderFormField(
                      obj,
                      key,
                      fieldName,
                      "",
                      currentObj,
                      editable,
                      fieldOptionID,
                      fields[a]
                    );
                  } else {
                    key = fieldName;
                    if (fieldRelation) {
                      subTabHeadersTmp += controller.renderFormField(
                        obj,
                        fieldRelation,
                        fieldRelation,
                        fieldName,
                        currentObj,
                        editable,
                        fieldOptionID,
                        fields[a]
                      );
                    }
                    fieldNameArray = fieldName.split(".");
                    var identifier = "";
                    var tmp = "";
                    var pos = 0;
                    try {
                      if (fieldNameArray.length == 1) {
                        tmp = obj[fieldNameArray[0]];
                      }
                      if (fieldNameArray.length == 2) {
                        tmp = obj[fieldNameArray[0]][fieldNameArray[1]];
                      }
                      if (fieldNameArray.length == 3) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ];
                      }
                      if (fieldNameArray.length == 4) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ][fieldNameArray[3]];
                      }
                      if (fieldNameArray.length == 5) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ][fieldNameArray[3]][fieldNameArray[4]];
                      }
                    } catch (e) {}
                    if (!fieldRelation) {
                      subTabHeadersTmp += controller.renderFormFieldNested(
                        obj,
                        key,
                        fieldRelation,
                        tmp,
                        currentObj,
                        editable,
                        fieldOptionID,
                        fields[a]
                      );
                    }
                  }
                }
              }
            }
            if (hasGroupField) {
              subTabHeadersTmp =
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>" +
                subTabHeadersTmp;
            }
            subTabHeaders += subTabHeadersTmp;
          }
          tabsFormHTML +=
            '<div id="' +
            tab[i]["tabName"] +
            '" class="tab-pane fade ' +
            tab[i]["entityName"] +
            " " +
            isActive +
            '">' +
            subTabHeaders +
            "</div>";
          subTabHeaders = "";
        }
        var actionButton = controller.renderFormActions(formName, editable);
        mainSubFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          '<ul class="nav nav-tabs">' +
          tabHeaders +
          "</ul>" +
          '<div class="tab-content" style="border-style:none;">' +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</div> " +
          "</form>";
        mainFormHTML += "<div class='main-form'>" + mainSubFormHTML + "</div>";
        callback(mainFormHTML);
      } else {
        let uniqueGroupNames = [...new Set(fields.map((item) => item.groupName))];
        for (groupIndex in uniqueGroupNames) {
          var displayGroupName = uniqueGroupNames[groupIndex];
          if (displayGroupName == undefined || displayGroupName == "undefined") {
            displayGroupName = "";
          }
          tabsFormHTML +=
            "<div class='form-group col-md-12' style='float: left;'><h4>" +
            displayGroupName +
            "</h4></div>";
          for (a = 0; a < fields.length; a++) {
            var fieldGroupName = fields[a]["groupName"];
            if (
              uniqueGroupNames[groupIndex] == fieldGroupName ||
              (displayGroupName == "" && uniqueGroupNames.length == 1)
            ) {
              var fieldName = fields[a]["field"];
              var fieldTitle = fields[a]["title"];
              var fieldType = fields[a]["type"];
              var fieldRelation = fields[a]["relation"];
              var fieldOptionID = fields[a]["option_id"];
              var fieldEditingID = fields[a]["editing_id"];
              if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                fieldOptionID = "";
              }
              if (fieldName in obj) {
                key = fieldName;
                tabsFormHTML += controller.renderFormField(
                  obj,
                  key,
                  fieldName,
                  "",
                  currentObj,
                  editable,
                  fieldOptionID,
                  fields[a]
                );
              } else {
                key = fieldName;
                if (fieldRelation) {
                  tabsFormHTML += controller.renderFormField(
                    obj,
                    fieldRelation,
                    fieldRelation,
                    fieldName,
                    currentObj,
                    editable,
                    fieldOptionID,
                    fields[a]
                  );
                } else {
                }
              }
            }
          }
        }
        var actionButton = controller.renderFormActions(formName, editable);
        mainFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</form>";
        mainFormHTML = "<div class='main-form'>" + mainFormHTML + "</div>";
        callback(mainFormHTML);
      }
    },
    renderAddFormTabsEnabled: function (formName, callback) {
      editable = true;
      var tabHeaders = "";
      var mainFormHTML = "";
      var tabsFormHTML = "";
      var subTabHeaders = "";
      var mainSubFormHTML = "";
      var currentObj = allFormObj[formName];
      var tab = currentObj.Mytabs;
      var fields = currentObj.fields;
      var idType = currentObj.idType;
      var formName = currentObj.formName;
      var loadTableobj = [];
      var dates = currentObj.dateFields;
      if (tab.length) {
        if (formName == "users") {
          for (i = 0; i < tab.length; i++) {
            var isActive = "";
            if (i == 0) {
              isActive = "active in";
            } else {
              isActive = "";
            }
            tabHeaders +=
              '<li class="' +
              isActive +
              '"><a data-toggle="tab" href="#' +
              tab[i]["tabName"] +
              '">' +
              tab[i]["tabTitle"] +
              "</a></li>";
            let uniqueGroupNames = [
              ...new Set(fields.map((item) => item.groupName)),
            ];
            for (groupIndex in uniqueGroupNames) {
              var displayGroupName = uniqueGroupNames[groupIndex];
              if (
                displayGroupName == undefined ||
                displayGroupName == "undefined"
              ) {
                displayGroupName = "";
              }
              subTabHeaders +=
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>";
              for (a = 0; a < fields.length; a++) {
                var fieldGroupName = fields[a]["groupName"];
                if (
                  uniqueGroupNames[groupIndex] == fieldGroupName ||
                  (displayGroupName == "" && uniqueGroupNames.length == 1)
                ) {
                  var fieldName = fields[a]["field"];
                  var fieldTitle = fields[a]["title"];
                  var fieldType = fields[a]["type"];
                  var fieldRelation = fields[a]["relation"];
                  var fieldOptionID = fields[a]["option_id"];
                  try {
                    var select_type = fields[a]["select_type"];
                  } catch (error) {}
                  if (
                    fieldOptionID == undefined ||
                    fieldOptionID == "undefined"
                  ) {
                    fieldOptionID = "";
                  }
                  if (fields[a]["tab"] == tab[i]["tabName"]) {
                    var s_type = "";
                    if (fieldType == "select") {
                      var options = "";
                      var depends = fields[a]["depends"];
                      if (depends == true) {
                      } else {
                        if (select_type == "multiple") {
                          s_type = "multiple";
                        }
                        try {
                          options = controller.setRelationValue(
                            fieldRelation,
                            setupObj,
                            false,
                            idType,
                            fieldOptionID,
                            currentObj.formName,
                            "",
                            "",
                            editable,
                            s_type
                          );
                        } catch (e) {}
                      }
                      try {
                        var fieldObjTemp = fields[a];
                        fieldObjTemp.value = options;
                        fieldObjTemp.s_type = s_type;
                        subTabHeaders += controller.renderField(
                          fieldObjTemp,
                          currentObj.formName,
                          editable
                        );
                      } catch (e) {}
                    } else {
                      try {
                        if (fields[a] != undefined && fields[a] != "undefined") {
                          if (dates != undefined && dates != "undefined") {
                            subTabHeaders += controller.renderField(
                              fields[a],
                              currentObj.formName,
                              editable,
                              true
                            );
                          } else {
                            if (fieldType == "boolean") {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            } else {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            }
                          }
                        } else {
                        }
                      } catch (e) {}
                    }
                  }
                }
              }
            }
            tabsFormHTML +=
              '<div id="' +
              tab[i]["tabName"] +
              '" class="tab-pane fade ' +
              isActive +
              '" >' +
              subTabHeaders +
              "</div>";
            subTabHeaders = "";
          }
        } else {
          for (i = 0; i < 1; i++) {
            var isActive = "";
            if (i == 0) {
              isActive = "active in";
            } else {
              isActive = "";
            }
            tabHeaders +=
              '<li class="' +
              isActive +
              '"><a data-toggle="tab" href="#' +
              tab[i]["tabName"] +
              '">' +
              tab[i]["tabTitle"] +
              "</a></li>";
            let uniqueGroupNames = [
              ...new Set(fields.map((item) => item.groupName)),
            ];
            for (groupIndex in uniqueGroupNames) {
              var displayGroupName = uniqueGroupNames[groupIndex];
              if (
                displayGroupName == undefined ||
                displayGroupName == "undefined"
              ) {
                displayGroupName = "";
              }
              subTabHeaders +=
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>";
              for (a = 0; a < fields.length; a++) {
                var fieldGroupName = fields[a]["groupName"];
                if (
                  uniqueGroupNames[groupIndex] == fieldGroupName ||
                  (displayGroupName == "" && uniqueGroupNames.length == 1)
                ) {
                  var fieldName = fields[a]["field"];
                  var fieldTitle = fields[a]["title"];
                  var fieldType = fields[a]["type"];
                  var fieldRelation = fields[a]["relation"];
                  var fieldOptionID = fields[a]["option_id"];
                  try {
                    var select_type = fields[a]["select_type"];
                  } catch (error) {}
                  if (
                    fieldOptionID == undefined ||
                    fieldOptionID == "undefined"
                  ) {
                    fieldOptionID = "";
                  }
                  if (fields[a]["tab"] == tab[i]["tabName"]) {
                    var s_type = "";
                    if (fieldType == "select") {
                      var options = "";
                      var depends = fields[a]["depends"];
                      if (depends == true) {
                      } else {
                        if (select_type == "multiple") {
                          s_type = "multiple";
                        }
                        try {
                          options = controller.setRelationValue(
                            fieldRelation,
                            setupObj,
                            false,
                            idType,
                            fieldOptionID,
                            currentObj.formName,
                            "",
                            "",
                            editable,
                            s_type
                          );
                        } catch (e) {}
                      }
                      try {
                        var fieldObjTemp = fields[a];
                        fieldObjTemp.value = options;
                        fieldObjTemp.s_type = s_type;
                        subTabHeaders += controller.renderField(
                          fieldObjTemp,
                          currentObj.formName,
                          editable
                        );
                      } catch (e) {}
                    } else {
                      try {
                        if (fields[a] != undefined && fields[a] != "undefined") {
                          if (dates != undefined && dates != "undefined") {
                            subTabHeaders += controller.renderField(
                              fields[a],
                              currentObj.formName,
                              editable,
                              true
                            );
                          } else {
                            if (fieldType == "boolean") {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            } else {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            }
                          }
                        } else {
                        }
                      } catch (e) {}
                    }
                  }
                }
              }
            }
            tabsFormHTML +=
              '<div id="' +
              tab[i]["tabName"] +
              '" class="tab-pane fade ' +
              isActive +
              '" >' +
              subTabHeaders +
              "</div>";
            subTabHeaders = "";
          }
        }
        var actionButton = controller.renderFormActions(formName);
        mainSubFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          '<ul class="nav nav-tabs">' +
          tabHeaders +
          "</ul>" +
          '<div class="tab-content" style="border-style:none;">' +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</div> " +
          "</form>";
        mainFormHTML += "<div class='main-form'>" + mainSubFormHTML + "</div>";
        callback([mainFormHTML, loadTableobj]);
      } else {
        let uniqueGroupNames = [...new Set(fields.map((item) => item.groupName))];
        for (groupIndex in uniqueGroupNames) {
          var displayGroupName = uniqueGroupNames[groupIndex];
          if (displayGroupName == undefined || displayGroupName == "undefined") {
            displayGroupName = "";
          }
          tabsFormHTML +=
            "<div class='form-group col-md-12' style='float: left;'><h4>" +
            displayGroupName +
            "</h4></div>";
          for (a = 0; a < fields.length; a++) {
            var fieldGroupName = fields[a]["groupName"];
            if (
              uniqueGroupNames[groupIndex] == fieldGroupName ||
              (displayGroupName == "" && uniqueGroupNames.length == 1)
            ) {
              var fieldName = fields[a]["field"];
              var fieldTitle = fields[a]["title"];
              var fieldType = fields[a]["type"];
              var fieldRelation = fields[a]["relation"];
              var fieldOptionID = fields[a]["option_id"];
              if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                fieldOptionID = "";
              }
              var fieldDefault = "";
              try {
                fieldDefault = fields[a]["default"];
              } catch (e) {}
              var fieldDisabled = false;
              try {
                fieldDisabled = fields[a]["disabled"];
              } catch (e) {}
              var select_type = "";
              try {
                select_type = fields[a]["select_type"];
              } catch (e) {}
              var s_type = "";
              if (fieldType == "select") {
                if (select_type == "multiple") {
                  s_type = "multiple";
                } else {
                  s_type = "";
                }
                try {
                  if (fields[a]["relation"] == "roles") {
                    var options = controller.setRelationValue(
                      "roles",
                      setupObj,
                      false,
                      idType,
                      "roleName",
                      formName,
                      "",
                      "",
                      editable,
                      s_type
                    );
                    var fieldObjTemp = fields[a];
                    fieldObjTemp.value = options;
                    fieldObjTemp.s_type = s_type;
                    var idType = 1;
                    tabsFormHTML += controller.renderField(
                      fieldObjTemp,
                      formName,
                      editable
                    );
                  } else {
                    var options = controller.setRelationValue(
                      fieldRelation,
                      setupObj,
                      false,
                      idType,
                      fieldOptionID,
                      currentObj.formName,
                      "",
                      "",
                      editable,
                      s_type
                    );
                    var fieldObjTemp = fields[a];
                    fieldObjTemp.value = options;
                    fieldObjTemp.s_type = s_type;
                    tabsFormHTML += controller.renderField(
                      fieldObjTemp,
                      currentObj.formName,
                      editable
                    );
                  }
                } catch (e) {}
              } else {
                try {
                  if (fields[a] != undefined && fields[a] != "undefined") {
                    if (dates != undefined && dates != "undefined") {
                      tabsFormHTML += controller.renderField(
                        fields[a],
                        currentObj.formName,
                        editable
                      );
                    } else {
                      tabsFormHTML += controller.renderField(
                        fields[a],
                        currentObj.formName,
                        editable
                      );
                    }
                  }
                } catch (e) {}
              }
              try {
                var select_type = fields[a]["select_type"];
              } catch (error) {}
            }
          }
        }
        var actionButton = controller.renderFormActions(formName);
        mainFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'></br>" +
          tabsFormHTML +
          "<br>" +
          actionButton +
          "</form>";
        mainFormHTML = "<div class='main-form'>" + mainFormHTML + "</div>";
        callback([mainFormHTML, loadTableobj]);
      }
    },
    renderAddForm: function (formName, callback) {
      editable = true;
      var tabHeaders = "";
      var mainFormHTML = "";
      var tabsFormHTML = "";
      var subTabHeaders = "";
      var mainSubFormHTML = "";
      var currentObj = allFormObj[formName];
      var tab = currentObj.Mytabs;
      var fields = currentObj.fields;
      var idType = currentObj.idType;
      var formName = currentObj.formName;
      var loadTableobj = [];
      var dates = currentObj.dateFields;
      if (tab.length) {
        if (formName == "users") {
          for (i = 0; i < tab.length; i++) {
            var isActive = "";
            if (i == 0) {
              isActive = "active in";
            } else {
              isActive = "";
            }
            tabHeaders +=
              '<li class="' +
              isActive +
              '"><a data-toggle="tab" href="#' +
              tab[i]["tabName"] +
              '">' +
              tab[i]["tabTitle"] +
              "</a></li>";
            let uniqueGroupNames = [
              ...new Set(fields.map((item) => item.groupName)),
            ];
            for (groupIndex in uniqueGroupNames) {
              var displayGroupName = uniqueGroupNames[groupIndex];
              if (
                displayGroupName == undefined ||
                displayGroupName == "undefined"
              ) {
                displayGroupName = "";
              }
              subTabHeaders +=
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>";
              for (a = 0; a < fields.length; a++) {
                var fieldGroupName = fields[a]["groupName"];
                if (
                  uniqueGroupNames[groupIndex] == fieldGroupName ||
                  (displayGroupName == "" && uniqueGroupNames.length == 1)
                ) {
                  var fieldName = fields[a]["field"];
                  var fieldTitle = fields[a]["title"];
                  var fieldType = fields[a]["type"];
                  var fieldRelation = fields[a]["relation"];
                  var fieldOptionID = fields[a]["option_id"];
                  try {
                    var select_type = fields[a]["select_type"];
                  } catch (error) {}
                  if (
                    fieldOptionID == undefined ||
                    fieldOptionID == "undefined"
                  ) {
                    fieldOptionID = "";
                  }
                  if (fields[a]["tab"] == tab[i]["tabName"]) {
                    var s_type = "";
                    if (fieldType == "select") {
                      var options = "";
                      var depends = fields[a]["depends"];
                      if (depends == true) {
                      } else {
                        if (select_type == "multiple") {
                          s_type = "multiple";
                        }
                        try {
                          options = controller.setRelationValue(
                            fieldRelation,
                            setupObj,
                            false,
                            idType,
                            fieldOptionID,
                            currentObj.formName,
                            "",
                            "",
                            editable,
                            s_type
                          );
                        } catch (e) {}
                      }
                      try {
                        var fieldObjTemp = fields[a];
                        fieldObjTemp.value = options;
                        fieldObjTemp.s_type = s_type;
                        subTabHeaders += controller.renderField(
                          fieldObjTemp,
                          currentObj.formName,
                          editable
                        );
                      } catch (e) {}
                    } else {
                      try {
                        if (fields[a] != undefined && fields[a] != "undefined") {
                          if (dates != undefined && dates != "undefined") {
                            subTabHeaders += controller.renderField(
                              fields[a],
                              currentObj.formName,
                              editable,
                              true
                            );
                          } else {
                            if (fieldType == "boolean") {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            } else {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            }
                          }
                        } else {
                        }
                      } catch (e) {}
                    }
                  }
                }
              }
            }
            tabsFormHTML +=
              '<div id="' +
              tab[i]["tabName"] +
              '" class=" ' +
              isActive +
              '" >' +
              subTabHeaders +
              "</div>";
            subTabHeaders = "";
          }
        } else {
          for (i = 0; i < tab.length; i++) {
            var isActive = "";
            if (i == 0) {
              isActive = "active in";
            } else {
              isActive = "";
            }
            let uniqueGroupNames = [
              ...new Set(fields.map((item) => item.groupName)),
            ];
            for (groupIndex in uniqueGroupNames) {
              var displayGroupName = uniqueGroupNames[groupIndex];
              if (
                displayGroupName == undefined ||
                displayGroupName == "undefined"
              ) {
                displayGroupName = "";
              }
              subTabHeaders +=
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>";
              for (a = 0; a < fields.length; a++) {
                var fieldGroupName = fields[a]["groupName"];
                if (
                  uniqueGroupNames[groupIndex] == fieldGroupName ||
                  (displayGroupName == "" && uniqueGroupNames.length == 1)
                ) {
                  var fieldName = fields[a]["field"];
                  var fieldTitle = fields[a]["title"];
                  var fieldType = fields[a]["type"];
                  var fieldRelation = fields[a]["relation"];
                  var fieldOptionID = fields[a]["option_id"];
                  try {
                    var select_type = fields[a]["select_type"];
                  } catch (error) {}
                  if (
                    fieldOptionID == undefined ||
                    fieldOptionID == "undefined"
                  ) {
                    fieldOptionID = "";
                  }
                  if (fields[a]["tab"] == tab[i]["tabName"]) {
                    var s_type = "";
                    if (fieldType == "select") {
                      var options = "";
                      var depends = fields[a]["depends"];
                      if (depends == true) {
                      } else {
                        if (select_type == "multiple") {
                          s_type = "multiple";
                        }
                        try {
                          options = controller.setRelationValue(
                            fieldRelation,
                            setupObj,
                            false,
                            idType,
                            fieldOptionID,
                            currentObj.formName,
                            "",
                            "",
                            editable,
                            s_type
                          );
                        } catch (e) {}
                      }
                      try {
                        var fieldObjTemp = fields[a];
                        fieldObjTemp.value = options;
                        fieldObjTemp.s_type = s_type;
                        subTabHeaders += controller.renderField(
                          fieldObjTemp,
                          currentObj.formName,
                          editable
                        );
                      } catch (e) {}
                    } else {
                      try {
                        if (fields[a] != undefined && fields[a] != "undefined") {
                          if (dates != undefined && dates != "undefined") {
                            subTabHeaders += controller.renderField(
                              fields[a],
                              currentObj.formName,
                              editable,
                              true
                            );
                          } else {
                            if (fieldType == "boolean") {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            } else {
                              subTabHeaders += controller.renderField(
                                fields[a],
                                currentObj.formName,
                                editable,
                                true
                              );
                            }
                          }
                        } else {
                        }
                      } catch (e) {}
                    }
                  }
                }
              }
            }
            tabsFormHTML +=
              "<h2 class='vertical-form-layout-header " +
              tab[i]["tabName"] +
              "_tab_link'>" +
              tab[i]["tabTitle"] +
              "</h2>";
            tabsFormHTML +=
              '<div id="' +
              tab[i]["tabName"] +
              '" data-tab="' +
              tab[i]["entityName"] +
              '" class="new-form-identifier vertical-form-layout  ' +
              tab[i]["entityName"] +
              " " +
              tab[i]["tabName"] +
              "_tab_link" +
              '" style="position:relative;">' +
              subTabHeaders +
              "</div>";
            subTabHeaders = "";
          }
        }
        var actionButton =
          "<div class='main-form-action'>" +
          controller.renderFormActions(formName) +
          "</div>";
        mainSubFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          '<ul class="nav nav-tabs">' +
          tabHeaders +
          "</ul>" +
          '<div class="" style="border-style:none;">' +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</div> " +
          "</form>";
        mainFormHTML += "<div class='main-form'>" + mainSubFormHTML + "</div>";
        callback([mainFormHTML, loadTableobj]);
      } else {
        let uniqueGroupNames = [...new Set(fields.map((item) => item.groupName))];
        for (groupIndex in uniqueGroupNames) {
          var displayGroupName = uniqueGroupNames[groupIndex];
          if (displayGroupName == undefined || displayGroupName == "undefined") {
            displayGroupName = "";
          }
          tabsFormHTML +=
            "<div class='form-group col-md-12' style='float: left;'><h4>" +
            displayGroupName +
            "</h4></div>";
          for (a = 0; a < fields.length; a++) {
            var fieldGroupName = fields[a]["groupName"];
            if (
              uniqueGroupNames[groupIndex] == fieldGroupName ||
              (displayGroupName == "" && uniqueGroupNames.length == 1)
            ) {
              var fieldName = fields[a]["field"];
              var fieldTitle = fields[a]["title"];
              var fieldType = fields[a]["type"];
              var fieldRelation = fields[a]["relation"];
              var fieldOptionID = fields[a]["option_id"];
              if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                fieldOptionID = "";
              }
              var fieldDefault = "";
              try {
                fieldDefault = fields[a]["default"];
              } catch (e) {}
              var fieldDisabled = false;
              try {
                fieldDisabled = fields[a]["disabled"];
              } catch (e) {}
              var select_type = "";
              try {
                select_type = fields[a]["select_type"];
              } catch (e) {}
              var s_type = "";
              if (fieldType == "select") {
                if (select_type == "multiple") {
                  s_type = "multiple";
                } else {
                  s_type = "";
                }
                try {
                  if (fields[a]["relation"] == "roles") {
                    var options = controller.setRelationValue(
                      "roles",
                      setupObj,
                      false,
                      idType,
                      "roleName",
                      formName,
                      "",
                      "",
                      editable,
                      s_type
                    );
                    var fieldObjTemp = fields[a];
                    fieldObjTemp.value = options;
                    fieldObjTemp.s_type = s_type;
                    var idType = 1;
                    tabsFormHTML += controller.renderField(
                      fieldObjTemp,
                      formName,
                      editable
                    );
                  } else {
                    var options = controller.setRelationValue(
                      fieldRelation,
                      setupObj,
                      false,
                      idType,
                      fieldOptionID,
                      currentObj.formName,
                      "",
                      "",
                      editable,
                      s_type
                    );
                    var fieldObjTemp = fields[a];
                    fieldObjTemp.value = options;
                    fieldObjTemp.s_type = s_type;
                    tabsFormHTML += controller.renderField(
                      fieldObjTemp,
                      currentObj.formName,
                      editable
                    );
                  }
                } catch (e) {}
              } else {
                try {
                  if (fields[a] != undefined && fields[a] != "undefined") {
                    if (dates != undefined && dates != "undefined") {
                      tabsFormHTML += controller.renderField(
                        fields[a],
                        currentObj.formName,
                        editable
                      );
                    } else {
                      tabsFormHTML += controller.renderField(
                        fields[a],
                        currentObj.formName,
                        editable
                      );
                    }
                  }
                } catch (e) {}
              }
              try {
                var select_type = fields[a]["select_type"];
              } catch (error) {}
            }
          }
        }
        var actionButton =
          "<div class='main-form-action'>" +
          controller.renderFormActions(formName) +
          "</div>";
        mainFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'></br>" +
          tabsFormHTML +
          "<br>" +
          actionButton +
          "</form>";
        mainFormHTML = "<div class='main-form'>" + mainFormHTML + "</div>";
        callback([mainFormHTML, loadTableobj]);
      }
    },
    renderChildAddForm: function () {
      var tabHeaders = "";
      var mainFormHTML = "";
      var tabsFormHTML = "";
      var subTabHeaders = "";
      var mainSubFormHTML = "";
      var tab = this.myFormObj.Mytabs;
      var dates = this.myFormObj.dateFields;
      var fields = this.myFormObj.fields;
      var idType = this.myFormObj.idType;
      for (a = 0; a < fields.length; a++) {
        var fieldName = fields[a]["field"];
        var fieldTitle = fields[a]["title"];
        var fieldType = fields[a]["type"];
        var fieldRelation = fields[a]["relation"];
        var s_type = "";
        if (fieldType == "select") {
          if (select_type == "multiple") {
            s_type = "multiple";
          }
          try {
            var options = controller.setRelationValue(
              fieldRelation,
              setupObj,
              false,
              idType,
              "",
              formName,
              "",
              "",
              editable,
              s_type
            );
            tabsFormHTML += controller.renderField(fields[a], "", editable);
          } catch (e) {}
        } else {
          try {
            if (fields[a] != undefined && fields[a] != "undefined") {
              if (dates != undefined && dates != "undefined") {
                tabsFormHTML += controller.renderField(fields[a], "", editable);
              } else {
                tabsFormHTML += controller.renderField(fields[a], "", editable);
              }
            }
          } catch (e) {}
        }
        try {
          var select_type = fields[a]["select_type"];
        } catch (error) {}
      }
      var actionButton = controller.renderFormActions();
      mainFormHTML =
        "<form id='" +
        this.myFormObj.formName +
        "_form'  form_identifier='" +
        this.myFormObj.formName +
        "' class='form parsley-form'>" +
        tabsFormHTML +
        "</br>" +
        actionButton +
        "</form>";
      mainFormHTML = "<div class='main-form'>" + mainFormHTML + "</div>";
      return mainFormHTML;
    },
    childTable: function (loadTableobj) {
      for (var key in loadTableobj) {
        controller.loadTable(
          loadTableobj[key][0].listings,
          loadTableobj[key][0].listUrl,
          loadTableobj[key][0].buttonsArr,
          loadTableobj[key][0].formName,
          loadTableobj[key][0].list,
          loadTableobj[key][0].group
        );
      }
      loadTableobj = "";
    },
    fieldExist: function (val, originalVal = "", currentObj) {
      var formFields = currentObj.fields;
      for (var key_ in formFields) {
        if (originalVal == "") {
          if (formFields[key_]["field"] == val) {
            return formFields[key_];
          }
        } else {
          if (formFields[key_]["field"] == originalVal) {
            return formFields[key_];
          }
        }
      }
      return false;
    },
    renderEditForm: function (
      obj,
      formName,
      editable = true,
      tabExclusion = [],
      callback
    ) {
      var currentObj = allFormObj[formName];
      try {
        if (currentObj.url_id != "tab") {
          try {
            allFormObj["parent_selected"] = obj;
            allFormObj["selected"] = obj;
          } catch (e) {}
          try {
            var tab_this = $("li.active.item");
            var tabPos = tab_this.attr("data-tab");
            allFormObj["tab_" + formName] = obj;
          } catch (e) {}
        } else {
          try {
            allFormObj["selected"] = "";
            allFormObj["selected"] = obj;
            allFormObj["parent_selected"] = obj;
          } catch (e) {}
        }
      } catch (e) {}
      var tabHeaders = "";
      var mainFormHTML = "";
      var tabsFormHTML = "";
      var subTabHeaders = "";
      var mainSubFormHTML = "";
      var tab = "";
      try {
        tab = currentObj.Mytabs;
      } catch (e) {}
      var fields = "";
      try {
        fields = currentObj.fields;
      } catch (e) {}
      var dates = "";
      try {
        dates = currentObj.dateFields;
      } catch (e) {}
      var tabLength = 0;
      try {
        tabLength = tab.length;
      } catch (e) {}
      if (tabLength > 0) {
        for (i = 0; i < tab.length; i++) {
          var isActive = "";
          if (i == 0) {
            isActive = "active in";
          } else {
            isActive = "";
          }
          var enabledElem = "";
          var n = tabExclusion.includes(tab[i]["tabName"]);
          if (n) {
            enabledElem = "style='display:none;'";
          }
          tabHeaders +=
            "<li " +
            enabledElem +
            ' tab-position= "' +
            i +
            '" class="item ' +
            tab[i]["tabName"] +
            '_tab_link"' +
            isActive +
            '" data-tab="' +
            tab[i]["entityName"] +
            '"><a data-toggle="tab" href="#' +
            tab[i]["tabName"] +
            '">' +
            tab[i]["tabTitle"] +
            "</a></li>";
          let uniqueGroupNames = [
            ...new Set(fields.map((item) => item.groupName)),
          ];
          for (groupIndex in uniqueGroupNames) {
            var hasGroupField = false;
            var displayGroupName = uniqueGroupNames[groupIndex];
            if (
              displayGroupName == undefined ||
              displayGroupName == "undefined"
            ) {
              displayGroupName = "";
            }
            var subTabHeadersTmp = "";
            for (a = 0; a < fields.length; a++) {
              var fieldGroupName = fields[a]["groupName"];
              if (
                uniqueGroupNames[groupIndex] == fieldGroupName ||
                (displayGroupName == "" && uniqueGroupNames.length == 1)
              ) {
                var fieldName = fields[a]["field"];
                var fieldTitle = fields[a]["title"];
                var fieldType = fields[a]["type"];
                var fieldRelation = fields[a]["relation"];
                var fieldOptionID = fields[a]["option_id"];
                var fieldEditingID = fields[a]["editing_id"];
                if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                  fieldOptionID = "";
                }
                if (fields[a]["tab"] == tab[i]["tabName"]) {
                  hasGroupField = true;
                  if (fieldName in obj) {
                    key = fieldName;
                    subTabHeadersTmp += controller.renderFormField(
                      obj,
                      key,
                      fieldName,
                      "",
                      currentObj,
                      editable,
                      fieldOptionID,
                      fields[a]
                    );
                  } else {
                    key = fieldName;
                    if (fieldRelation) {
                      subTabHeadersTmp += controller.renderFormField(
                        obj,
                        fieldRelation,
                        fieldRelation,
                        fieldName,
                        currentObj,
                        editable,
                        fieldOptionID,
                        fields[a]
                      );
                    }
                    fieldNameArray = fieldName.split(".");
                    var identifier = "";
                    var tmp = "";
                    var pos = 0;
                    try {
                      if (fieldNameArray.length == 1) {
                        tmp = obj[fieldNameArray[0]];
                      }
                      if (fieldNameArray.length == 2) {
                        tmp = obj[fieldNameArray[0]][fieldNameArray[1]];
                      }
                      if (fieldNameArray.length == 3) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ];
                      }
                      if (fieldNameArray.length == 4) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ][fieldNameArray[3]];
                      }
                      if (fieldNameArray.length == 5) {
                        tmp =
                          obj[fieldNameArray[0]][fieldNameArray[1]][
                            fieldNameArray[2]
                          ][fieldNameArray[3]][fieldNameArray[4]];
                      }
                    } catch (e) {}
                    if (!fieldRelation) {
                      subTabHeadersTmp += controller.renderFormFieldNested(
                        obj,
                        key,
                        fieldRelation,
                        tmp,
                        currentObj,
                        editable,
                        fieldOptionID,
                        fields[a]
                      );
                    }
                  }
                }
              }
            }
            if (hasGroupField) {
              subTabHeadersTmp =
                "<div class='form-group col-md-12' style='float: left;'><h4>" +
                displayGroupName +
                "</h4></div>" +
                subTabHeadersTmp;
            }
            subTabHeaders += subTabHeadersTmp;
          }
          tabsFormHTML +=
            "<h3 class='vertical-form-layout-header " +
            tab[i]["tabName"] +
            "_tab_link'>" +
            tab[i]["tabTitle"] +
            "</h3>";
          tabsFormHTML +=
            '<div id="' +
            tab[i]["tabName"] +
            '" data-tab="' +
            tab[i]["entityName"] +
            '" class="vertical-form-layout  ' +
            tab[i]["entityName"] +
            " " +
            tab[i]["tabName"] +
            '_tab_link"> ' +
            subTabHeaders +
            "</div>";
          subTabHeaders = "";
        }
        var actionButton = controller.renderFormActions(formName, editable);
        mainSubFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          "<div>" +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</div> " +
          "</form>";
        mainFormHTML += "<div class='main-form'>" + mainSubFormHTML + "</div>";
        callback(mainFormHTML);
      } else {
        let uniqueGroupNames = [...new Set(fields.map((item) => item.groupName))];
        for (groupIndex in uniqueGroupNames) {
          var displayGroupName = uniqueGroupNames[groupIndex];
          if (displayGroupName == undefined || displayGroupName == "undefined") {
            displayGroupName = "";
          }
          tabsFormHTML +=
            "<div class='form-group col-md-12' style='float: left;'><h4>" +
            displayGroupName +
            "</h4></div>";
          for (a = 0; a < fields.length; a++) {
            var fieldGroupName = fields[a]["groupName"];
            if (
              uniqueGroupNames[groupIndex] == fieldGroupName ||
              (displayGroupName == "" && uniqueGroupNames.length == 1)
            ) {
              var fieldName = fields[a]["field"];
              var fieldTitle = fields[a]["title"];
              var fieldType = fields[a]["type"];
              var fieldRelation = fields[a]["relation"];
              var fieldOptionID = fields[a]["option_id"];
              var fieldEditingID = fields[a]["editing_id"];
              if (fieldOptionID == undefined || fieldOptionID == "undefined") {
                fieldOptionID = "";
              }
              if (fieldName in obj) {
                key = fieldName;
                tabsFormHTML += controller.renderFormField(
                  obj,
                  key,
                  fieldName,
                  "",
                  currentObj,
                  editable,
                  fieldOptionID,
                  fields[a]
                );
              } else {
                key = fieldName;
                if (fieldRelation) {
                  tabsFormHTML += controller.renderFormField(
                    obj,
                    fieldRelation,
                    fieldRelation,
                    fieldName,
                    currentObj,
                    editable,
                    fieldOptionID,
                    fields[a]
                  );
                } else {
                }
              }
            }
          }
        }
        var actionButton = controller.renderFormActions(formName, editable);
        mainFormHTML =
          "<form id='" +
          currentObj.formName +
          "_form'  form_identifier='" +
          currentObj.formName +
          "' class='form parsley-form'>" +
          tabsFormHTML +
          "</br>" +
          actionButton +
          "</form>";
        mainFormHTML = "<div class='main-form'>" + mainFormHTML + "</div>";
        callback(mainFormHTML);
      }
    },
    renderFormFieldNested: function (
      obj,
      key,
      fieldName,
      value,
      currentObj,
      editable,
      option_id = ""
    ) {
      var tabsFormHTMLTmp = "";
      var returnField = controller.fieldExist(key, "", currentObj);
      var formFields = currentObj.fields;
      if (returnField != false) {
        var renderObj = {
          title: returnField["title"],
          field: returnField["field"],
          value: value,
          type: returnField["type"],
          disabled: returnField["disabled"],
          validations: returnField["validations"],
          postField: returnField["postField"],
          editField: returnField["editing_id"],
        };
        tabsFormHTMLTmp += controller.renderField(
          renderObj,
          currentObj.formName,
          editable,
          option_id
        );
      } else {
        var renderObj = {
          title: "Field Not Found",
          field: "Not Found",
          value: "Not Found",
          type: "text",
          disabled: returnField["disabled"],
          validations: returnField["validations"],
          s_type: "",
          postField: returnField["postField"],
          editField: returnField["editing_id"],
        };
        tabsFormHTMLTmp += controller.renderField(
          renderObj,
          currentObj.formName,
          editable,
          option_id
        );
      }
      return tabsFormHTMLTmp;
    },
    renderFormField: function (
      obj,
      key,
      fieldName,
      originalFieldName = "",
      currentObj,
      editable,
      option_id = "",
      fieldDefinedObj = ""
    ) {
      var dates = currentObj.dateFields;
      var formName = currentObj.formName;
      var tabsFormHTML = "";
      if (obj.hasOwnProperty(key)) {
        if (
          typeof obj[key] === "object" &&
          obj[key] !== null &&
          obj[key] != undefined &&
          obj[key] != "undefined"
        ) {
          var comparekey = key + "_id";
          var returnField = controller.fieldExist(
            comparekey,
            originalFieldName,
            currentObj
          );
          var s_type = "";
          try {
            s_type = returnField["select_type"];
            if (s_type == "undefined" || s_type == undefined) {
              s_type = "";
            }
          } catch (e) {}
          if (fieldName == comparekey || fieldName == key) {
            try {
              var options = "";
              if (key == "roles") {
                var idType = 1;
                var listEntityName = returnField["listEntityName"];
                if (
                  listEntityName == "undefined" ||
                  listEntityName == undefined
                ) {
                  listEntityName = "";
                }
                options = controller.setRelationValue(
                  "roles",
                  obj,
                  false,
                  idType,
                  "roleName",
                  "",
                  listEntityName,
                  "",
                  editable,
                  s_type
                );
                var renderObj = {
                  title: returnField["title"],
                  field: originalFieldName,
                  value: options,
                  type: returnField["type"],
                  disabled: returnField["disabled"],
                  s_type: returnField["select_type"],
                  validations: returnField["validations"],
                  postField: returnField["postField"],
                };
                tabsFormHTML += controller.renderField(
                  renderObj,
                  formName,
                  editable
                );
              } else {
                var listEntityName = returnField["listEntityName"];
                if (
                  listEntityName == "undefined" ||
                  listEntityName == undefined
                ) {
                  listEntityName = "";
                }
                options = controller.setRelationValue(
                  key,
                  obj,
                  false,
                  idType,
                  option_id,
                  "",
                  listEntityName,
                  "",
                  editable,
                  s_type
                );
                var renderObj = {
                  title: returnField["title"],
                  field: comparekey,
                  value: options,
                  type: returnField["type"],
                  disabled: returnField["disabled"],
                  s_type: returnField["select_type"],
                  validations: returnField["validations"],
                  postField: returnField["postField"],
                };
                tabsFormHTML += controller.renderField(
                  renderObj,
                  currentObj.formName,
                  editable
                );
              }
            } catch (e) {}
          }
        } else {
          if (fieldName == key) {
            try {
              if (obj[key] != undefined && obj[key] != "undefined") {
                var returnField = controller.fieldExist(key, "", currentObj);
                if (returnField != false) {
                  var renderObj = {
                    title: returnField["title"],
                    field: returnField["field"],
                    value: obj[key],
                    type: returnField["type"],
                    disabled: returnField["disabled"],
                    validations: returnField["validations"],
                    s_type: "",
                    postField: returnField["postField"],
                  };
                  tabsFormHTML += controller.renderField(
                    renderObj,
                    currentObj.formName,
                    editable
                  );
                } else {
                }
              }
            } catch (e) {}
          }
        }
        return tabsFormHTML;
      } else {
        try {
          var listEntityName = fieldDefinedObj["listEntityName"];
        } catch (e) {}
        try {
          var editing_id = fieldDefinedObj["editing_id"];
        } catch (e) {}
        var s_type = "";
        try {
          s_type = fieldDefinedObj["select_type"];
          if (s_type == "undefined" || s_type == undefined) {
            s_type = "";
          }
        } catch (e) {}
        if (fieldDefinedObj["type"] == "select") {
          options = controller.setRelationValue(
            key,
            obj,
            false,
            idType,
            option_id,
            "",
            listEntityName,
            editing_id,
            editable,
            s_type
          );
          fieldDefinedObj.value = options;
          tabsFormHTML += controller.renderField(
            fieldDefinedObj,
            currentObj.formName,
            editable
          );
        } else {
          options = controller.setRelationValue(
            key,
            obj,
            false,
            idType,
            option_id,
            "",
            listEntityName,
            editing_id,
            editable,
            s_type
          );
          fieldDefinedObj.value = options;
          tabsFormHTML += controller.renderField(
            fieldDefinedObj,
            currentObj.formName,
            editable
          );
        }
        return tabsFormHTML;
      }
    },
    renderFormActions: function (formName, editable = true) {
      if (formName == "assignedInspection") {
        var formActionsHTML = "";
        formActionsHTML = "<div class='xcrud-top-actions btn-group'>";
        formActionsHTML +=
          "<a href='javascript:;' form-name='" +
          formName +
          "' data_task='return' class='btn btn-warning xcrud-action return'>Return</a>";
        formActionsHTML += "</div>";
        return formActionsHTML;
      } else if (formName == "assignInspection") {
        var formActionsHTML = "";
        formActionsHTML = "<div class='xcrud-top-actions btn-group'>";
        formActionsHTML +=
          "<a href='javascript:;' form-name='" +
          formName +
          "' data_task='return' class='btn btn-warning xcrud-action return'>Return</a>";
        formActionsHTML += "</div>";
        return formActionsHTML;
      } else if (formName == "importer") {
        var formActionsHTML = "";
        formActionsHTML = "<div class='xcrud-top-actions btn-group'>";
        formActionsHTML +=
          "<a href='javascript:;' form-name='" +
          formName +
          "' data_task='return' class='btn btn-warning xcrud-action return'>Return</a>";
        formActionsHTML += "</div>";
        return formActionsHTML;
      } else {
        var formActionsHTML = "";
        formActionsHTML = "<div class='xcrud-top-actions btn-group'>";
        if (editable) {
          formActionsHTML +=
            "<a href='javascript:;' form-name='" +
            formName +
            "'  data_task='save_return' data-after='list' class='btn btn-primary xcrud-action save'>Save</a>";
        }
        formActionsHTML +=
          "<a href='javascript:;' form-name='" +
          formName +
          "' data_task='return' class='btn btn-warning xcrud-action return'>Return</a>";
        formActionsHTML += "</div>";
        return formActionsHTML;
      }
    },
    renderField: function (fieldObj, formName, editable = true, isadd = false) {
      var id = fieldObj.field;
      var title = fieldObj.title;
      var fieldType = fieldObj.type;
      var select_type = fieldObj.select_type;
      var fieldDefault = "";
      try {
        var value = fieldObj.value;
        if (value == undefined || value == "undefined") {
          value = "";
        }
      } catch (e) {}
      try {
        var editing_id = fieldObj.editing_id;
        if (editing_id == undefined || editing_id == "undefined") {
          editing_id = "";
        }
      } catch (e) {}
      try {
        var s_type = fieldObj.s_type;
        if (s_type == undefined || s_type == "undefined") {
          s_type = "";
        }
      } catch (e) {}
      try {
        var m_type = fieldObj.s_type;
        if (m_type == undefined || m_type == "undefined") {
          m_type = "";
        }
      } catch (e) {}
      try {
        var visbleHTML = "";
        var visible = fieldObj.visible;
        if (visible == undefined || visible == "undefined") {
          visible = "";
        }
        if (!visible) {
        }
      } catch (error) {}
      try {
        var fieldDefault = fieldObj.default;
        if (fieldDefault == undefined || fieldDefault == "undefined") {
        } else {
          value = fieldDefault;
        }
      } catch (e) {}
      try {
        var fieldPlaceholder = fieldObj.placeholder;
        if (fieldPlaceholder == undefined || fieldPlaceholder == "undefined") {
          fieldPlaceholder = "";
        }
      } catch (e) {}
      try {
        var fieldDependants = fieldObj.dependants;
        if (fieldDependants == undefined || fieldDependants == "undefined") {
          fieldDependants = "";
        }
      } catch (e) {}
      try {
        var fieldDepends = fieldObj.depends;
        if (fieldDepends == undefined || fieldDepends == "undefined") {
          fieldDepends = "";
        }
      } catch (e) {}
      try {
        var fieldTooltip = fieldObj.tooltip;
        if (fieldTooltip == undefined || fieldTooltip == "undefined") {
          fieldTooltip = "";
        }
      } catch (e) {}
      try {
        var fieldTitle = fieldObj.title;
        if (fieldTitle == undefined || fieldTitle == "undefined") {
          fieldTitle = "";
        }
      } catch (e) {}
      var htmlDisabled = "";
      var fieldDisabled = false;
      try {
        fieldDisabled = fieldObj.disabled;
        if (fieldDisabled == undefined || fieldDisabled == "undefined") {
          fieldDisabled = "";
        }
      } catch (e) {}
      var postField = "";
      try {
        postField = fieldObj.postField;
        if (postField == undefined || postField == "undefined") {
        } else {
          id = postField;
        }
      } catch (e) {}
      var validations = "";
      var validations = "data-parsley-required='true'";
      try {
        validations = fieldObj.validations;
        if (validations == undefined || validations == "undefined") {
          validations = "data-parsley-required='true'";
        }
        if (formName == "users") {
        }
      } catch (e) {}
      if (fieldDisabled) {
        validations = "data-parsley-excluded data-parsley-required='false'";
      }
      if (fieldDisabled) {
        htmlDisabled = "readonly=''  style='pointer-events:none';";
      }
      var formHTML = "";
      if (id == "company.registrationDate") {
        value = controller.formatDate(value);
      }
      if (fieldType == "hidden") {
        formHTML +=
          "<input  " +
          htmlDisabled +
          "  class='xcrud-input form-control " +
          formName +
          "' type='hidden' value='" +
          value +
          "' id='" +
          id +
          "' name='" +
          id +
          "' maxlength='70'>";
      } else if (fieldType == "textarea") {
        formHTML +=
          "<div " +
          visbleHTML +
          " class='form-group col-md-6 " +
          id +
          "_holder'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        if (editable) {
          formHTML +=
            "<textarea  " +
            validations +
            " " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' placeholder='" +
            fieldPlaceholder +
            "' class='xcrud-input form-control " +
            formName +
            "' type='text' data-type='text' value='" +
            value +
            "' id='" +
            id +
            "' name='" +
            id +
            "' rows='4' cols='100' style='width:-moz-available;'>" +
            value +
            "</textarea>";
        } else {
          formHTML += "<div class='control-label-plain'>" + value + "</div>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "text") {
        formHTML +=
          "<div " +
          visbleHTML +
          " class='form-group col-md-6 " +
          id +
          "_holder'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        if (editable) {
          formHTML +=
            "<input  " +
            validations +
            " " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' placeholder='" +
            fieldPlaceholder +
            "' class='xcrud-input form-control " +
            formName +
            "' type='text' data-type='text' value='" +
            value +
            "' id='" +
            id +
            "' name='" +
            id +
            "' maxlength='70'>";
        } else {
          formHTML += "<div class='control-label-plain'>" + value + "</div>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "password") {
        formHTML +=
          "<div class='form-group col-md-6'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        if (editable) {
          formHTML +=
            "<input " +
            validations +
            " " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' placeholder='" +
            fieldPlaceholder +
            "' class='xcrud-input form-control " +
            formName +
            "' type='password' data-type='text' value='" +
            value +
            "' id='" +
            id +
            "' name='" +
            id +
            "' maxlength='70'>";
        } else {
          formHTML += "<div class='control-label-plain'>" + value + "</div>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "select") {
        var multi_select = "";
        if (s_type == "multiple") {
          multi_select = "multi-select";
        }
        formHTML +=
          "<div " +
          visbleHTML +
          " class='form-group col-md-6 " +
          id +
          "_holder'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        if (
          (id == "consigneeID" && formName == "exporterConsignment") ||
          formName == "consolidatedPhyto"
        ) {
          if (editable) {
            formHTML += "<div class='col-md-6'>";
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "',true) " +
              validations +
              " " +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              s_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
            formHTML += "</div>";
          } else {
            formHTML += "<div class='col-md-7'>";
            formHTML += value;
            formHTML += "</div>";
          }
        } else if (
          (id == "importer_exporterid" && formName == "pip_application") ||
          formName == "pip_applicationrequest"
        ) {
          if (editable) {
            formHTML += "<div class='col-md-7'>";
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "',true) " +
              validations +
              " " +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              s_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
            formHTML += "</div>";
          } else {
            formHTML += "<div class='col-md-7'>";
            formHTML += value;
            formHTML += "</div>";
          }
        } else {
          formHTML += "<div class='col-md-7'>";
          if (editable) {
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "',true) " +
              validations +
              " " +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              s_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
          } else {
            formHTML += value;
          }
          formHTML += "</div>";
        }
        formHTML += "</div>";
      } else if (select_type == "multiple") {
        formHTML +=
          "<div " +
          visbleHTML +
          " class='form-group col-md-6 " +
          id +
          "_holder'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        if (id == "trading_block_id" && formName == "exporterFarm") {
          if (editable) {
            formHTML += "<div class='col-md-6'>";
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "',true) " +
              validations +
              " " +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              m_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
            formHTML += "</div>";
          } else {
            formHTML += "<div class='col-md-7'>";
            formHTML +=
              "<select style='pointer-events:none;border:none;background:transparent;-webkit-appearance: none;-moz-appearance: none;text-indent: 1px;text-overflow: '';'" +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              s_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
            formHTML += "</div>";
          }
        } else {
          formHTML += "<div class='col-md-7'>";
          if (editable) {
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "',true) " +
              validations +
              " " +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              m_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
          } else {
            formHTML +=
              "<select style='pointer-events:none;border:none;background:transparent;-webkit-appearance: none;-moz-appearance: none;text-indent: 1px;text-overflow: '';'" +
              htmlDisabled +
              " title='" +
              fieldTitle +
              "' " +
              s_type +
              " class='" +
              multi_select +
              " xcrud-input form-control " +
              formName +
              " " +
              id +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value +
              "</select>";
          }
          formHTML += "</div>";
        }
        formHTML += "</div>";
      } else if (fieldType == "date") {
        formHTML +=
          "<div class='form-group col-md-6'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        var formattedDate = controller.formatDate(value);
        if (editable) {
          formHTML +=
            "<input " +
            validations +
            " " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' placeholder='" +
            fieldPlaceholder +
            "' class='xcrud-input form-control " +
            formName +
            "' type='text' data-type='text' value='" +
            formattedDate +
            "' id='" +
            id +
            "' name='" +
            id +
            "' maxlength='70'>";
        } else {
          formHTML +=
            "<div class='control-label-plain'>" + formattedDate + "</div>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "file") {
        formHTML +=
          "<div class='form-group col-md-6'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        if (editable) {
          formHTML +=
            "<input " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' placeholder='" +
            fieldPlaceholder +
            "' class='" +
            formName +
            "' type='file'  id='" +
            id +
            "' name='" +
            id +
            "'>";
        } else {
          formHTML += "<div class='control-label-plain'>" + value + "</div>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "boolean") {
        formHTML +=
          "<div class='form-group col-md-6 " +
          id +
          "_holder'><label class='control-label col-sm-5'>" +
          title +
          "</label>";
        formHTML += "<div class='col-md-7'>";
        if (editable) {
          if (isadd) {
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "') " +
              htmlDisabled +
              "   " +
              validations +
              "  title='" +
              fieldTitle +
              "' class='xcrud-input form-control " +
              formName +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value;
            formHTML += "<option selected value='false'>No</option>";
            formHTML += "<option value='true'>Yes</option>";
            formHTML += "</select>";
          } else {
            formHTML +=
              "<select onchange=controller.onChangeLogicForSelect('" +
              id +
              "','" +
              formName +
              "') " +
              htmlDisabled +
              "   " +
              validations +
              "  title='" +
              fieldTitle +
              "' class='xcrud-input form-control " +
              formName +
              "' data-type='text' id='" +
              id +
              "' name='" +
              id +
              "' maxlength='70'> " +
              value;
            if (value == true || value == "true") {
              formHTML += "<option  selected value='true'>Yes</option>";
              formHTML += "<option value='false'>No</option>";
            } else {
              formHTML += "<option  value='true'>Yes</option>";
              formHTML += "<option  selected value='false'>No</option>";
            }
            formHTML += "</select>";
          }
        } else {
          formHTML +=
            "<select onchange=controller.onChangeLogicForSelect('" +
            id +
            "','" +
            formName +
            "') " +
            validations +
            " style='pointer-events:none;border:none;background:transparent;-webkit-appearance: none;-moz-appearance: none;text-indent: 1px;text-overflow: '';' " +
            htmlDisabled +
            " title='" +
            fieldTitle +
            "' class='xcrud-input form-control " +
            formName +
            "' data-type='text' id='" +
            id +
            "' name='" +
            id +
            "' maxlength='70'> " +
            value;
          if (value == true || value == "true") {
            formHTML += "<option selected value='true'>Yes</option>";
            formHTML += "<option value='false'>No</option>";
          } else {
            formHTML += "<option  value='true'>Yes</option>";
            formHTML += "<option  selected value='false'>No</option>";
          }
          formHTML += "</select>";
        }
        formHTML += "</div></div>";
      } else if (fieldType == "userid") {
        formHTML +=
          "<input " +
          htmlDisabled +
          " class='xcrud-input form-control' type='hidden' value='" +
          userObj.id +
          "' id='" +
          id +
          "' name='" +
          id +
          "' maxlength='70'>";
      } else if (fieldType == "button") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-7'style='margin-left:-10px'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.checkCondition('" +
          formName +
          "')>Check Condition</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "buttonUCR") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-3'>";
        formHTML +=
          "<a id='validateucrnumber' class='btn btn-primary' onclick='controller.checkUCRvalidation();'>Validate UCR</a>";
        formHTML += "</div>";
        formHTML += "<div class='col-md-3' style='width: 50%'>";
        formHTML +=
          "<a href='https://jue.mcnet.co.mz/mcnet/portal/homepage' target='_blank' style='color:blue; text-decoration: underline'>Register with single window</a>";
        formHTML += "</div>";
        formHTML += "</div>";
      } else if (fieldType == "buttonSeed") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML +=
          "<div class='col-md-7' style='padding-left: 0px !important;'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.checkSeedvalidation()>Validate Seed Certificate No.</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "btnvalidatsr14Pip") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML +=
          "<div class='col-md-7' style='padding-left: 0px !important;'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.checkSeedvalidationPip()>Validate Seed Certificate No.</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "buttonViewAFALicence") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-7'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.viewAfaLicence()>View AFA Licence</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "custombuttonsave") {
        var formActionsHTML = "";
        formActionsHTML = "<div class='customBtn'>";
        formActionsHTML = "<div class='xcrud-top-actions btn-group'>";
        formActionsHTML +=
          "<a href='javascript:;' form-name='" +
          formName +
          "'  data_task='save_return' data-after='list' class='btn btn-primary xcrud-action saveRecord' style='padding-left: 60px; padding-right:60px'>Save</a>";
        formActionsHTML += "</div>";
        formActionsHTML += "</div>";
        return formActionsHTML;
      } else if (fieldType == "btnAddExporter") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-6'>";
        formHTML +=
          "<a class='btn btn-primary' id='btnAddConsignees' onclick='controller.showExporterModal();'>Add Exporter</a>";
        formHTML += "</div>";
        formHTML += "</div>";
      } else if (fieldType == "btnAddConsignee") {
        $("#consigneeform")[0].reset();
        $("#consigneeform").trigger("reset");
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-4'>";
        formHTML +=
          "<a class='btn btn-primary' onclick='controller.showConModal();'>Add Consignees</a>";
        formHTML += "</div>";
        formHTML += "</div>";
      } else if (fieldType == "buttonViewImporterAFALicence") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML +=
          "<div class='col-md-7' style='padding-left: 0px !important;'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.viewImporterAfaLicence()>View AFA Licence</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "buttonSr14Number") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML +=
          "<div class='col-md-7' style='padding-left: 0px !important;'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.checkSR14Number()>Validate Seed Certificate No.</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "buttonMap") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML +=
          "<div class='col-md-7' style='padding-left: 0px !important;'>";
        formHTML +=
          "<a class='btn btn-primary' onclick=controller.initMap()>Set Location</a>";
        formHTML += "</div></div>";
      } else if (fieldType == "buttonshowMapdiv") {
        formHTML += "<div class='form-group col-md-6 " + id + "_holder'>";
        formHTML += "<div class='col-md-12'>";
        formHTML +=
          "<a class='btn btn-primary' id='buttonshowMapdiv' onclick=controller.initializemap() class ='buttonshowMapdiv'>Show Location</a>";
        formHTML += "</div></div>";
      }
      return formHTML;
    },
    checkUCRvalidation: function () {
      var ucrnumber = $("#ucrNumber").val();
      if (ucrnumber) {
        var url =
          serverURL + "exporterConsignment/validateUCR?ucrNo=" + ucrnumber + "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.responseText == undefined) {
            controller.showToastMsg("Validated", "#1a5589");
          } else {
            responseJSON = JSON.parse(data.responseText);
            controller.showToastMsg(responseJSON.data, "#ff6666");
          }
        });
      } else {
        controller.showToastMsg("Enter an UCR Number", "#ff6666");
      }
    },
  
    checkPIPUCRvalidation: function () {
      var ucrnumber = $("#ucrNumber").val();
      if (ucrnumber) {
        var url =
          serverURL + "pipApplication/validateUCR?ucrNo=" + ucrnumber + "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.responseText == undefined) {
            controller.showToastMsg("Validated", "#1a5589");
          } else {
            responseJSON = JSON.parse(data.responseText);
            controller.showToastMsg(responseJSON.data, "#ff6666");
          }
        });
      } else {
        controller.showToastMsg("Enter an UCR Number", "#ff6666");
      }
    },
  
    checkPIPUCRvalidationUpdatefunction() {
      var ucrnumber = $("#ucrNumber_2").val();
      if (ucrnumber) {
        var url =
          serverURL + "pipApplication/validateUCR?ucrNo=" + ucrnumber + "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.responseText == undefined) {
            controller.showToastMsg("Validated", "#1a5589");
          } else {
            responseJSON = JSON.parse(data.responseText);
            controller.showToastMsg(responseJSON.data, "#ff6666");
          }
        });
      } else {
        controller.showToastMsg("Enter an UCR Number", "#ff6666");
      }
    },
  
    checkUCRvalidationPhyto: function () {
      var ucrnumber = $("#sr14_no").val();
      if (ucrnumber) {
        var url =
          serverURL + "exporterConsignment/validateUCR?ucrNo=" + ucrnumber + "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.responseText == undefined) {
            controller.showToastMsg("Validated", "#1a5589");
          } else {
            responseJSON = JSON.parse(data.responseText);
            controller.showToastMsg(responseJSON.data, "#ff6666");
          }
        });
      } else {
        controller.showToastMsg("Enter an UCR Number", "#ff6666");
      }
    },
  
    checkUCRvalidation_2: function () {
      var ucrnumber = $("#sr14_no_2").val();
      if (ucrnumber) {
        var url =
          serverURL + "exporterConsignment/validateUCR?ucrNo=" + ucrnumber + "";
        controller.getAuthRequest(url, true, function (data, status) {
          if (data.responseText == undefined) {
            controller.showToastMsg("Validated", "#1a5589");
          } else {
            responseJSON = JSON.parse(data.responseText);
            controller.showToastMsg(responseJSON.data, "#ff6666");
          }
        });
      } else {
        controller.showToastMsg("Enter an UCR Number", "#ff6666");
      }
    },
    checkSeedvalidation: function (formName) {
      var sr14number = $("#sr14_no").val();
      var consignmentWeight = $("#consignmentWeight").val();
      if (sr14number) {
        var url =
          serverURL +
          "exporterConsignment/seedValidation?srNumber=" +
          sr14number +
          "";
        controller.checksr14postRequest(url, true, function (data, status) {});
      } else {
        controller.showToastMsg("Enter Seed Certificate No.", "#ff6666");
      }
    },
    checkSeedvalidationPip: function (formName) {
      var sr14number = $("#sr14Number").val();
      if (sr14number) {
        var url =
          serverURL +
          "exporterConsignment/seedValidation?srNumber=" +
          sr14number +
          "";
        controller.checksr14postRequestPIP(url, true, function (data, status) {});
      } else {
        controller.showToastMsg("Enter Seed Certificate No.", "#ff6666");
      }
    },
    checkSR14Number: function () {
      var sr14number = $("#sr14_number").val();
      if (sr14number) {
        var url =
          serverURL +
          "exporterConsignment/seedValidation?srNumber=" +
          sr14number +
          "";
        controller.checksr14postRequest(url, true, function (data, status) {});
      } else {
        controller.showToastMsg("Enter Seed Certificate No.", "#ff6666");
      }
    },
    checkCondition: function (formName) {
      if (formName == "pip_application") {
        if (
          $("#country_of_origin_id").val() &&
          $("#import_purposeid").val() &&
          $("#product_form_id").val() &&
          $("#products_id").val()
        ) {
          var country = $("#country_of_origin_id").val();
          var importpurpose = $("#import_purposeid").val();
          var productform = $("#product_form_id").val();
          var products = $("#products_id").val();
          var url =
            serverURL +
            "importRequirement/getImportRequirements?country_id=" +
            country +
            "&import_purpose_id=" +
            importpurpose +
            "&product_form_id=" +
            productform +
            "&products_id=" +
            products +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            if (status) {
              var option = $("<option></option>");
              option.attr("value", data.importCondition.import_condition_id);
              option.text(data.importCondition.name);
              $("#import_condition_id").html();
              $("#import_condition_id").html(option);
              $("#description").val(data.description);
            } else {
              controller.showToastMsg(data.responseJSON.data, "#ff6666");
            }
          });
        } else {
        }
      }
    },
    launchModalForm: function () {
      controller.renderCRUDForm("childTableEditIframe", formObj, function () {});
      $(".childTableEdit").modal("show");
    },
    launchApprovalWindow: function (approvalType, data, approver) {
      if (data.length >= 1) {
        $(".modal.fade.approve_Confirm_Many_form").modal("show");
        controller.initActions();
      }
    },
    loadFormData: function (obj) {
      var dates = this.myFormObj.dateFields;
      var idType = this.myFormObj.idType;
      for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
          if (
            typeof obj[key] === "object" &&
            obj[key] !== null &&
            obj[key] != undefined &&
            obj[key] != "undefined"
          ) {
            try {
              controller.setRelationValue(key, obj, false, idType);
            } catch (e) {}
          } else {
            try {
              if (obj[key] != undefined && obj[key] != "undefined") {
                if (dates.includes(key)) {
                  $("#" + key).val(controller.formatDate(obj[key]));
                } else {
                  $("#" + key).val(obj[key]);
                }
              }
            } catch (e) {}
          }
        }
      }
    },
    beforeStartWorkflow: function (callBack) {
      callBack(true);
    },
    startWorkflowEntity: function (data, formName) {
      controller.beforeStartWorkflow(function (response) {
        var nextDocApprovalMessage = "Record has been forwarded to ";
        var form_identifier = formName;
        var currentFormObj = allFormObj[form_identifier];
        var idType = currentFormObj.idType;
  
        if (idType == 2) {
          var identifier = form_identifier + "ID";
        } else if (idType == 3) {
          var identifier = "";
          try {
            identifier = currentObj.primaryFieldName;
          } catch (e) {}
        } else {
          var identifier = form_identifier + "_id";
        }
        if (formName == "consolidatedPhyto") {
          identifier = "exporterConsignmentID";
        }
        if (formName == "quarantineRequesteProduct") {
          identifier = "quarantine_facility_product_request_id";
        }
        if (formName == "allReprints") {
          identifier = "reprint_application_id";
        }
        if (
          formName == "allPhytoReprints" ||
          formName == "allPhytoReprintsByUser"
        ) {
          identifier = "reprint_application_id";
        }
        if (formName == "allImportConsignmentReprints") {
          identifier = "reprint_application_id";
        }
        if (
          formName == "quarantineFacilityInspection" ||
          formName == "quarantineFacilityInspection" ||
          formName == "exporterFarmInspection" ||
          formName == "exporterFirmInspection" ||
          formName == "exporterLowRiskInspection"
        ) {
          identifier = "exporterInspectionRequestID";
        }
        if (formName == "petRiskAnalysisRequest") {
          identifier = "pestRiskAnalysisRequest_id";
        }
        if (formName == "storageLocation") {
          identifier = "storage_location_id";
        }
        if (formName == "productform") {
          identifier = "product_form_id";
        }
  
        if (formName == "productvariety") {
          identifier = "product_variety_id";
        }
  
        var recordId = data[identifier];
  
        if (response) {
          var currentRole = localStorage.getItem("currentRole");
          if (form_identifier == "exporterFarm") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_farm +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "exporter") {
            if (data.isResearcher == true) {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                data.exporterID +
                "&tableRegister_id=" +
                tableRegister_exporter_registration +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=152" +
                "&createdBy=" +
                data.createdBy;
            } else if (data.isExportConsolidator == true) {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                data.exporterID +
                "&tableRegister_id=" +
                tableRegister_exporter_registration +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=202" +
                "&createdBy=" +
                data.createdBy;
            } else if (
              data.isExportConsolidator == true &&
              data.isOwnFarmExporter == true
            ) {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                data.exporterID +
                "&tableRegister_id=" +
                tableRegister_exporter_registration +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=" +
                data.docType.docType_id +
                "&createdBy=" +
                data.createdBy;
            } else {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                data.exporterID +
                "&tableRegister_id=" +
                tableRegister_exporter_registration +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=" +
                data.docType.docType_id +
                "&createdBy=" +
                data.createdBy;
            }
          } else if (form_identifier == "exporterFirm") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_firm +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "exportLowRiskCommodity") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_low_risk_commodity +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "exporterConsignment") {
            if (data.docType == undefined) {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                recordId +
                "&tableRegister_id=" +
                tableRegister_exporter_consignment +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=" +
                52 +
                "&createdBy=" +
                data.createdBy;
            } else {
              var urlParams =
                "missionID=" +
                1 +
                "&recordid=" +
                recordId +
                "&tableRegister_id=" +
                tableRegister_exporter_consignment +
                "&userRoleID=" +
                currentRole +
                "&doctypeID=" +
                data.docType.docType_id +
                "&createdBy=" +
                data.createdBy;
            }
          } else if (form_identifier == "consolidatedPhyto") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_consignment +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "split_export_consignment") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_split_consignment +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "printout_replacement") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_printout_replacement +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "importer") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_importer +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "consignmentInspectionRequest") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_consignmentInspectionRequest +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "quarantineFacility") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_quarantine_facility +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "quarantineRequesteProduct") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_quarantine_product_request +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "agents") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_agent_registration +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "evaluation_application") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_evaluation_application +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (
            form_identifier == "exporterInspectionRequest" ||
            form_identifier == "quarantineFacilityInspection" ||
            form_identifier == "exporterFarmInspection" ||
            form_identifier == "exporterFirmInspection" ||
            form_identifier == "exporterLowRiskInspection"
          ) {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_inspection_request +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (
            form_identifier == "exporterInspectionRequest" ||
            form_identifier == "quarantineFacilityInspection" ||
            form_identifier == "exporterFarmInspection" ||
            form_identifier == "exporterFirmInspection" ||
            form_identifier == "exporterLowRiskInspection"
          ) {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_exporter_inspection_request +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "petRiskAnalysisRequest") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_pest_risk_analysis_request_list +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "export_requirement") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_export_requirements +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "import_requirement") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_import_requirements +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "allReprints") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              reprint_application +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "allPhytoReprints") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              reprint_application +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "allPhytoReprintsByUser") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              reprint_application +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "allImportConsignmentReprints") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              reprint_application +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=" +
              data.docType.docType_id +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "storageLocation") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_storage_location +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "assigned_products") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_commodities +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "products") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_commodities +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "product_class") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_commodities_class +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "product_category") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_commodities_category +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "product_category") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_commodity_family +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "productform") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_product_form +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "productvariety") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_product_variety +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "county") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_county +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "inspectionRequirement") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_inspection_Requirement +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "inspectionLocation") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_inspection_Location +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "ban_list") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_ban_list +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "ward") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_ward +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          } else if (form_identifier == "subcounty") {
            var urlParams =
              "missionID=" +
              1 +
              "&recordid=" +
              recordId +
              "&tableRegister_id=" +
              tableRegister_subcounty +
              "&userRoleID=" +
              currentRole +
              "&doctypeID=52" +
              "&createdBy=" +
              data.createdBy;
          }
  
          if (form_identifier == "pip_application") {
            var pipApplicationID = data["pipApplicationID"];
            var url =
              serverURL +
              "pipApplicationVariety/getPIPApplicationVarietyByPIPApplication?pipApplicationID=" +
              pipApplicationID;
            controller.requestWithToken(url, function (data1, status) {
              if (data1[0] == undefined || data1[0] == "undefined") {
                var recordId = data["pipApplicationID"];
                var urlParams =
                  "missionID=" +
                  1 +
                  "&recordid=" +
                  recordId +
                  "&tableRegister_id=" +
                  tableRegister_pip_application +
                  "&userRoleID=" +
                  currentRole +
                  "&doctypeID=" +
                  data.docType.docType_id +
                  "&createdBy=" +
                  data.createdBy;
                formData = "";
                workflow.startWorkflow(
                  formData,
                  urlParams,
                  function (output) {
                    var outputMessage = controller.sanitizeErrorMessage(output);
                    var outputData = controller.sanitizeErrorData(output);
                    try {
                      var t = output.responseText;
                      var obj = JSON.parse(t);
                      if (obj.success == false) {
                        controller.showToastMsg(obj.data, "#ff6666");
                      } else {
                        controller.showToastMsg(obj.data, "#1a5589");
                      }
                    } catch (e) {}
                    controller.refreshCrudTables(form_identifier);
                    controller.refreshExporterTable(currentFormObj.formName);
                  },
                  "approve",
                  nextDocApprovalMessage
                );
              } else if (data1[0].importCondition.code == "QR") {
                controller.requestWithToken(
                  serverURL + "importer/getImporterByCompanyID",
                  function (data1, status) {
                    var importerID = data1[0].importerID;
                    var url =
                      serverURL +
                      "quarantineFacility/getQuarantineFacilityByImporter?importerID=" +
                      importerID +
                      "";
                    controller.requestWithToken(url, function (data2, status) {
                      var option = "";
                      if (data2.length > 0) {
                        $(".modal.fade.selectfacility").modal("show");
                        for (var i = 0; i < data2.length; i++) {
                          option +=
                            "<option value=" +
                            data2[i].quarantineFacilityID +
                            ">" +
                            data2[i].name +
                            "</option>";
                          $("#selectfacilityname").html(option);
                        }
                        $("#selectfacilitybtn").click(function (event) {
                          $(".modal.fade.selectfacility").modal("hide");
                          var recordId = data["pipApplicationID"];
                          var urlParams =
                            "missionID=" +
                            1 +
                            "&recordid=" +
                            recordId +
                            "&tableRegister_id=" +
                            tableRegister_pip_application +
                            "&userRoleID=" +
                            currentRole +
                            "&doctypeID=" +
                            data.docType.docType_id +
                            "&createdBy=" +
                            data.createdBy;
                          var facility_id =
                            document.getElementById("selectfacilityname").value;
                          controller.createImporterquarantineFacility(
                            recordId,
                            facility_id
                          );
                          formData = "";
                          workflow.startWorkflow(
                            formData,
                            urlParams,
                            function (output) {
                              var outputMessage =
                                controller.sanitizeErrorMessage(output);
                              var outputData =
                                controller.sanitizeErrorData(output);
                              try {
                                if (outputMessage == "SUCCESS") {
                                  controller.showToastMsg(outputData, "#1a5589");
                                } else {
                                  var t = output.responseText;
                                  var obj = JSON.parse(t);
                                  controller.showToastMsg(obj.data, "#ff6666");
                                }
                              } catch (e) {}
                              controller.refreshCrudTables(form_identifier);
                              controller.refreshExporterTable(
                                currentFormObj.formName
                              );
                            },
                            "approve",
                            nextDocApprovalMessage
                          );
                        });
                      } else {
                        $(".modal.fade.noquarantineFacilitymodal").modal("show");
                        $("#yesaddquarantinebtn").click(function (event) {
                          event.stopImmediatePropagation();
                          event.stopPropagation();
                          event.preventDefault();
                          $(".modal.fade.noquarantineFacilitymodal").modal(
                            "hide"
                          );
                          window.location = "./#app/quarantineFacility";
                        });
                      }
                    });
                  }
                );
              } else {
                var recordId = data["pipApplicationID"];
                var urlParams =
                  "missionID=" +
                  1 +
                  "&recordid=" +
                  recordId +
                  "&tableRegister_id=" +
                  tableRegister_pip_application +
                  "&userRoleID=" +
                  currentRole +
                  "&doctypeID=" +
                  data.docType.docType_id +
                  "&createdBy=" +
                  data.createdBy;
                formData = "";
                workflow.startWorkflow(
                  formData,
                  urlParams,
                  function (output) {
                    var outputMessage = controller.sanitizeErrorMessage(output);
                    var outputData = controller.sanitizeErrorData(output);
                    try {
                      if (outputMessage == "SUCCESS") {
                        controller.showToastMsg(outputData, "#1a5589");
                      } else {
                        var t = output.responseText;
                        var obj = JSON.parse(t);
                        if (obj.success == false) {
                          controller.showToastMsg(obj.data, "#ff6666");
                        } else {
                          controller.showToastMsg(obj.data, "#1a5589");
                        }
                      }
                    } catch (e) {}
                    setTimeout(function () {
                      controller.refreshCrudTables(form_identifier);
                      controller.refreshExporterTable(currentFormObj.formName);
                    }, 2000);
                  },
                  "approve",
                  nextDocApprovalMessage
                );
              }
            });
          }
          formData = "";
          workflow.startWorkflow(
            formData,
            urlParams,
            function (output) {
              var outputMessage = controller.sanitizeErrorMessage(output);
              var outputData = controller.sanitizeErrorData(output);
              try {
                if (outputMessage == "SUCCESS") {
                  controller.showToastMsg(outputData, "#1a5589");
                  setTimeout(function () {}, 2000);
                } else {
                  setTimeout(() => {}, 1000);
                  var t = output.responseText;
                  var obj = JSON.parse(t);
                  if (obj.success == false) {
                    controller.showToastMsg(obj.data, "#ff6666");
                  } else {
                    controller.showToastMsg(obj.data, "#1a5589");
                  }
                }
              } catch (e) {}
            },
            "approve",
            nextDocApprovalMessage
          );
        }
      });
    },
    sanitizeErrorMessage: function (output) {
      var outputMsg = "";
      try {
        outputMsg = output.message;
      } catch (e) {
        try {
          outputMsg = output.responseJSON.message;
        } catch (e) {
          outputMsg = "Error:";
        }
      }
      if (outputMsg == undefined || outputMsg == "undefined") {
        try {
          outputMsg = output.responseJSON.message;
        } catch (e) {
          outputMsg = "Error:";
        }
      }
      if (outputMsg == undefined || outputMsg == "undefined") {
        outputMsg = "Error: Kindly Contact Admin";
      }
      return outputMsg;
    },
    sanitizeErrorData: function (output) {
      var outputData = "";
      try {
        outputData = output.data;
      } catch (e) {
        try {
          outputData = output.responseJSON.data;
        } catch (e) {
          outputData = "Error:";
        }
      }
      if (outputData == undefined || outputData == "undefined") {
        try {
          outputData = output.responseJSON.data;
        } catch (e) {
          outputData = "Error:";
        }
      }
      if (outputData == undefined || outputData == "undefined") {
        outputData = "Error: Kindly Contact Admin";
      }
      return outputData;
    },


backToLogin: function(){
  if (localStorage.getItem("userObj") != null || localStorage.getItem("userObj") != "") {
    localStorage.removeItem("userObj");
    localStorage.removeItem("currentRole");
    window.location.href + '?eraseCache=true';
    window.location = "verify.html";
    location.reload(true);
    window.location.reload();
    localStorage.clear();
} else {
    try {
        localStorage.clear();
        localStorage.removeItem("userObj");
        localStorage.removeItem("currentRole");
        window.location = "verify.html";
        location.reload(true);
        window.location.reload();
        localStorage.clear();
        window.location = window.location.href + '?eraseCache=true';

    } catch (e) {
        localStorage.removeItem("userObj");
        localStorage.removeItem("currentRole");
        window.location = "verify.html";
        location.reload();
        window.location.reload();
        localStorage.clear();
        window.location = window.location.href + '?eraseCache=true';

    }
}
  },

    requestWithToken: function (url, reponseObj) {
      console.log("datadatadata 1", userObj.jwtToken);
    
      $.ajax({
        url: url,
        headers: {
          Authorization: "Bearer " + userObj.accessToken, // Correct format
        },

        contentType: "application/json",
        async: true,
        success: function (data) {
          reponseObj(data);
        },
        error: function (xhr, textStatus, errorThrown) {
          if (xhr.status == 400 || xhr.status == 403) { // Handle 403 error
            var t = xhr.responseText;
            try {
              var obj = JSON.parse(t);
              controller.showToastMsg(obj.message || "Unauthorized", "#ff6666");
            } catch (e) {
              controller.showToastMsg("Unauthorized", "#ff6666");
            }
          } else if (xhr.status == 500) {
            controller.showToastMsg("Server Error", "#ff6666");
          }
        },
      });
    },

    verifyOtprequestWithToken: function (url, reponseObj) {
      console.log("datadatadata 1", userObj.jwtToken);
    
      $.ajax({
        url: url,
        type: "POST",
        headers: {
          Authorization: "Bearer " + userObj.accessToken, // ✅ Correct Bearer format
          "Content-Type": "application/json",
        },
        dataType: "json",
        async: true,
        success: function (data) {
          reponseObj(data);
        },
        error: function (xhr, textStatus, errorThrown) {
          console.log("Error:", xhr.status, xhr.responseText);
    
          if (xhr.status === 400 || xhr.status === 403) { // ✅ Handle 403 (Forbidden)
            try {
              var obj = JSON.parse(xhr.responseText);
              controller.showToastMsg(obj.message || "Unauthorized", "#ff6666");
            } catch (e) {
              controller.showToastMsg("Unauthorized", "#ff6666");
            }
          } else if (xhr.status === 500) {
            controller.showToastMsg("Server Error", "#ff6666");
          }
        },
      });
    },
    
    
    
    requestWithTokenPOST: function (url, formData, reponseObj) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        success: function (data) {
          reponseObj(data);
        },
        fail: function (e) {},
        error: function (XMLHttpRequest, textStatus, errorThrown) {},
      });
    },
  
    requestWithTokenPOSTPesaflow: function (url, formData, reponseObj) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        success: function (data, textStatus, xhr) {
          if (xhr.status == 200) {
            reponseObj(data);
          } else if (xhr.status == 400) {
            // controller.showToastMsg("Payment has not been Received !", "#ff6666");
          } else if (xhr.status == 401) {
          } else if (xhr.status == 500) {
            controller.showToastMsg("Unautorized!", "#ff6666");
          }
        },
        fail: function (xhr) {
          if (xhr.status == 400) {
            // controller.showToastMsg("Payment has not been Received !", "#ff6666");
          } else if (xhr.status == 500) {
            // controller.showToastMsg("Payment has not been Received !", "#ff6666");
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          // controller.showToastMsg("Payment has not been Received !", "#ff6666");
        },
      });
    },
    requestWithTokenPOSTPayment: function (url, formData, reponseObj) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        success: function (data) {
          reponseObj(data);
        },
        fail: function (e) {
          controller.showToastMsg(
            "Application Post Payment Failed , Try again",
            "#ff6666"
          );
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          controller.showToastMsg(
            "Application Post Payment Failed , Try again",
            "#ff6666"
          );
        },
      });
    },
    requestRetractDocumentWithTokenPOST: function (url, formData, reponseObj) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        success: function (data, textStatus, xhr) {
          if (xhr.status == 200) {
            controller.showToastMsg(data.data, "#1a5589");
            controller.refreshCrudTables();
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          } else if (xhr.status == 400) {
            var t = xhr.responseText;
            var obj = JSON.parse(t);
            controller.showToastMsg(obj.data, "#ff6666");
            controller.refreshCrudTables();
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          } else if (xhr.status == 401) {
          } else if (xhr.status == 500) {
            controller.refreshCrudTables();
            controller.showToastMsg("Unable to Retract Document", "#ff6666");
  
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          }
        },
        fail: function (xhr) {
          if (xhr.status == 400) {
            var t = xhr.responseText;
            var obj = JSON.parse(t);
            controller.refreshCrudTables();
          } else if (xhr.status == 500) {
            controller.refreshCrudTables();
            controller.showToastMsg("Unable to Retract Document", "#ff6666");
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          controller.refreshCrudTables();
          var t = XMLHttpRequest.responseText;
          var obj = JSON.parse(t);
          controller.showToastMsg(obj.data, "#ff6666");
        },
      });
    },
  
    requestRetractDocumentWithTokenPOSTRegisterApplications: function (
      url,
      formData,
      reponseObj
    ) {
      $.ajax({
        url: url,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        type: "post",
        data: formData,
        success: function (data, textStatus, xhr) {
          if (xhr.status == 200) {
            controller.showToastMsg(data.data, "#1a5589");
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          } else if (xhr.status == 400) {
            var t = xhr.responseText;
            var obj = JSON.parse(t);
            controller.showToastMsg(obj.data, "#ff6666");
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          } else if (xhr.status == 401) {
          } else if (xhr.status == 500) {
            controller.showToastMsg("Unable to Retract Document", "#ff6666");
  
            setTimeout(function () {
              window.location.reload();
            }, 1000);
          }
        },
        fail: function (xhr) {
          if (xhr.status == 400) {
            var t = xhr.responseText;
            var obj = JSON.parse(t);
          } else if (xhr.status == 500) {
            controller.showToastMsg("Unable to Retract Document", "#ff6666");
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          controller.refreshCrudTables();
          var t = XMLHttpRequest.responseText;
          var obj = JSON.parse(t);
          controller.showToastMsg(obj.data, "#ff6666");
        },
      });
    },
    loadTable: function (
      columnsArr,
      listUrl,
      buttonsArr,
      tableName,
      tableId,
      groupby,
      method
    ) {
      var table = new Tabulator(tableId, {
        pagination: "local",
        paginationSize: 10,
        paginationSizeSelector: [1, 2, 3, 5, 10, 50, 100, 1000, 10000],
        placeholder: "No Data Available",
        printHeader: "<h1>Example Table Header<h1>",
        printFooter: "<h2>Example Table Footer<h2>",
        selectable: true,
        selectablePersistence: false,
        layout: "fitColumns", // automatically stretch columns to fill available width
        resizableColumns: true,
        fitColumns: true,
        printAsHtml: true,
        printStyled: true,
        resizable: true,
        printHeader: "<h1>" + tableName + "<h1>",
        printFooter: "<h2>" + tableName + "<h2>",
        addRowPos: "top",
        groupBy: groupby,
        columns: columnsArr,
        ajaxSorting: false,
        rowSelectionChanged: function (data, row) {
          SelectedData.push(data);
        },
        rowFormatter: function (row) {
          var data = row.getData();
          if (tableName == "payment") {
            if (
              data.description ==
              "Total Payment For Application for Certificate of Competency - Exporter"
            ) {
              row.getElement().style.fontWeight = "900";
            }
          }
        },
        rowClick: function (e, row) {
          var element = row.getElement(),
            data = row.getData();
          if (globalCell == true) {
          } else {
            var tab_this = $("li.active.item");
            var tabPos = tab_this.attr("data-tab");
            allFormObj["tab_" + tabPos] = data;
            var divElem = $(element).closest(".listings");
            var formName = divElem.attr("id");
            if (formName == "listings_onetime_export") {
              formName = "onetime_export";
            } else if (formName == "listings_onetime_import") {
              formName = "onetime_import";
            } else if (formName == "listings_pip_application") {
              formName = "pip_application";
            } else {
              try {
                var formNameArr = formName.split("_");
                formName = formNameArr[1];
              } catch (error) {}
            }
            var currentObj = allFormObj[formName];
            try {
              if (currentObj.url_id != "tab") {
                try {
                  allFormObj["parent_selected"] = data;
                  allFormObj["selected"] = data;
                } catch (e) {}
              } else {
                try {
                  allFormObj["selected"] = "";
                  allFormObj["selected"] = data;
                } catch (e) {}
              }
            } catch (e) {}
            try {
              console.log("data", data);
              console.log("formName", formName);
  
              if (formName == "printout") {
                getprintout_replacement(data.printout_replacement_id);
              }
              // if (formName == "exporterConsignment") {
              //     getPaymentByConsigment(data.exporterConsignmentID);
              // }
              if (formName == "consolidatedPhyto") {
                getPaymentByConsigment(data.exporterConsignmentID);
              } else if (formName == "inspectionHeader") {
                getLineByHeader(data.inspectionHeaderID, data);
              } else if (formName == "exporterFarm") {
                getPaymentByFarm(data.exporterFarmID);
              } else if (formName == "exporterFarmInspection") {
                getPaymentByFarmInspectionRequest(
                  data.exporterInspectionRequestID
                );
              } else if (formName == "exporterFirmInspection") {
                getPaymentByFarmInspectionRequest(
                  data.exporterInspectionRequestID
                );
              }
              // else if (formName == "split") {
              //     getSplitPaymentByConsigment(data.split_export_consignment_id);
              // }
              else if (formName == "exporterLowRiskInspection") {
                getPaymentByFarmInspectionRequest(
                  data.exporterInspectionRequestID
                );
              } else if (formName == "quarantineFacilityInspection") {
                getPaymentByFarmInspectionRequest(
                  data.exporterInspectionRequestID
                );
              } else if (formName == "exporterFirm") {
                getPaymentByFirm(data.exporterFirmID);
              } else if (formName == "quarantineFacility") {
                getPaymentByQuarantineFacility(data.quarantineFacilityID);
              } else if (formName == "exportLowRiskCommodity") {
                getPaymentByLowRisk(data.exportLowRiskCommodityID);
              } else if (formName == "onetime_export") {
                getPaymentByonetime_exporter(data.onetime_export_id, data);
              } else if (formName == "onetime_import") {
                getPaymentByonetime_importer(data.onetime_import_id, data);
              } else if (formName == "printout_replacement") {
                getPaymentByPIPreplacement(data.printout_replacement_id);
              } else if (formName == "pip_application") {
                // getPaymentByPIP(data.pipApplicationID);
              } else if (formName == "consignmentInspectionRequest") {
                getPaymentByConsigmentInspectionRequest(
                  data.consignmentInspectionRequestID
                );
              } else if (formName == "exporterInspectionRequest") {
                getPaymentByInspectionRequest(data);
              }
            } catch (e) {}
          }
          try {
            controller.getRelationObjectsByParam(data, element);
          } catch (e) {}
          globalCell = false;
        },
        printConfig: {
          formatCells: false,
        },
      });
  
      try {
        document
          .getElementById("print-table")
          .addEventListener("click", function () {
            table.print(false, true);
          });
        document
          .getElementById("download-csv")
          .addEventListener("click", function () {
            table.download("csv", "data.csv", {
              delimiter: ",",
            });
          });
      } catch (error) {}
  
      $(".action-select")
        .off("click")
        .on("click", function (event) {});
  
  
      $(".crudOnetimeExportImportLineeSave")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                exportRequirementID:
                  data2[i].exportRequirement.export_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
            var datarecords = inspectionrecords;
            for (let i = 0; i < datarecords.length; i++) {
              inspectionrecords = [];
              InspectionApprove(datarecords[i], "");
            }
          }
        });
  
  
  
        
        // $(".crudOnetimeExportImportLineeSavedisposal")
        // .off("click")
        // .on("click", function (event) {
        //   event.stopImmediatePropagation();
        //   event.stopPropagation();
        //   event.preventDefault();
        //   if (!event.detail || event.detail == 1) {
        //     var data2 = table.getData();
        //     for (var i = 0; i < data2.length; i++) {
        //       var url = serverURL + "inspectionLine/updateInspectionLine";
        //       var async_status = true;
        //       var formJson = {
        //         inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
        //         inspectionLineID: data2[i].inspectionLineID,
        //         exportRequirementID:
        //           data2[i].exportRequirement.export_requirement_id,
        //         remarks: data2[i].remarks,
        //         results: data2[i].results,
        //         status: data2[i].status,
        //       };
  
  
              
        //       controller.allPostinspectionLinesRequestDispose(
        //         url,
        //         formJson,
        //         async_status,
        //         function (data, status) {
        //           refreshCurrentTable(this.formObj8);
        //         }
        //       );
        //     }
        //     var datarecords = inspectionrecords;
        //     for (let i = 0; i < datarecords.length; i++) {
        //       inspectionrecords = [];
        //       InspectionReject(datarecords[i], "");
        //     }
        //   }
        // });
  
  
  
  
      $(".crudOnetimeExportImportLineereject")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                exportRequirementID:
                  data2[i].exportRequirement.export_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
            var datarecords = inspectionrecords;
            for (let i = 0; i < datarecords.length; i++) {
              inspectionrecords = [];
              InspectionReject(datarecords[i], "");
            }
          }
        });
  
  
  
      $(".crudRejectInspection")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                exportRequirementID:
                  data2[i].exportRequirement.export_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
            var datarecords = inspectionrecords;
            for (let i = 0; i < datarecords.length; i++) {
              inspectionrecords = [];
              InspectionReject(datarecords[i], "");
            }
          }
        });
      $(".saverecordlinesReject")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                inspectionRequirementID:
                  data2[i].inspectionRequirement.inspectionRequirementID,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
            var datarecords = inspectionrecords;
            for (let i = 0; i < datarecords.length; i++) {
              inspectionrecords = [];
              InspectionReject(datarecords[i], "");
            }
          }
        });
      $(".saverecordImportlinesReject")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                import_requirement_id:
                  data2[i].importRequirement.import_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
            var datarecords = inspectionrecords;
            for (let i = 0; i < datarecords.length; i++) {
              inspectionrecords = [];
              InspectionReject(datarecords[i], "");
            }
          }
        });
      $(".saverecordlines")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
  
            if (
              allFormObj.hasOwnProperty("assignedPhytoInspections") ||
              allFormObj.hasOwnProperty("assignedPIPInspections") ||
              allFormObj.hasOwnProperty("onetime_import") ||
              allFormObj.hasOwnProperty("onetime_export")
            ) {
              InspectionApprove(data, "");
            } else {
              $(".modal.fade.validUntil").modal("show");
              $("#validUntilBtn").click(function () {
                var formJson = $("#validUntil").serializeObject();
                var validUntil = formJson.validTo;
                if (validUntil == null || validUntil == "") {
                  controller.showToastMsg("Validity Date Required", "#ff6666");
                } else {
                  $(".modal.fade.validUntil").modal("hide");
                  for (var i = 0; i < data2.length; i++) {
                    var url = serverURL + "inspectionLine/updateInspectionLine";
                    var async_status = true;
                    var formJson = {
                      inspectionHeaderID:
                        data2[i].inspectionHeader.inspectionHeaderID,
                      inspectionLineID: data2[i].inspectionLineID,
                      inspectionRequirementID:
                        data2[i].inspectionRequirement.inspectionRequirementID,
                      remarks: data2[i].remarks,
                      results: data2[i].results,
                      status: data2[i].status,
                    };
                    controller.allPostinspectionLinesRequest(
                      url,
                      formJson,
                      async_status,
                      function (data, status) {
                        refreshCurrentTable(this.formObj8);
                      }
                    );
                  }
                  var datarecords = inspectionrecords;
                  for (let i = 0; i < datarecords.length; i++) {
                    inspectionrecords = [];
                    InspectionApprove(datarecords[i], validUntil);
                  }
                }
              });
            }
          }
        });
  
      // Approval of quarantine inspections Request
      $(".saverecordQuarantinelinesApprove")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
  
            $(".modal.fade.validUntil").modal("show");
            $("#validTo").val("");
            $("#validUntilBtn").click(function (event) {
              event.stopImmediatePropagation();
              event.stopPropagation();
              event.preventDefault();
              var formJson = $("#validUntil").serializeObject();
              var validUntil = formJson.validTo;
              if (validUntil == null || validUntil == "") {
                controller.showToastMsg("Validity Date Required", "#ff6666");
              } else {
                $(".modal.fade.validUntil").modal("hide");
                for (var i = 0; i < data2.length; i++) {
                  var url = serverURL + "inspectionLine/updateInspectionLine";
                  var async_status = true;
                  var formJson = {
                    inspectionHeaderID:
                      data2[i].inspectionHeader.inspectionHeaderID,
                    inspectionLineID: data2[i].inspectionLineID,
                    inspectionRequirementID:
                      data2[i].inspectionRequirement.inspectionRequirementID,
                    remarks: data2[i].remarks,
                    results: data2[i].results,
                    status: data2[i].status,
                  };
                  controller.allPostinspectionLinesRequest(
                    url,
                    formJson,
                    async_status,
                    function (data, status) {
                      // refreshCurrentTable(this.formObj8);
                    }
                  );
                }
                setTimeout(function () {
                  for (let i = 0; i < inspectionrecords.length; i++) {
                    InspectionApprove(inspectionrecords[i], validUntil);
                  }
                }, 1500);
              }
            });
          }
        });
  
      $(".saverecordQuarantinelinesReject")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                inspectionRequirementID:
                  data2[i].inspectionRequirement.inspectionRequirementID,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  // refreshCurrentTable(this.formObj8);
                }
              );
            }
  
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionReject(inspectionrecords[i], "");
              }
            }, 1500);
          }
        });
  
      // import consignmnet cargo
      $(".saverecordCargoreleaselinesReject")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                import_requirement_id:
                  data2[i].importRequirement.import_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {}
              );
            }
  
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionReject(inspectionrecords[i], "");
              }
            }, 1500);
          }
        });
  
      $(".saverecordCargoReleaselinesApprove")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                import_requirement_id:
                  data2[i].importRequirement.import_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {}
              );
            }
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionApprove(inspectionrecords[i], "");
              }
            }, 1500);
          }
        });
  
      $(".createRecordlines")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
  
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            var formJson = $("#validUntil").serializeObject();
            var validUntil = formJson.validTo;
            $(".requirementModal").modal("hide");
            // if (validUntil == null || validUntil == "") {
            //     controller.showToastMsg("Validity Date Required", "#ff6666");
            // } else {
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                inspectionRequirementID:
                  data2[i].inspectionRequirement.inspectionRequirementID,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {}
              );
            }
  
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionApprove(inspectionrecords[i], "");
              }
            }, 1500);
  
            // }
          }
        });
      $(".crudimportConsignmentLineSave")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                import_requirement_id:
                  data2[i].importRequirement.import_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostinspectionLinesRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  // refreshCurrentTable(this.formObj8);
                }
              );
            }
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionApprove(inspectionrecords[i], "");
              }
            }, 1500);
          }
        });
      $(".crudexportLineSave")
        .off("click")
        .on("click", function (event) {
          event.stopImmediatePropagation();
          event.stopPropagation();
          event.preventDefault();
          if (!event.detail || event.detail == 1) {
            var data2 = table.getData();
            for (var i = 0; i < data2.length; i++) {
              var url = serverURL + "inspectionLine/updateInspectionLine";
              var async_status = true;
              var formJson = {
                inspectionHeaderID: data2[i].inspectionHeader.inspectionHeaderID,
                inspectionLineID: data2[i].inspectionLineID,
                exportRequirementID:
                  data2[i].exportRequirement.export_requirement_id,
                remarks: data2[i].remarks,
                results: data2[i].results,
                status: data2[i].status,
              };
              controller.allPostRequest(
                url,
                formJson,
                async_status,
                function (data, status) {
                  refreshCurrentTable(this.formObj8);
                }
              );
            }
  
            setTimeout(function () {
              for (let i = 0; i < inspectionrecords.length; i++) {
                InspectionApprove(inspectionrecords[i], "");
              }
            }, 1500);
          }
        });
      if (tableName == "payment") {
        table.setSort([
          {
            column: "amount",
            dir: "asc",
          },
          {
            column: "invoiceDate",
            dir: "desc",
          },
        ]);
      }
      var tmpData = [];
      // controller.show_progress();
      $.ajax({
        url: listUrl,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        type: method,
        ajaxLoader: true, // Enable built-in loading spinner
        async: true,
        success: function (data) {
          controller.hide_progress();
          var jsonData = data;
          if (!Array.isArray(jsonData)) {
            jsonData = [jsonData];
          }
          for (var i in jsonData) {
            var counter = jsonData[i];
            if (tableName == "payment") {
              if (counter.isPaid) {
                counter.isPaid = "Paid";
              } else {
                if (counter.amount == 0) {
                  counter.isPaid = "No Payment to be made";
                } else {
                  counter.isPaid = "Pending Payment";
                }
              }
            } else {
            }
            tmpData.push(counter);
          }
          table
            .setData(tmpData)
            .then(function () {})
            .catch(function (error) {});
        },
        fail: function () {
          $("#blinder").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          controller.hide_progress();
          var jsonData = XMLHttpRequest.responseText;
          if (!Array.isArray(jsonData)) {
            jsonData = [jsonData];
          }
          for (var i in jsonData) {
            var counter = jsonData[i];
            if (tableName == "payment") {
              if (counter.isPaid) {
                counter.isPaid = "Paid";
              } else {
                counter.isPaid = "Pending Payment";
              }
            } else {
            }
            tmpData.push(counter);
          }
          table
            .setData(tmpData)
            .then(function () {})
            .catch(function (error) {});
        },
      });
      var the_Function = function (cell, formatterParams, onRendered) {
        return "<i class='fa fa-print'>function_trigger</i>";
      };
    },
    loadTableStaticData: function (
      columnsArr,
      data,
      buttonsArr,
      tableName,
      tableId,
      groupby,
      method = "GET"
    ) {
      var table = new Tabulator(tableId, {
        pagination: "local",
        paginationSize: 10,
        placeholder: "No Data Available",
        selectable: true,
        selectablePersistence: true,
        layout: "fitColumns",
        addRowPos: "top",
        groupBy: groupby,
        columns: columnsArr,
        rowSelectionChanged: function (data, rows) {
          SelectedData.push(data);
        },
        columns: columnsArr,
        rowClick: function (e, row) {
          var element = row.getElement(),
            data = row.getData();
          allFormObj["selected"] = "";
          allFormObj["selected"] = data;
          controller.getRelationObjectsByParam(data, element);
        },
      });
      var tmpData = [];
      controller.show_progress();
      var jsonData = data;
      if (!Array.isArray(jsonData)) {
        jsonData = [jsonData];
      }
      for (var i in jsonData) {
        var counter = jsonData[i];
        tmpData.push(counter);
      }
      setTimeout(() => {
        table
          .setData(tmpData)
          .then(function () {
            table.redraw(true);
          })
          .catch(function (error) {});
      }, 1000);
      table.redraw(true);
      var the_Function = function (cell, formatterParams, onRendered) {
        return "<i class='fa fa-print'>function_trigger</i>";
      };
    },
    initiateAssignInspection: function (action, approver, tableName, recordName) {
      var formData = SelectedData[SelectedData.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
  
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          controller.forwardMany(approver, action);
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            toBeApprovedActivity.push(output[i]);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    resetForm: function () {
      const form = document.querySelector("#validUntil");
      form.reset();
      const disabledFields = form.querySelectorAll(":disabled");
      for (let i = 0; i < disabledFields.length; i++) {
        disabledFields[i].removeAttribute("disabled");
      }
      form.reset();
      for (let i = 0; i < disabledFields.length; i++) {
        disabledFields[i].setAttribute("disabled", true);
      }
    },
  
    completeAssignedInspection: function (
      action,
      approver,
      tableName,
      recordName
    ) {
      var formData = SelectedData[SelectedData.length - 1];
  
      console.log("consssss", formData);
  
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          controller.show_progress();
          controller.forwardMany(approver, action);
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            toBeApprovedActivity.push(output[i]);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    paymentSTKRequest: function (phoneNumber, tableRegisterID, recordID) {
      var formJson = {
        phoneNumber: phoneNumber,
        recordId: recordID,
        tableRegisterId: tableRegisterID,
      };
  
      var dataActivity = [formJson];
      var formJson = JSON.stringify(dataActivity);
      var url = serverURL + "payment/STKPush";
      var async_status = true;
      controller.mpesaRequest(
        url,
        formJson,
        async_status,
        function (data, status) {}
      );
    },
  
    initiateBulkPayment: function (
      action,
      phoneNumber,
      recordId,
      tableRegisterId,
      formTypeID
    ) {
      var formData = SelectedData[SelectedData.length - 1];
      var urlParams =
        "phoneNumber=" +
        phoneNumber +
        "&recordId=" +
        recordId +
        "&tableRegisterId=" +
        tableRegisterId +
        "&formTypeID=" +
        formTypeID;
      var recordid;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          controller.forwardBulkPayment(phoneNumber, action, tableRegisterId);
          return;
        }
        var url =
          serverURL +
          "payment/getPaymentByFormTypeIDAndRecordID?recordID=" +
          formData[index][recordId] +
          "&formTypeID=" +
          formTypeID;
        workflow.getActivity(url, "", function (data, status) {
          for (let i = 0; i < data.length; i++) {
            stkPushRecords.push({
              recordId: data[i].record_id,
              phoneNumber,
              tableRegisterId,
            });
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
    refreshExporterTable: function (formName) {
      var thisObj = allFormObj[formName];
      controller.renderCRUDTable(thisObj, "GET");
    },
    loaddpreviousremarksView: function (action, approver, tableName, recordName) {
      var formData = SelectedData[SelectedData.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            $(".crud_section_comments2").innerHTML = output[i].previousRemarks;
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
    loaddpreviousremarks: function (action, approver, tableName, recordName) {
      var formData = SelectedData[SelectedData.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            console.log("output[i].previousRemarks", output[i].previousRemarks);
  
            if (output[i].previousRemarks == "") {
              try {
                $("#previousCommentsRemarks").val("No Previous Comments");
                $("#previousCommentsRemarksvalue").val("No Previous Comments");
              } catch (error) {}
            } else {
              try {
                $("#previousCommentsRemarksvalue").val(output[i].previousRemarks);
              } catch (error) {}
              $("#previousCommentsRemarks").val(output[i].previousRemarks);
            }
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    loaddpreviousApproversremarks: function (
      action,
      approver,
      tableName,
      recordName
    ) {
      var formData = Applications[Applications.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
  
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
  
        console.log("formData[index]", formData);
  
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            if (output[i].previousRemarks == "") {
              $("#previousCommentsRemarksvalue").val("No Previous Comments");
              $("#previousCommentsRemarksvaluereject").val(
                "No Previous Comments"
              );
            } else {
              $("#previousCommentsRemarksvalue").val(output[i].previousRemarks);
              $("#previousCommentsRemarksvaluereject").val(
                output[i].previousRemarks
              );
            }
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    loaddPreviousRemarks: function (action, approver, tableName, recordName) {
      var formData = Applications[Applications.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
  
      $.trim($("#tableName").val(tableName));
      $.trim($("#recordName").val(recordName));
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
  
        console.log("formData[index]", formData);
        console.log("formData[index] recordName", formData[recordName]);
  
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            if (output[i].previousRemarks == "") {
              $("#previousCommentsRemarksValue").val("No Previous Comments");
              $("#previousCommentsRemarksvaluereject").val(
                "No Previous Comments"
              );
            } else {
              $("#previousCommentsRemarksValue").val(output[i].previousRemarks);
              $("#previousCommentsRemarksvaluereject").val(
                output[i].previousRemarks
              );
            }
          }
          // getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    confirmDocumentsApprovalActivities: function (
      action,
      approver,
      tableName,
      recordName
    ) {
      var formData = Applications[Applications.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
  
      console.log("confirmDocumentsApprovalActivities", urlParams);
  
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          controller.forwardMany(approver, action);
          return;
        }
        console.log("confirmDocumentsApprovalActivities", formData[recordName]);
  
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            toBeApprovedActivity.push(output[i]);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    confirmDocumentsApproval: function (action, approver, tableName, recordName) {
      var formData = Applications[Applications.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
  
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          controller.forwardMany(approver, action);
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            toBeApprovedActivity.push(output[i]);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    loadPreviousComments: function (tableName, recordName) {
      var formData = SelectedData[SelectedData.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            var htmlview = "";
            var tableHTML = $("#previousapproversremarks");
            htmlview =
              htmlview +
              "<table class='table table-bordered'><tr style='background: #3543B3'></tr>";
            htmlview = htmlview + "<tr>";
            htmlview =
              htmlview + "<td>Remarks: " + output[i].previousRemarks + "</td>";
            htmlview = htmlview + "</tr>";
            htmlview = htmlview + "<tr>";
            htmlview = htmlview + "<td>Message: " + output[i].message + "</td>";
            htmlview = htmlview + "</tr>";
            htmlview = htmlview + "</table>";
            tableHTML.html(htmlview);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
    loadPreviousApproversComment: function (tableID, tableName, recordName) {
      var formData = SelectedData[SelectedData.length - 1];
      var approverID = userObj.id;
      var urlParams =
        "approverID=" +
        approverID +
        "&recordID=" +
        recordName +
        "&tableName=" +
        tableName;
      var getActivities = function (index, formData) {
        if (formData.length == index) {
          return;
        }
        var url =
          serverURL +
          "workflowActivity/findActiveByTableRecordIDApprover?recordID=" +
          formData[index][recordName] +
          "&tableName=" +
          tableName +
          "";
        workflow.getActivity(url, urlParams, function (output) {
          for (let i = 0; i < output.length; i++) {
            var html = "";
            var tableHTML = $(tableID);
            $("#previousRemarks").val(output[i].previousRemarks);
            tableHTML.html(html);
          }
          getActivities(++index, formData);
        });
      };
      getActivities(0, formData);
    },
  
    getCategoryByProduct: function (val) {
      var productID = val;
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      controller.requestWithToken(url, function (data1, status) {
        $("#product_category_id").html();
        option =
          "<option value=" +
          data1["productCategory"].product_category_id +
          ">" +
          data1["productCategory"].name +
          "</option>";
        $("#product_category_id").html(option);
      });
    },
    onChangeLogicForSelect: function (val, formName, editable = false) {
      if (formName == "products") {
        if (
          $("#importValid").val() == "true" ||
          $("#importValid").val() == true
        ) {
          $(".product_family_id_holder").show();
        } else {
          $(".product_family_id_holder").hide();
        }
      }
      if (formName == "onetime_export_variety_details") {
        if (val == "productsID") {
          try {
            var products_id = $("#" + val).val();
            // var countryid = allFormObj["selected"]["countryOfDestination"]["country_id"];
            var url =
              serverURL +
              "productForm/findByProduct?pageNo=0&pageSize=1000&productID=" +
              products_id;
            // var url = serverURL + 'exportRequirement/findProductFormByExportRequiremntCountry?countryId=' + countryid + '&productId=' + products_id + '';
            controller.getPOSTAuthRequest(url, true, function (data, status) {
              var option = "";
              option +=
                "<option selected disabled >--Select Commodity Form--</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].product_form_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              } else {
              }
              $("#productFormID").html();
              $("#productFormID").html(option);
            });
          } catch (error) {}
        }
      }
      if (formName == "exporter") {
        if (
          $("#isOwnFarmExporter").val() == "true" ||
          $("#isOwnFarmExporter").val() == true
        ) {
          var option = "";
          option += '<option selected value="false">No</option>';
          $("#isResearcher").html(option);
        } else if (
          $("#isOwnFarmExporter").val() == "false" ||
          $("#isOwnFarmExporter").val() == false
        ) {
          $(".isResearcher_holder").show();
        }
        if (
          $("#isExportConsolidator").val() == "true" ||
          $("#isExportConsolidator").val() == true
        ) {
          var option = "";
          option += '<option selected value="false">No</option>';
          $("#isResearcher").html(option);
        } else if (
          $("#isExportConsolidator").val() == "false" ||
          $("#isExportConsolidator").val() == false
        ) {
          $(".isResearcher_holder").show();
        }
        if (
          $("#isDryCommodityExporter").val() == "true" ||
          $("#isExportConsolidator").val() == true
        ) {
          var option = "";
          option += '<option selected value="false">No</option>';
          $("#isResearcher").html(option);
        } else if (
          $("#isDryCommodityExporter").val() == "false" ||
          $("#isExportConsolidator").val() == false
        ) {
          $(".isResearcher_holder").show();
        }
        if (val == "isOwnFarmExporter") {
          var isOwnFarmExporter = $("#" + val).val();
          var isdrycommodity = $("#isDryCommodityExporter").val();
          var isExportConsolidator = $("#isExportConsolidator").val();
          var isResearcher = $("#isResearcher").val();
          var exporterID = allFormObj["selected"]["exporterID"];
          var companyID = allFormObj["selected"]["company"]["company_id"];
          if (
            isOwnFarmExporter == "false" &&
            isdrycommodity == "false" &&
            isExportConsolidator == "false"
          ) {
            var option = "";
            option += '<option value="true">Yes</option>';
            option += '<option value="false">No</option>';
            $("#isResearcher").html(option);
          }
          var formJson = {
            isResearcher: isResearcher,
            addressID: "303",
            researchInstituteID: "",
            researcherCategoryID: "",
            isOwnFarmExporter: isOwnFarmExporter,
            isDryCommodityExporter: isdrycommodity,
            isExportConsolidator: isExportConsolidator,
            company_id: company_id,
            exporterID: exporterID,
            users_id: 0,
            active: true,
          };
          var url = serverURL + "exporter/updateExporter";
          controller.updateExporterPostRequest(
            url,
            formJson,
            "",
            function (data, status) {}
          );
        }
        if (val == "isDryCommodityExporter") {
          var isDryCommodityExporter = $("#" + val).val();
          var isOwnFarmExporter = $("#isOwnFarmExporter").val();
          var isExportConsolidator = $("#isExportConsolidator").val();
          var isResearcher = $("#isResearcher").val();
          var exporterID = allFormObj["selected"]["exporterID"];
          var companyID = allFormObj["selected"]["company"]["company_id"];
          if (
            isDryCommodityExporter == "false" &&
            isOwnFarmExporter == "false" &&
            isExportConsolidator == "false"
          ) {
            var option = "";
            option += '<option value="true">Yes</option>';
            option += '<option value="false">No</option>';
            $("#isResearcher").html(option);
          }
          var formJson = {
            isResearcher: isResearcher,
            addressID: "303",
            researchInstituteID: "",
            researcherCategoryID: "",
            isOwnFarmExporter: isOwnFarmExporter,
            isDryCommodityExporter: isDryCommodityExporter,
            isExportConsolidator: isExportConsolidator,
            company_id: company_id,
            exporterID: exporterID,
            users_id: 0,
            active: true,
          };
          var url = serverURL + "exporter/updateExporter";
          controller.updateExporterPostRequest(
            url,
            formJson,
            "",
            function (data, status) {}
          );
        }
        if (val == "isExportConsolidator") {
          var isExportConsolidator = $("#" + val).val();
          var isOwnFarmExporter = $("#isOwnFarmExporter").val();
          var isDryCommodityExporter = $("#isDryCommodityExporter").val();
          var isResearcher = $("#isResearcher").val();
          var exporterID = allFormObj["selected"]["exporterID"];
          var companyID = allFormObj["selected"]["company"]["company_id"];
          if (
            isOwnFarmExporter == "false" &&
            isDryCommodityExporter == "false" &&
            isExportConsolidator == "false"
          ) {
            var option = "";
            option += '<option value="true">Yes</option>';
            option += '<option value="false">No</option>';
            $("#isResearcher").html(option);
          }
          var formJson = {
            isResearcher: isResearcher,
            addressID: "303",
            researchInstituteID: "",
            researcherCategoryID: "",
            isOwnFarmExporter: isOwnFarmExporter,
            isDryCommodityExporter: isDryCommodityExporter,
            isExportConsolidator: isExportConsolidator,
            company_id: company_id,
            exporterID: exporterID,
            users_id: 0,
            active: true,
          };
          var url = serverURL + "exporter/updateExporter";
          controller.updateExporterPostRequest(
            url,
            formJson,
            "",
            function (data, status) {}
          );
        }
        if (val == "isResearcher") {
          var isResearcher = $("#" + val).val();
          if (isResearcher == true || isResearcher == "true") {
            var researchInstituteID = $("#researchInstituteID").val();
            var researcherCategoryID = $("#researcherCategoryID").val();
            var exporterID = allFormObj["selected"]["exporterID"];
            var address = allFormObj["selected"]["address"]["address_id"];
            var companyID = allFormObj["selected"]["company"]["company_id"];
            var formJson = {
              isResearcher: isResearcher,
              addressID: address,
              researchInstituteID: researchInstituteID,
              researcherCategoryID: researcherCategoryID,
              isOwnFarmExporter: false,
              isDryCommodityExporter: false,
              isExportConsolidator: false,
              company_id: company_id,
              exporterID: exporterID,
              users_id: 0,
              active: true,
            };
            var url = serverURL + "exporter/updateExporter";
            controller.updateExporterPostRequest(
              url,
              formJson,
              "",
              function (data, status) {}
            );
  
            isInstitutionletter = true;
            allFormObj["parent_selected"]["isResearcher"] = true;
  
            // if (exporterID) {
            //
            //     controller.loadDocumentsUploadStatus('#Attachments',   serverURL + "exporterDocument/getExporterDocumentByExporterID?exporterID="+exporterID, 322, function () {
            //     });
            //     return;
            // }
  
            var url =
              serverURL +
              "exporterDocument/getExporterDocumentByExporterID?exporterID=" +
              exporterID;
            controller.loadDocumentsUploadStatus(
              "#Attachments",
              url,
              322,
              function (data) {
                // if(data){
                //     $("#").show();
                // }
              }
            );
          }
          if (isResearcher == false || isResearcher == "false") {
            var researchInstituteID = $("#researchInstituteID").val();
            var researcherCategoryID = $("#researcherCategoryID").val();
            var exporterID = allFormObj["selected"]["exporterID"];
            var address = allFormObj["selected"]["address"]["address_id"];
            var companyID = allFormObj["selected"]["company"]["company_id"];
            var formJson = {
              isResearcher: false,
              addressID: address,
              researchInstituteID: "",
              researcherCategoryID: "",
              isOwnFarmExporter: false,
              isDryCommodityExporter: false,
              isExportConsolidator: false,
              company_id: company_id,
              exporterID: exporterID,
              users_id: 0,
              active: true,
            };
            var url = serverURL + "exporter/updateExporter";
            controller.updateExporterPostRequest(
              url,
              formJson,
              "",
              function (data, status) {}
            );
            isInstitutionletter = false;
            allFormObj["parent_selected"]["isResearcher"] = false;
  
            var url =
              serverURL +
              "exporterDocument/getExporterDocumentByExporterID?exporterID=" +
              exporterID;
            controller.loadDocumentsUploadStatus(
              "#Attachments",
              url,
              322,
              function (data) {
                // if(data){
                //     $("#").show();
                // }
              }
            );
  
            //
            // controller.loadDocumentsUploadStatus('#Attachments',   serverURL + "exporterDocument/getExporterDocumentByExporterID?exporterID="+exporterID, 322, function () {
            // });
          }
        }
        if (val == "researchInstituteID") {
          var researchInstituteID = $("#" + val).val();
          var researcherCategoryID = $("#researcherCategoryID").val();
          var exporterID = allFormObj["selected"]["exporterID"];
          var address = allFormObj["selected"]["address"]["address_id"];
          var companyID = allFormObj["selected"]["company"]["company_id"];
          var formJson = {
            isResearcher: true,
            addressID: address,
            researchInstituteID: researchInstituteID,
            researcherCategoryID: researcherCategoryID,
            isOwnFarmExporter: false,
            isDryCommodityExporter: false,
            isExportConsolidator: false,
            company_id: company_id,
            exporterID: exporterID,
            users_id: 0,
            active: true,
          };
          var url = serverURL + "exporter/updateExporter";
          controller.updateExporterPostRequest(
            url,
            formJson,
            "",
            function (data, status) {}
          );
        }
        if (val == "researcherCategoryID") {
          var researcherCategoryID = $("#" + val).val();
          var researchInstituteID = $("#researchInstituteID").val();
          var exporterID = allFormObj["selected"]["exporterID"];
          var address = allFormObj["selected"]["address"]["address_id"];
          var companyID = allFormObj["selected"]["company"]["company_id"];
          var formJson = {
            isResearcher: true,
            addressID: address,
            researchInstituteID: researchInstituteID,
            researcherCategoryID: researcherCategoryID,
            isOwnFarmExporter: false,
            isDryCommodityExporter: false,
            isExportConsolidator: false,
            company_id: company_id,
            exporterID: exporterID,
            users_id: 0,
            active: true,
          };
          var url = serverURL + "exporter/updateExporter";
          controller.updateExporterPostRequest(
            url,
            formJson,
            "",
            function (data, status) {}
          );
        }
      }
      if (formName == "ban_list") {
        if (val == "product_form_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProductFormID(product_form_id);
        }
      }
      if (formName == "import_requirement") {
        if (val == "products_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProduct(product_form_id);
        }
      }
      if (formName == "export_requirement") {
        if (val == "products_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProduct(product_form_id);
        }
      }
      if (formName == "ban_list") {
        if (val == "trading_block_id") {
          var trading_block_id = $("#" + val).val();
          controller.getTradingBlockBanListCountries(trading_block_id);
        }
      }
      if (formName == "quarantineFacilityInspection") {
        if (val == "quarantineFacilityID") {
          var quarantineFacilityID = $("#" + val).val();
          controller.getQProductsByQuarantinefacility(quarantineFacilityID);
        }
      }
      if (formName == "evaluation_application") {
        if (val == "product_form_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProductFormID(product_form_id);
        }
      }
      if (formName == "petRiskAnalysisRequest") {
        if (val == "product_form_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProductFormID(product_form_id);
        }
      }
      if (formName == "export_requirement") {
        if (val == "products_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProduct(product_form_id);
        }
      }
      if (formName == "ban_list") {
        if (val == "products_id") {
          var product_form_id = $("#" + val).val();
          controller.getproductbyProduct(product_form_id);
        }
      }
  
      if (formName == "import_requirement") {
        if (val == "product_form_id") {
          var product_form_id = $("#" + val).val();
          controller.getproducthscodebyProduct(product_form_id);
        }
      }
      if (formName == "export_requirement") {
        if (val == "product_form_id") {
          var product_form_id = $("#" + val).val();
          controller.getproducthscodebyProduct(product_form_id);
        }
      }
  
      if (formName == "export_requirement") {
        if (val == "products_id") {
          var products_id = $("#" + val).val();
          controller.getBotanicalNameExporterrequirement(products_id);
        }
      }
      if (formName == "onetime_export_variety_details") {
        if (val == "productFormID") {
          try {
            var product_form_id = $("#" + val).val();
            var countryid =
              allFormObj["selected"]["countryOfDestination"]["country_id"];
            var products_id = $("#productsID").val();
            var url =
              serverURL +
              "exportRequirement/getExportRequirement?country_id=" +
              countryid +
              "&product_form_id=" +
              product_form_id +
              "&products_id=" +
              products_id +
              "";
            $.ajax({
              url: url,
              contentType: "application/json",
              headers: {
                Authorization: userObj.tokenType + " " + userObj.accessToken,
              },
              type: "post",
              data: formData,
              success: function (data) {
                if (data.products.productCategory.product_category_id != null) {
                  var option = "";
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                  option +=
                    "<option value=" +
                    data.products.productCategory.product_category_id +
                    ">" +
                    data.products.productCategory.name +
                    "</option>";
                  $("#productCategoryID").html();
                  $("#productCategoryID").html(option);
                } else {
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                }
              },
              fail: function (e) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#productCategoryID").html(option);
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#productCategoryID").html(option);
              },
            });
          } catch (error) {}
        }
      }
      if (formName == "onetime_export") {
        if (val == "identification_document_id") {
          var documetid = $("#" + val).val();
          if (documetid == 39054) {
            $(".national_id_holder .control-label").html("Passport");
          } else if (documetid == 39056) {
            $(".national_id_holder .control-label").html("National ID");
          } else if (documetid == 39058) {
            $(".national_id_holder .control-label").html("Aliens");
          }
        }
      }
      if (formName == "product_variety") {
        if (val == "product_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
      }
      if (formName == "exporterConsignment" || formName == "consolidatedPhyto") {
        $(".shippingOrderNumber_holder").hide();
        if (val == "consigneeID") {
          var consigneeID = $("#" + val).val();
          controller.getConsigneeCountry(consigneeID);
        }
        if (val == "seedApplication") {
          if ($("#seedApplication").val() == "true") {
            $(".sr14_no_holder").show();
            document
              .getElementById("sr14_no")
              .setAttribute("data-parsley-required", "true");
            $(".btnvalidatsr14_holder").show();
          } else {
            document
              .getElementById("sr14_no")
              .setAttribute("data-parsley-required", "false");
            document.getElementById("sr14_no").value = "";
            $(".sr14_no_holder").hide();
            $(".btnvalidatsr14_holder").hide();
            $(".sr14_no").val("");
          }
        }
        if (val == "conveyance_means_id") {
          if ($("#conveyance_means_id").val() == 202) {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            setTimeout(function () {
              $(".vesselName_holder").show();
              $(".vesselName_holder .control-label").html("Vessel Name");
              $(".shippingOrderNumber_holder").hide();
            }, 200);
          } else if ($("#conveyance_means_id").val() == 153) {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            setTimeout(function () {
              $(".vesselName_holder .control-label").html("Reg Number");
              $(".vesselName_holder").show();
              $(".shippingOrderNumber_holder").hide();
            }, 200);
          } else if ($("#conveyance_means_id").val() == 152) {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            setTimeout(function () {
              $(".vesselName_holder .control-label").html("Flight Number");
              $(".vesselName_holder").show();
              $(".shippingOrderNumber_holder").hide();
            }, 200);
          } else if ($("#conveyance_means_id").val() == 204) {
            setTimeout(function () {
              $(".vesselName_holder").show();
              $(".shippingOrderNumber_holder").show();
              $(".vesselName_holder .control-label").html("Vessel Name");
            }, 200);
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
          } else {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            $(".vesselName_holder").show();
            $(".shippingOrderNumber_holder").show();
            $(".vesselName_holder .control-label").html("Vessel Name");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
          }
        }
      }
      if (formName == "pipApplicationVarietyRequest") {
        $(".sr14Number_holder").hide();
        if ($("#seed").val() == "true") {
          document
            .getElementById("sr14Number")
            .setAttribute("data-parsley-required", "true");
          $(".sr14Number_holder").show();
        } else if ($("#seed").val() == "false") {
          $(".sr14Number_holder").hide();
          document
            .getElementById("sr14Number")
            .setAttribute("data-parsley-required", "false");
          document.getElementById("sr14Number").value = "N/A";
        }
      }
      if (formName == "exporterProduct") {
        if (val == "productsID") {
          var productsID = $("#" + val).val();
          controller.getproductbyID(productsID);
        }
      }
      if (formName == "exporterFirm" && val == "farm") {
        if ($("#farm").val() == "true") {
          $(".newfarm_holder").hide();
          $(".market_holder").hide();
          $(".fullName_holder").hide();
          $(".email_holder").hide();
          $(".country_id_holder").hide();
          $(".pin_holder").hide();
          $(".postalAddress_holder").hide();
          $(".postalCode_holder").hide();
          $(".streetName_holder").hide();
          $(".telephone_holder").hide();
        } else {
          $(".market_holder").show();
          $(".newfarm_holder").show();
          $(".newfarm_holder").show();
          $(".market_holder").show();
          $(".fullName_holder").show();
          $(".email_holder").show();
          $(".country_id_holder").show();
          $(".pin_holder").show();
          $(".postalAddress_holder").show();
          $(".postalCode_holder").show();
          $(".streetName_holder").show();
          $(".telephone_holder").show();
        }
      }
      if (formName == "exporterFirm" && val == "newfarm") {
        if ($("#newfarm").val() == "true") {
          $(".farm_holder").hide();
          $(".market_holder").hide();
        } else {
          $(".market_holder").show();
          $(".farm_holder").show();
        }
      }
      if (formName == "exporterFirm" && val == "market") {
        if ($("#market").val() == "true") {
          $(".newfarm_holder").hide();
          $(".farm_holder").hide();
          $(".fullName_holder").hide();
          $(".email_holder").hide();
          $(".country_id_holder").hide();
          $(".pin_holder").hide();
          $(".postalAddress_holder").hide();
          $(".postalCode_holder").hide();
          $(".streetName_holder").hide();
          $(".telephone_holder").hide();
          $(".farms_holder").hide();
        } else {
          $(".newfarm_holder").show();
          $(".farm_holder").show();
          $(".farms_holder").show();
          $(".fullName_holder").show();
          $(".email_holder").show();
          $(".country_id_holder").show();
          $(".pin_holder").show();
          $(".postalAddress_holder").show();
          $(".postalCode_holder").show();
          $(".streetName_holder").show();
          $(".telephone_holder").show();
        }
      }
      if (formName == "pipApplicationVarietyRequest") {
        if (val == "importPurposeID") {
          var importpurpose = $("#" + val).val();
          var country = $("#country_of_origin_id").val();
          var url =
            serverURL +
            "importRequirement/findProductByImportRequiremntCountryAndImportPupose?countryId=" +
            country +
            "&importPurposeId=" +
            importpurpose +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            if (data.length > 0) {
              var option = "";
              option += "<option>-Select Commodity-</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].products_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              }
              $("#products_id").html();
              $("#products_id").html(option);
            } else {
              option += "<option>-Select Option-</option>";
              $("#products_id").html(option);
            }
          });
        }
      }
      if (formName == "onetime_import_variety_details") {
        if (val == "importPurposeID") {
          var importpurpose = $("#" + val).val();
          var country_ID = $("#countryID").val();
          var url =
            serverURL +
            "importRequirement/findProductByImportRequiremntCountryAndImportPupose?countryId=" +
            country_ID +
            "&importPurposeId=" +
            importpurpose +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            if (data.length > 0) {
              var option = "";
              option += "<option>-Select Commodity-</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].products_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              }
              $("#productsID").html();
              $("#productsID").html(option);
            } else {
              option += "<option>-Select Commodity-</option>";
              $("#productsID").html(option);
            }
          });
        }
      }
      if (formName == "onetime_import_variety_details") {
        if (val == "productsID") {
          var products_id = $("#" + val).val();
          var country_ID = $("#countryID").val();
          var importpurpose = $("#importPurposeID").val();
          var url =
            serverURL +
            "importRequirement/findProductFormByImportRequiremntCountry?countryId=" +
            country_ID +
            "&importPurposeId=" +
            importpurpose +
            "&productId=" +
            products_id +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = "";
            option +=
              "<option selected disabled >--Select Commodity Form--</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].product_form_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            } else {
            }
            $("#productFormID").html();
            $("#productFormID").html(option);
          });
        }
      }
      if (formName == "onetime_import_variety_details") {
        var products_id = $("#productsID").val();
        var country = $("#countryID").val();
        var product_form_id = $("#productFormID").val();
        var importpurpose = $("#importPurposeID").val();
        var url =
          serverURL +
          "importRequirement/getImportRequirements?country_id=" +
          country +
          "&import_purpose_id=" +
          importpurpose +
          "&product_form_id=" +
          product_form_id +
          "&products_id=" +
          products_id +
          "";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].importCondition.import_condition_id +
                ">" +
                data[i].importCondition.name +
                "</option>";
              $("#description").html(data[i].description);
            }
          } else {
          }
          $("#importConditionID").html(option);
        });
      }
      if (formName == "pipApplicationVarietyRequest") {
        if (val == "products_id") {
          var products_id = $("#" + val).val();
          var country = $("#country_of_origin_id").val();
          var importpurpose = $("#importPurposeID").val();
          var url =
            serverURL +
            "importRequirement/findProductFormByImportRequiremntCountry?countryId=" +
            country +
            "&importPurposeId=" +
            importpurpose +
            "&productId=" +
            products_id +
            "";
          controller.getAuthRequest(url, true, function (data, status) {
            var option = "";
            option +=
              "<option selected disabled >--Select Commodity Form--</option>";
            if (data.length > 0) {
              for (let i = 0; i < data.length; i++) {
                option +=
                  "<option value=" +
                  data[i].product_form_id +
                  ">" +
                  data[i].name +
                  "</option>";
              }
            } else {
            }
            $("#productFormID").html();
            $("#productFormID").html(option);
          });
        }
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        if (val == "products_id") {
          try {
            var products_id = $("#" + val).val();
            var url =
              serverURL +
              "productForm/findByProduct?pageNo=0&pageSize=1000&productID=" +
              products_id;
            // var countryid = allFormObj["selected"]["countryOfDestination"]["country_id"];
            // var url = serverURL + 'exportRequirement/findProductFormByExportRequiremntCountry?countryId=' + countryid + '&productId=' + products_id + '';
            controller.getPOSTAuthRequest(url, true, function (data, status) {
              var option = "";
              option +=
                "<option selected disabled >--Select Commodity Form--</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].product_form_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              } else {
              }
              $("#product_form_id").html();
              $("#product_form_id").html(option);
            });
          } catch (error) {}
        }
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        if (val == "products_id") {
          try {
            var products_id = $("#" + val).val();
            var url =
              serverURL +
              "productForm/findByProduct?pageNo=0&pageSize=1000&productID=" +
              products_id;
            // var countryid = allFormObj["selected"]['exporterConsignment']["countryOfDestination"]["country_id"];
            // var url = serverURL + 'exportRequirement/findProductFormByExportRequiremntCountry?countryId=' + countryid + '&productId=' + products_id + '';
            controller.getPOSTAuthRequest(url, true, function (data, status) {
              var option = "";
              option +=
                "<option selected disabled >--Select Commodity Form--</option>";
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  option +=
                    "<option value=" +
                    data[i].product_form_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              } else {
              }
              $("#product_form_id").html();
              $("#product_form_id").html(option);
            });
          } catch (error) {}
        }
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        if (val == "product_form_id") {
          try {
            var product_form_id = $("#" + val).val();
            var countryid =
              allFormObj["selected"]["countryOfDestination"]["country_id"];
            var products_id = $("#products_id").val();
            var url =
              serverURL +
              "exportRequirement/getExportRequirement?country_id=" +
              countryid +
              "&product_form_id=" +
              product_form_id +
              "&products_id=" +
              products_id +
              "";
            $.ajax({
              url: url,
              contentType: "application/json",
              headers: {
                Authorization: userObj.tokenType + " " + userObj.accessToken,
              },
              type: "post",
              data: formData,
              success: function (data) {
                if (data.products.productCategory.product_category_id != null) {
                  var option = "";
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                  option +=
                    "<option value=" +
                    data.products.productCategory.product_category_id +
                    ">" +
                    data.products.productCategory.name +
                    "</option>";
                  $("#product_category_id").html();
                  $("#product_category_id").html(option);
                } else {
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                }
                if (data.isCOC == true || data.isCOC == "true") {
                  $(".netWeight_holder").show();
                  $(".grossWeight_holder").show();
                  $(".product_class_id_holder").show();
                  $(".produce_nature_id_holder").show();
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("produce_nature_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "true");
                  $("#netWeight").attr("data-required", "true");
                  $("#grossWeight").attr("data-required", "true");
                } else if (data.isCOC == false || data.isCOC == "false") {
                  $(".netWeight_holder").hide();
                  $(".grossWeight_holder").hide();
                  $(".product_class_id_holder").hide();
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "false");
                  $("#netWeight").attr("data-required", "false");
                  $("#grossWeight").attr("data-required", "false");
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "false");
                }
              },
              fail: function (e) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#product_category_id").html(option);
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#product_category_id").html(option);
              },
            });
          } catch (error) {}
        }
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        if (val == "product_form_id") {
          try {
            var product_form_id = $("#" + val).val();
            var countryid =
              allFormObj["selected"]["exporterConsignment"][
                "countryOfDestination"
              ]["country_id"];
            var products_id = $("#products_id").val();
            var url =
              serverURL +
              "exportRequirement/getExportRequirement?country_id=" +
              countryid +
              "&product_form_id=" +
              product_form_id +
              "&products_id=" +
              products_id +
              "";
            $.ajax({
              url: url,
              contentType: "application/json",
              headers: {
                Authorization: userObj.tokenType + " " + userObj.accessToken,
              },
              type: "post",
              data: formData,
              success: function (data) {
                if (data.products.productCategory.product_category_id != null) {
                  var option = "";
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                  option +=
                    "<option value=" +
                    data.products.productCategory.product_category_id +
                    ">" +
                    data.products.productCategory.name +
                    "</option>";
                  $("#product_category_id").html();
                  $("#product_category_id").html(option);
                } else {
                  option +=
                    "<option selected disabled >--Select Category--</option>";
                }
                if (data.isCOC == true || data.isCOC == "true") {
                  $(".netWeight_holder").show();
                  $(".grossWeight_holder").show();
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "true");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "true");
                  $("#netWeight").attr("data-required", "true");
                  $("#grossWeight").attr("data-required", "true");
                } else if (data.isCOC == false || data.isCOC == "false") {
                  $(".netWeight_holder").hide();
                  $(".grossWeight_holder").hide();
                  $("#netWeight").attr("data-required", "false");
                  $("#grossWeight").attr("data-required", "false");
                  document
                    .getElementById("product_class_id")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("netWeight")
                    .setAttribute("data-parsley-required", "false");
                  document
                    .getElementById("grossWeight")
                    .setAttribute("data-parsley-required", "false");
                }
              },
              fail: function (e) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#product_category_id").html(option);
              },
              error: function (XMLHttpRequest, textStatus, errorThrown) {
                var option = "";
                option +=
                  "<option selected disabled >--Select Category--</option>";
                $("#product_category_id").html(option);
              },
            });
          } catch (error) {}
        }
      }
      if (formName == "pipApplicationVarietyRequest") {
        var products_id = $("#products_id").val();
        var country = $("#country_of_origin_id").val();
        var product_form_id = $("#productFormID").val();
        var importpurpose = $("#importPurposeID").val();
        var url =
          serverURL +
          "importRequirement/getImportRequirements?country_id=" +
          country +
          "&import_purpose_id=" +
          importpurpose +
          "&product_form_id=" +
          product_form_id +
          "&products_id=" +
          products_id +
          "";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].importCondition.import_condition_id +
                ">" +
                data[i].importCondition.name +
                "</option>";
              $("#description").html(data[i].description);
            }
          } else {
          }
          $("#importConditionID").html(option);
        });
      }
      if (formName == "pipApplicationVarietyRequest") {
        var products_id = $("#products_id").val();
        var country = $("#country_of_origin_id").val();
        var product_form_id = $("#productFormID").val();
        var importpurpose = $("#importPurposeID").val();
        var url =
          serverURL +
          "importRequirement/getImportRequirements?country_id=" +
          country +
          "&import_purpose_id=" +
          importpurpose +
          "&product_form_id=" +
          product_form_id +
          "&products_id=" +
          products_id +
          "";
        controller.getAuthRequest(url, true, function (data, status) {
          var option = "";
          if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].productFamily.product_family_id +
                ">" +
                data[i].productFamily.name +
                "</option>";
            }
          } else {
          }
          $("#productFamilyId").html();
          $("#productFamilyId").html(option);
        });
      }
      if (formName == "onetime_import") {
        if (val == "fumigation") {
          if ($("#fumigation").val() == "true") {
            $(".fumgCertificateNo_holder").show();
          } else {
            $(".fumgCertificateNo_holder").hide();
          }
        }
      }
      if (formName == "onetime_import") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyanceMeansID").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyanceMeansID").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 204) {
          $(".vesselName_holder").show();
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
        } else if ($("#conveyanceMeansID").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName").show();
          $(".vesselName_holder").hide();
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if (formName == "onetime_export_variety_details") {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
      }
      if (formName == "pipApplicationVarietyRequest") {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalNamePipApplicationvariety(productID, formName);
        }
      }
      if (
        formName == "pipApplicationVarietyRequest" ||
        formName == "onetime_export_variety_details"
      ) {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getproductForm(productID, formName);
        }
      }
      if (formName == "product_variety") {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
      }
      if (formName == "exporterFarm") {
        if (val == "tradingblocks") {
          var tradingBlockID = $("#" + val).val();
          controller.getTradingBlockCountries(tradingBlockID);
          if (tradingBlockID > 1) {
            controller.getTradingBlockCountries(tradingBlockID);
          } else {
            controller.getTradingBlockCountries(tradingBlockID);
          }
        }
      }
      if (formName == "exporterFirm") {
        if (val == "farms") {
          var farmID = $("#" + val).val();
        }
      }
      if (formName == "pip_application") {
        if (
          $("#packaging_type_id").val() == 3 ||
          $("#packaging_type_id").val() == "3"
        ) {
          $(".numberOfPackages_holder").show();
        } else {
          $(".numberOfPackages_holder").hide();
        }
      }
      if (formName == "consignmentInspectionRequest") {
        if (
          $("#packagingMaterial").val() == 3 ||
          $("#packagingMaterial").val() == "3"
        ) {
          $(".containerType_holder").show();
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
        } else {
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
          $(".containerType_holder").hide();
        }
      }
      if (formName == "onetime_import_variety_details") {
        $(".containerType_holder").hide();
        if (
          $("#packagingTypeID").val() == 3 ||
          $("#packagingTypeID").val() == "3"
        ) {
          $(".containerType_holder").show();
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "true");
        } else {
          document
            .getElementById("containerType")
            .setAttribute("data-parsley-required", "false");
          $(".containerType_holder").hide();
        }
      }
      if (formName == "exporter") {
        controller.initializeExporterRegistrationTabs();
        if (val == "researchInstituteID") {
          if (editable) {
            if ($("#isResearcher").val() == "true") {
              // alert("Kindly Save the Document to add Institution Letter")
              controller.refreshCrudTables("documents");
            }
          }
        }
        if (val == "researcherCategoryID") {
          if ($("#researcherCategoryID").val() == "Research Teo") {
          } else {
          }
        }
      }
      if (val == "isResearcher") {
        if (
          $("#isResearcher").val() == "true" ||
          $("#isResearcher").val() == true
        ) {
          $(".Firms_tab_link").hide();
          $(".OwnFarms_tab_link").hide();
          $(".exporterFarmproducts_tab_link").hide();
          $(".isOwnFarmExporter_holder").hide();
          $(".OwnFarmsDestination_tab_link").hide();
          $(".LowRiskCommoditiesRegistration_tab_link").hide();
          $(".isOwnFarmExporter_holder").hide();
          $(".isDryCommodityExporter_holder").hide();
          $(".isExportConsolidator_holder").hide();
          $("#isOwnFarmExporter").val() == "false";
          $("#isDryCommodityExporter").val() == "false";
          $("#isExportConsolidator").val() == "false";
          document
            .getElementById("isOwnFarmExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isDryCommodityExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isExportConsolidator")
            .setAttribute("data-parsley-required", "false");
          try {
            document.getElementsByClassName(
              "researchInstituteID_holder"
            )[0].style.display = "block";
          } catch (e) {}
          try {
            $(".researchInstituteID_holder").show();
            $(".researcherCategoryID_holder").show();
          } catch (e) {}
          try {
            $(".researchInstitute_id_holder").show();
            $(".researcherCategory_id_holder").show();
          } catch (e) {}
        } else {
          $(".isOwnFarmExporter_holder").show();
          $(".isDryCommodityExporter_holder").show();
          $(".isExportConsolidator_holder").show();
          document
            .getElementById("isOwnFarmExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isDryCommodityExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isExportConsolidator")
            .setAttribute("data-parsley-required", "false");
          try {
            document.getElementsByClassName(
              "researchInstituteID_holder"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "researcherCategoryID_holder"
            )[0].style.display = "none";
          } catch (e) {}
          try {
            $(".researchInstituteID_holder").hide();
            $(".researcherCategoryID_holder").hide();
          } catch (e) {}
          try {
            $(".researchInstitute_id_holder").hide();
            $(".researcherCategory_id_holder").hide();
          } catch (e) {}
          $(".researcherCategoryID_holder").on("change", function () {});
        }
      }
      if (formName == "consignmentInspectionRequest") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyance_means_id").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyance_means_id").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#manifestNo").val("");
          $(".vesselName_holder").show();
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 204) {
          $(".vesselName_holder").show();
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyance_means_id").val() == 154) {
          $(".vesselName_holder").show();
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if ($("#conveyance_means_id").val() == 153) {
        $(".billOfLading_holder").hide();
        $(".manifestNo_holder").show();
        $(".awbNumber_holder").hide();
        $("#awbNumber").val("");
        $("#billOfLading").val("");
      } else if ($("#conveyance_means_id").val() == 202) {
        $(".manifestNo_holder").hide();
        $(".awbNumber_holder").hide();
        $(".billOfLading_holder").show();
        $("#awbNumber").val("");
        $("#manifestNo").val("");
      } else if ($("#conveyance_means_id").val() == 152) {
        $(".awbNumber_holder").show();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $("#manifestNo").val("");
      } else {
        $(".sr14_no_holder").hide();
        $(".btnvalidatsr14_holder").hide();
        $("#awbNumber").val("");
        $("#billOfLading").val("");
        $("#manifestNo").val("");
      }
      if (formName == "exporterConsignment" || formName == "consolidatedPhyto") {
        if (
          $("#countryOfOrigin_id").val() == "1" ||
          $("#countryOfOrigin_id").val() == 1
        ) {
          var option = $(
            '<option value="1016">' + "Phytosanitary Certificate" + "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").hide();
          $(".oldContainer_holder").hide();
          $(".repckagingTypeID_holder").hide();
        } else {
          var option = $(
            '<option value="52">' +
              "Re-Export Phytosanitary Certificate" +
              "</option>"
          );
          $("#certificate_type_id").html(option);
          $(".repackaged_holder").show();
          $(".oldContainer_holder").show();
          $(".repckagingTypeID_holder").show();
        }
        if ($("#repackaged").val() == "true" || $("#repackaged").val() == true) {
          $(".repckagingTypeID_holder").show();
        } else {
          $(".repckagingTypeID_holder").hide();
        }
      }
      if (formName == "onetime_import") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyanceMeansID").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyanceMeansID").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName").show();
          $(".vesselName_holder").hide();
        } else if ($("#conveyanceMeansID").val() == 204) {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
          $(".vesselName_holder").show();
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if (formName == "consignmentInspectionRequest") {
        $(".awbNumber_holder").hide();
        $(".manifestNo_holder").hide();
        $(".billOfLading_holder").hide();
        $(".vesselName_holder").hide();
        if ($("#conveyance_means_id").val() == 153) {
          $(".billOfLading_holder").hide();
          $(".manifestNo_holder").show();
          $(".awbNumber_holder").hide();
          $(".vesselName_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
        } else if ($("#conveyance_means_id").val() == 202) {
          $(".manifestNo_holder").hide();
          $(".awbNumber_holder").hide();
          $(".billOfLading_holder").show();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 152) {
          $(".awbNumber_holder").show();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#manifestNo").val("");
          $(".vesselName").show();
          $(".vesselName_holder").hide();
        } else if ($("#conveyance_means_id").val() == 204) {
          $(".vesselName_holder").show();
          $(".shippingOrderNumber_holder").show();
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $("#awbNumber").val("");
          $("#manifestNo").val("");
          $("#billOfLading").val("");
        } else {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".sr14_no_holder").hide();
          $(".btnvalidatsr14_holder").hide();
          $("#awbNumber").val("");
          $("#billOfLading").val("");
          $("#manifestNo").val("");
        }
      }
      if (formName == "exporterConsignment" || formName == "consolidatedPhyto") {
        if (val == "consigneeID") {
          var consigneeID = $("#" + val).val();
          controller.getConsigneeCountry(consigneeID);
        }
        if (val == "seedApplication") {
          if ($("#seedApplication").val() == "true") {
            $(".sr14_no_holder").show();
            document
              .getElementById("sr14_no")
              .setAttribute("data-parsley-required", "true");
            $(".btnvalidatsr14_holder").show();
          } else {
            document
              .getElementById("sr14_no")
              .setAttribute("data-parsley-required", "false");
            document.getElementById("sr14_no").value = "";
            $(".sr14_no_holder").hide();
            $(".btnvalidatsr14_holder").hide();
            $(".sr14_no").val("");
          }
        }
        if (val == "conveyance_means_id") {
          if ($("#conveyance_means_id").val() == 202) {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            $(".vesselName_holder").show();
            $(".vesselName_holder .control-label").html("Vessel Name");
          } else if ($("#conveyance_means_id").val() == 153) {
            $(".vesselName_holder .control-label").html("Reg Number");
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            $(".vesselName_holder").show();
          } else if ($("#conveyance_means_id").val() == 152) {
            $(".vesselName_holder .control-label").html("Flight Number");
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            $(".vesselName_holder").show();
          } else {
            document
              .getElementById("vesselName")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
            $(".vesselName_holder").show();
            $(".vesselName_holder .control-label").html("Vessel Name");
          }
        }
        if (formName == "consignmentInspectionRequest") {
          $(".awbNumber_holder").hide();
          $(".manifestNo_holder").hide();
          $(".billOfLading_holder").hide();
          $(".vesselName_holder").hide();
          if ($("#conveyance_means_id").val() == 153) {
            $(".billOfLading_holder").hide();
            $(".manifestNo_holder").show();
            $(".awbNumber_holder").hide();
            $(".vesselName_holder").hide();
            $("#awbNumber").val("");
            $("#billOfLading").val("");
          } else if ($("#conveyance_means_id").val() == 202) {
            $(".manifestNo_holder").hide();
            $(".awbNumber_holder").hide();
            $(".billOfLading_holder").show();
            $("#awbNumber").val("");
            $("#manifestNo").val("");
            $(".vesselName_holder").hide();
          } else if ($("#conveyance_means_id").val() == 152) {
            $(".awbNumber_holder").show();
            $(".manifestNo_holder").hide();
            $(".billOfLading_holder").hide();
            $("#manifestNo").val("");
            $(".vesselName").show();
            $(".vesselName_holder").hide();
          } else if ($("#conveyance_means_id").val() == 204) {
            $(".vesselName_holder").show();
            $(".shippingOrderNumber_holder").show();
            $(".awbNumber_holder").hide();
            $(".manifestNo_holder").hide();
            $(".billOfLading_holder").hide();
            $("#awbNumber").val("");
            $("#manifestNo").val("");
            $("#billOfLading").val("");
            document
              .getElementById("shippingOrderNumber")
              .setAttribute("data-parsley-required", "false");
          } else {
            $(".awbNumber_holder").hide();
            $(".manifestNo_holder").hide();
            $(".billOfLading_holder").hide();
            $(".sr14_no_holder").hide();
            $(".btnvalidatsr14_holder").hide();
            $("#awbNumber").val("");
            $("#billOfLading").val("");
            $("#manifestNo").val("");
          }
        }
        if (val == "countryOfOrigin_id") {
          if ($("#countryOfOrigin_id").val() == 1) {
            $(".originalIssuingCountry_id_holder").hide();
            $(".certificateNumber_holder").hide();
            $("#certificate_type_id").val() == 1;
          } else {
            $("#certificate_type_id").val() == 52;
            $(".originalIssuingCountry_id_holder").show();
            $(".certificateNumber_holder").show();
          }
        }
      }
      if (formName == "consolidatedPhyto") {
        if ($("#seedApplication").val() == "true") {
          document
            .getElementsByClassName("sr14_no_holder")[0]
            .setAttribute("data-parsley-required", "true");
          $(".sr14_no_holder").show();
        } else {
          document
            .getElementsByClassName("sr14_no_holder")[0]
            .setAttribute("data-parsley-required", "false");
          $(".sr14_no_holder").hide();
        }
        if ($("#conveyanceMeans_id").val() == 202) {
          document
            .getElementsByClassName("vesselName_holder")[0]
            .setAttribute("data-parsley-required", "true");
          $(".vesselName_holder").show();
        } else {
          document
            .getElementsByClassName("vesselName_holder")[0]
            .setAttribute("data-parsley-required", "false");
          $(".vesselName_holder").hide();
        }
        if ($("#countryOfOrigin_id").val() == 1) {
          $(".originalIssuingCountry_id_holder").hide();
          $(".certificateNumber_holder").hide();
          $("#certificate_type_id").val() == 1;
        } else {
          $("#certificate_type_id").val() == 52;
          $(".originalIssuingCountry_id_holder").show();
          $(".certificateNumber_holder").show();
        }
        if (val == "consigneeID") {
          var consigneeID = $("#" + val).val();
          controller.getConsigneeCountry(consigneeID);
        }
      }
      if (formName == "exporterConsignmentVarietyDetails") {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
        if (val == "requirestreatmentqry") {
          if ($("#requirestreatmentqry").val() == "true") {
            $("#chemicalIngredients").val("");
            $("#concentration").val("");
            $("#temperature").val("");
            $("#durationInTemperature").val("");
            $("#treatmentDate").val("");
            $("#treatmentDetails").val("");
            document.getElementById("chemicalIngredients").disabled = false;
            document.getElementById("concentration").disabled = false;
            document.getElementById("temperature").disabled = false;
            document.getElementById("durationInTemperature").disabled = false;
            document.getElementById("treatmentDate").disabled = false;
            document.getElementById("treatmentDetails").disabled = false;
  
            document
              .getElementById("chemicalIngredients")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("concentration")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("temperature")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("durationInTemperature")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("treatmentDate")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("treatmentDetails")
              .setAttribute("data-parsley-required", "true");
          } else {
            $("#chemicalIngredients").val("***");
            $("#concentration").val("***");
            $("#temperature").val("***");
            $("#durationInTemperature").val("***");
            $("#treatmentDate").val("***");
            $("#treatmentDetails").val("***");
            document.getElementById("chemicalIngredients").disabled = true;
            document.getElementById("concentration").disabled = true;
            document.getElementById("temperature").disabled = true;
            document.getElementById("durationInTemperature").disabled = true;
            document.getElementById("treatmentDate").disabled = true;
            document.getElementById("treatmentDetails").disabled = true;
  
            document
              .getElementById("chemicalIngredients")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("concentration")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("temperature")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("durationInTemperature")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("treatmentDate")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("treatmentDetails")
              .setAttribute("data-parsley-required", "false");
          }
        }
      }
      if (formName == "onetime_export_variety_details") {
        if (val == "requirestreatmentonetime") {
          if ($("#requirestreatmentonetime").val() == "true") {
            $("#chemicalIngredients").val("");
            $("#concentration").val("");
            $("#temperature").val("");
            $("#durationInTemperature").val("");
            $("#treatmentDate").val("");
            $("#treatmentDetails").val("");
            document.getElementById("chemicalIngredients").disabled = false;
            document.getElementById("concentration").disabled = false;
            document.getElementById("temperature").disabled = false;
            document.getElementById("durationInTemperature").disabled = false;
            document.getElementById("treatmentDate").disabled = false;
            document.getElementById("treatmentDetails").disabled = false;
  
            document
              .getElementById("chemicalIngredients")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("concentration")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("temperature")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("durationInTemperature")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("treatmentDate")
              .setAttribute("data-parsley-required", "true");
            document
              .getElementById("treatmentDetails")
              .setAttribute("data-parsley-required", "true");
          } else {
            $("#chemicalIngredients").val("***");
            $("#concentration").val("***");
            $("#temperature").val("***");
            $("#durationInTemperature").val("***");
            $("#treatmentDate").val("***");
            $("#treatmentDetails").val("***");
            document.getElementById("chemicalIngredients").disabled = true;
            document.getElementById("concentration").disabled = true;
            document.getElementById("temperature").disabled = true;
            document.getElementById("durationInTemperature").disabled = true;
            document.getElementById("treatmentDate").disabled = true;
            document.getElementById("treatmentDetails").disabled = true;
  
            document
              .getElementById("chemicalIngredients")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("concentration")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("temperature")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("durationInTemperature")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("treatmentDate")
              .setAttribute("data-parsley-required", "false");
            document
              .getElementById("treatmentDetails")
              .setAttribute("data-parsley-required", "false");
          }
        }
      }
      if (formName == "inspectionRequirements") {
        if ($("#inspectionTypeID").val() == 1) {
          $("#isfarmMonthly").removeAttr("disabled");
          $("#isfarmEstablishment").removeAttr("disabled");
          $("#isfarmNonconformity").removeAttr("disabled");
          $(".isfarmMonthly_holder").show();
          $(".isfarmEstablishment_holder").show();
          $(".isfarmNonconformity_holder").show();
          if ($("#isfarmEstablishment").val() == "true") {
            $(".isfarmMonthly_holder").hide();
            $(".isfarmNonconformity_holder").hide();
          } else if ($("#isfarmEstablishment").val() == "false") {
            $(".isfarmMonthly_holder").show();
            $(".isfarmNonconformity_holder").show();
          }
          if ($("#isfarmMonthly").val() == "true") {
            $(".isfarmEstablishment_holder").hide();
            $(".isfarmNonconformity_holder").hide();
          } else if ($("#isfarmMonthly").val() == "false") {
            $(".isfarmEstablishment_holder").show();
            $(".isfarmNonconformity_holder").show();
          }
          if ($("#isfarmNonconformity").val() == "true") {
            $(".isfarmMonthly_holder").hide();
            $(".isfarmEstablishment_holder").hide();
          } else if ($("#isfarmNonconformity").val() == "false") {
            $(".isfarmEstablishment_holder").show();
            $(".isfarmMonthly_holder").show();
          }
        } else {
          $("#isfarmEstablishment").val() == "";
          $("#isfarmMonthly").val() == "";
          $("#isfarmNonconformity").val() == "";
          $("#isfarmMonthly").prop("disabled", true);
          $("#isfarmMonthly").attr("disabled", true);
          $("#isfarmEstablishment").prop("disabled", true);
          $("#isfarmEstablishment").attr("disabled", true);
          $("#isfarmNonconformity").prop("disabled", true);
          $("#isfarmNonconformity").attr("disabled", true);
          $(".isfarmMonthly_holder").hide();
          $(".isfarmEstablishment_holder").hide();
          $(".isfarmNonconformity_holder").hide();
        }
      }
      if (formName == "inspectionRequirement") {
        var value = $("#isfarmEstablishment").val();
        if (value == "true" || value == true) {
          $(".isfarmMonthly_holder").hide();
          $(".isfarmNonconformity_holder").hide();
          $(".isfarmNonconformity_holder").css("display", "none");
        } else if (value == "false" || value == false) {
          $(".isfarmMonthly_holder").show();
          $(".isfarmNonconformity_holder").show();
        }
        var isfarmmonthly = $("#isfarmMonthly").val();
        if (isfarmmonthly == "true" || isfarmmonthly == true) {
          $(".isfarmEstablishment_holder").hide();
          $(".isfarmNonconformity_holder").hide();
        } else if (isfarmmonthly == "false" || isfarmmonthly == false) {
          $(".isfarmEstablishment_holder").show();
          $(".isfarmNonconformity_holder").show();
        }
        if ($("#isfarmNonconformity").val() == "true") {
          $(".isfarmMonthly_holder").hide();
          $(".isfarmEstablishment_holder").hide();
        } else if ($("#isfarmNonconformity").val() == "false") {
          $(".isfarmEstablishment_holder").show();
          $(".isfarmMonthly_holder").show();
        }
      }
      if (formName == "exporterFarm") {
        if ($("#fallow").val() == "true" || $("#fallow").val() == true) {
          $(".previousCropsID_holder").hide();
        } else {
          $(".previousCropsID_holder").show();
        }
        if (val == "trading_block_id") {
          var tradingBlockID = $("#" + val).val();
          controller.getTradingBlockCountries(tradingBlockID);
        }
      }
      if (formName == "ban_list") {
        if (val == "trading_block_id") {
          var tradingBlockID = $("#" + val).val();
          controller.getTradingBlockBanListCountries(tradingBlockID);
        }
      }
      if (
        formName == "exporterFarm" ||
        formName == "region" ||
        formName == "regionCounty" ||
        formName == "userlocationdetails" ||
        formName == "ward" ||
        formName == "exportLowRiskCommodity" ||
        formName == "exporterFirm"
      ) {
        if (val == "county_id") {
          var county_id = $("#" + val).val();
          controller.getSubCountyByID(county_id, formName);
        }
        if (val == "subcounty_id") {
          var subcounty_id = $("#" + val).val();
          controller.getwardBySubCounty(subcounty_id, formName);
        }
        if (val == "productss_id") {
          var productID = $("#" + val).val();
          var url =
            serverURL +
            "product/getProductsByID?id=" +
            productID +
            "&pageNo=0&pageSize=100";
          controller.requestWithToken(url, function (data1, status) {
            $("#product_category_id").html();
            option =
              "<option value=" +
              data1["productCategory"].product_category_id +
              ">" +
              data1["productCategory"].name +
              "</option>";
            $("#product_category_id").html(option);
          });
        }
      }
      if (formName == "exporterFarmInspection") {
        if (val == "exporterID") {
          var exporterid = $("#" + val).val();
          controller.getExporterFarmByExporter(exporterid, formName);
        }
      }
      if (formName == "consignmentInspectionRequest") {
        if (val == "company_id") {
          var company_id = $("#" + val).val();
          controller.getPIPApplicationByCompany(company_id, formName);
        }
      }
      if (formName == "exporterLowRiskInspection") {
        if (val == "exporterID") {
          var exporterid = $("#" + val).val();
          controller.getExporterLowRiskFacilityByExporter(exporterid, formName);
        }
      }
      if (formName == "quarantineFacilityInspection") {
        if (val == "importerID") {
          var importerid = $("#" + val).val();
          controller.getImporterQuarantineFacilityByImporter(importerid);
        }
      }
      if (formName == "pipApplicationVariety") {
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
      }
      if (
        formName == "pip_application" ||
        formName == "farmestablishmentsinspectionRequirement" ||
        formName == "farmMonthlyinspectionRequirement" ||
        formName == "nonConformityinspectionRequirement" ||
        formName == "pip_applicationrequest"
      ) {
        if (val == "product_category_id") {
          var productCategoryID = $("#" + val).val();
          controller.getProductByCategory(productCategoryID);
          controller.getProductFormByCategory(productCategoryID);
        }
        if (val == "products_id") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
        if (val == "importer_exporterid") {
          var importer_exporterid = $("#" + val).val();
          controller.getImporter_exporterCountry(importer_exporterid);
        }
        if (formName == "pip_application" && setupObj["agent_mgt"]) {
          if (val == "company_id") {
            var company_id = $("#" + val).val();
            controller.getImpExpByCompany(company_id);
          }
        }
      }
      if (formName == "onetime_import_variety_details") {
        if (val == "productCategoryID") {
          var productCategoryID = $("#" + val).val();
          controller.getcommodityByCategory(productCategoryID);
        }
        if (val == "productsID") {
          var productID = $("#" + val).val();
          controller.getcomodityBotanicalName(productID, formName);
        }
      }
      if (formName == "importer_product") {
        if (val == "product_category_id") {
          var productCategoryID = $("#" + val).val();
          controller.getImporterProductByCategory(productCategoryID);
        }
      }
      if (formName == "exporterConsignment" && setupObj["company"]) {
        if (val == "company_id") {
          var company_id = $("#" + val).val();
          controller.getConsigneeByCompany(company_id);
        }
      }
      if (formName == "consignmentInspectionRequest" && setupObj["agent_mgt"]) {
        if (val == "company_id") {
          var company_id = $("#" + val).val();
          controller.getpipByCompany(company_id);
        }
      }
      if (formName == "exporterFirm") {
        if (val == "farm") {
          if ($("#farm").val() == "true") {
            $(".farms_holder").show();
          } else {
            $(".farms_holder").hide();
          }
        }
      }
      if (formName == "pip_application") {
        if (val == "is_seed") {
          if ($("#is_seed").val() == "true") {
            $(".btnvalidatsr14_holder").show();
            document
              .getElementById("sr14_number")
              .setAttribute("data-parsley-required", "true");
            $(".btnvalidatsr14_holder").show();
            document
              .getElementsByClassName("sr14_number_holder")[0]
              .setAttribute("data-parsley-required", "true");
            document.getElementsByClassName(
              "sr14_number_holder"
            )[0].style.display = "block";
          } else {
            document
              .getElementsByClassName("sr14_number_holder")[0]
              .setAttribute("data-parsley-required", "false");
            document
              .getElementsByClassName("sr14_number_holder")[0]
              .setAttribute("data-parsley-required", "false");
            document.getElementsByClassName(
              "sr14_number_holder"
            )[0].style.display = "none";
            $(".btnvalidatsr14_holder").hide();
          }
        }
      }
      if (
        formName == "onetime_import_variety_details" ||
        formName == "onetime_export_variety_details"
      ) {
        if (val == "seed") {
          if ($("#seed").val() == "true") {
            document
              .getElementById("sr14Number")
              .setAttribute("data-parsley-required", "true");
            document.getElementsByClassName(
              "sr14Number_holder"
            )[0].style.display = "block";
          } else {
            document
              .getElementById("sr14Number")
              .setAttribute("data-parsley-required", "false");
            document.getElementsByClassName(
              "sr14Number_holder"
            )[0].style.display = "none";
          }
        }
        if (val == "productsID") {
          var productID = $("#" + val).val();
          controller.getBotanicalName(productID, formName);
        }
        if (val == "productCategoryID") {
          var productCategoryID = $("#" + val).val();
          var url =
            serverURL +
            "product/findByProductCategory?productCategoryID=" +
            productCategoryID +
            "&pageNo=0&pageSize=100";
          var formData = {
            productCategoryID: productCategoryID,
            pageNo: "1",
            pageSize: "100",
          };
          controller.allPostgetRequest(
            url,
            formData,
            true,
            function (data, status) {
              var option = "";
              if (data.length > 0) {
                controller.getBotanicalName(data[0].products_id, "");
                for (let i = 0; i < data.length; i++) {
                  options += "<option>-Select Category-</option>";
                  option +=
                    "<option value=" +
                    data[i].products_id +
                    ">" +
                    data[i].name +
                    "</option>";
                }
              } else {
                option += "<option selected disabled >Select a Category</option>";
              }
              $("#productsID").html();
              $("#productsID").html(option);
            }
          );
        }
      }
    },
    getPIPApplicationByCompany: function (company_id, formName) {
      var url =
        serverURL +
        "pipApplication/getPIPApplicationByCompany?companyID=" +
        company_id +
        "";
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        option += "<option>-Select Import Permit-</option>";
        $("#farms").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].pipApplicationID +
            ">" +
            data[i].pipApplicationID +
            "</option>";
          $("#pip_application_id").html(option);
        }
      });
    },
    initializeExporterRegistrationTabs: function () {
      try {
        if (
          $("#isResearcher").val() == "true" ||
          $("#isResearcher").val() == true
        ) {
          $(".Firms_tab_link").hide();
          $(".OwnFarms_tab_link").hide();
          $(".exporterFarmproducts_tab_link").hide();
          $(".isOwnFarmExporter_holder").hide();
          $(".OwnFarmsDestination_tab_link").hide();
          $(".LowRiskCommoditiesRegistration_tab_link").hide();
          $(".isOwnFarmExporter_holder").hide();
          $(".isDryCommodityExporter_holder").hide();
          $(".isExportConsolidator_holder").hide();
          $("#isDryCommodityExporter").val() == "false";
          $("#isExportConsolidator").val() == "false";
          document
            .getElementById("isOwnFarmExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isDryCommodityExporter")
            .setAttribute("data-parsley-required", "false");
          document
            .getElementById("isExportConsolidator")
            .setAttribute("data-parsley-required", "false");
          try {
            document.getElementsByClassName(
              "researchInstituteID_holder"
            )[0].style.display = "block";
          } catch (e) {}
          try {
            $(".researchInstituteID_holder").show();
            $(".researcherCategoryID_holder").show();
          } catch (e) {}
          try {
            $(".researchInstitute_id_holder").show();
            $(".researcherCategory_id_holder").show();
          } catch (e) {}
        } else {
          try {
            document.getElementsByClassName(
              "researchInstituteID_holder"
            )[0].style.display = "none";
            document.getElementsByClassName(
              "researcherCategoryID_holder"
            )[0].style.display = "none";
          } catch (e) {}
          try {
            $(".researchInstituteID_holder").hide();
            $(".researcherCategoryID_holder").hide();
          } catch (e) {}
          try {
            $(".researchInstitute_id_holder").hide();
            $(".researcherCategory_id_holder").hide();
          } catch (e) {}
          $(".researcherCategoryID_holder").on("change", function () {});
          if (
            $("#isOwnFarmExporter").val() == "true" ||
            $("#isOwnFarmExporter").val() == true
          ) {
            $(".OwnFarms_tab_link").show();
            $(".exporterFarmproducts_tab_link").show();
          } else if (
            $("#isOwnFarmExporter").val() == "false" ||
            $("#isOwnFarmExporter").val() == false
          ) {
            $(".OwnFarms_tab_link").hide();
            $(".exporterFarmproducts_tab_link").hide();
          }
          if (
            $("#isExportConsolidator").val() == "true" ||
            $("#isExportConsolidator").val() == true
          ) {
            $(".Firms_tab_link").show();
          } else if (
            $("#isExportConsolidator").val() == "false" ||
            $("#isExportConsolidator").val() == false
          ) {
            $(".Firms_tab_link").hide();
          }
          if (
            $("#isDryCommodityExporter").val() == "true" ||
            $("#isDryCommodityExporter").val() == true
          ) {
            $(".LowRiskCommoditiesRegistration_tab_link").show();
          } else if (
            $("#isDryCommodityExporter").val() == "false" ||
            $("#isDryCommodityExporter").val() == false
          ) {
            $(".LowRiskCommoditiesRegistration_tab_link").hide();
          }
        }
      } catch (error) {}
    },
    getExporterFarmByExporter: function (exporterid, formName) {
      var url =
        serverURL +
        "exporterFarm/getExporterFarmByExporter?exporterID=" +
        exporterid +
        "&pageNo=0&pageSize=100";
      var formData = {
        exporterID: exporterid,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        if (data.length > 0) {
          var option = "";
          option += "<option>-Select Exporter Farm-</option>";
          $("#farms").html();
          $("#exporterFarmID").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].exporterFarmID +
              ">" +
              data[i].farmName +
              "</option>";
            $("#farms").html(option);
            $("#exporterFarmID").html(option);
          }
        } else {
          $("#exporterFarmID").val("");
          controller.showToastMsg(
            "Selected Exporter has No Registered Farm",
            "#ff6666"
          );
          controller.refreshCrudTables();
        }
      });
    },
    getExporterLowRiskFacilityByExporter: function (exporterid, formName) {
      var url =
        serverURL +
        "exporterLowRiskCommodity/getExporterLowRiskCommodityByExporter?exporterID=" +
        exporterid +
        "&pageNo=0&pageSize=100";
      var formData = {
        exporterID: exporterid,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        if (data.length > 0) {
          var option = "";
          option += "<option>-Select Warehouse-</option>";
          $("#exporterLowRiskCommodityID").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].exportLowRiskCommodityID +
              ">" +
              data[i].farmName +
              "</option>";
            $("#exporterLowRiskCommodityID").html(option);
          }
        } else {
          $("#exporterLowRiskCommodityID").val("");
          controller.showToastMsg(
            "Selected Importer has No Warehouse",
            "#ff6666"
          );
          controller.refreshCrudTables();
        }
      });
    },
    getImporterQuarantineFacilityByImporter: function (importerid) {
      var url =
        serverURL +
        "quarantineFacility/getQuarantineFacilityByImporter?importerID=" +
        importerid +
        "&pageNo=0&pageSize=100";
      var formData = {
        importerID: importerid,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        if (data.length > 0) {
          var option = "";
          option += "<option>-Select Quarantine Facility-</option>";
          $("#quarantineFacilityID").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].quarantineFacilityID +
              ">" +
              data[i].name +
              "</option>";
            $("#quarantineFacilityID").html(option);
          }
        } else {
          $("#quarantineFacilityID").val("");
          controller.showToastMsg(
            "Selected Importer has No Quarantine Facility",
            "#ff6666"
          );
          controller.refreshCrudTables();
        }
      });
    },
    getSelectedSubCountyByID: function (county_id, subcounty_id, formName) {
      var url =
        serverURL +
        "subCounty/getSubCountyByCounty?countID=" +
        county_id +
        "&pageNo=0&pageSize=100";
      var formData = {
        countID: county_id,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        for (var i = 0; i < data.length; i++) {
          if (data[i].subcounty_id == subcounty_id) {
            option +=
              "<option selected value=" +
              subcounty_id +
              ">" +
              data[i].name +
              "</option>";
          } else {
            option +=
              "<option value=" +
              data[i].subcounty_id +
              ">" +
              data[i].name +
              "</option>";
          }
        }
        $("#subcounty_id").html(option);
      });
    },
    getSubCountyByID: function (county_id, formName) {
      var url =
        serverURL +
        "subCounty/getSubCountyByCounty?countID=" +
        county_id +
        "&pageNo=0&pageSize=100";
      var formData = {
        countID: county_id,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        option += "<option>-Select District-</option>";
        controller.getwardBySubCounty(data[0].subcounty_id, formName);
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].subcounty_id +
            ">" +
            data[i].name +
            "</option>";
        }
        $("#subcounty_id").html(option);
      });
    },
    getselectedCountry: function () {
      var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        $("#country_id").html();
        option += controller.loadSelect(data, "country_id", "name", "");
        for (var i = 0; i < data.length; i++) {
          option += "<option selected value=1>ETHIOPIA</option>";
          $("#country_id").html(option);
        }
      });
    },
    getselectedwardBySubCounty: function (subcounty_id, formName, ward_id) {
      var url =
        serverURL +
        "ward/wardListySubCountyID?subCountyID=" +
        subcounty_id +
        "&pageNo=0&pageSize=100";
      var formData = {
        countID: subcounty_id,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        for (var i = 0; i < data.length; i++) {
          if (data[i].ward_id == ward_id) {
            option +=
              "<option selected value=" +
              ward_id +
              ">" +
              data[i].name +
              "</option>";
          } else {
            option +=
              "<option value=" +
              data[i].ward_id +
              ">" +
              data[i].name +
              "</option>";
          }
          $("#ward_id").html(option);
        }
      });
    },
    getwardBySubCounty: function (subcounty_id, formName) {
      var url =
        serverURL +
        "ward/wardListySubCountyID?subCountyID=" +
        subcounty_id +
        "&pageNo=0&pageSize=100";
      var formData = {
        countID: subcounty_id,
        pageNo: "1",
        pageSize: "100",
      };
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        option += "<option>- Select City -</option>";
        $("#ward_id").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" + data[i].ward_id + ">" + data[i].name + "</option>";
          $("#ward_id").html(option);
        }
      });
    },
    getcomodityBotanicalName: function (productID, formname) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          $("#botanicalName").val(data.botanicalName);
        }
      );
    },
    getuserRoles: function (productID, formname) {
      var url = serverURL + "roles/roleList?pageNo=0&pageSize=1000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].roleName +
            ">" +
            data[i].name +
            "</option>";
          $("#roleName").html(option);
          $("#roleName").html(option);
        }
      });
    },
    getBotanicalNameExporterrequirement: function (productID) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      controller.getProductPostRequest(url, "", true, function (data, status) {
        if (allFormObj["pip_application"]) {
          if (formname == "pipApplicationVariety") {
            $("#botanicalName").val(data.botanicalName);
          } else {
            $("#botanical_name").val(data.botanicalName);
          }
        } else {
          $("#botanicalName").val(data.botanicalName);
        }
      });
    },
    getBotanicalNamePipApplicationvariety: function (productID, formname) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          $("#botanicalName").val(data.botanicalName);
          $("#botanicalName_val").val(data.botanicalName);
          $("#botanicalNameVal").val(data.botanicalName);
          $("#botanicalNameValue").val(data.botanicalName);
        }
      );
    },
    getBotanicalName: function (productID, formname) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          if (allFormObj["pip_application"]) {
          } else {
            $("#botanicalName").val(data.botanicalName);
          }
          if (formname == "pipApplicationVariety") {
            $("#botanicalName").val(data.botanicalName);
          } else {
            $("#botanical_name").val(data.botanicalName);
          }
        }
      );
    },
    getBotanicalNameVariety: function (productID) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          if (data) {
            try {
              $("#botanicalName").val(data.botanicalName);
              $("#botanicalName_2").val(data.botanicalName);
              $("#botanicalName_3").val(data.botanicalName);
            } catch (error) {}
            try {
              var option = "";
              option +=
                "<option selected value=" +
                data.productCategory.product_category_id +
                ">" +
                data.productCategory.name +
                "</option>";
              $("#product_category_id").html(option);
            } catch (error) {}
          } else {
            $("#botanicalName").val(data.botanicalName);
          }
        }
      );
    },
    populateInspectionCheclist: function (recordID, data) {
      $(".modal.fade.inspectionphytoformformmodal").modal("show");
      var html = "";
      $.ajax({
        url:
          serverURL +
          "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
          recordID,
        headers: {
          Authorization: userObj.tokenType + " " + userObj.accessToken,
        },
        async: true,
        success: function (data) {
          var requiredQuestions = data;
          var jsonData = data;
          var documentTypesUploaded = [];
          var tableHTML = $("#inspectionphytoform");
          var num = 0;
          var tmpCat = "";
          html = html + "<table class='table table-striped'>";
          html = html + "</table>";
          for (var i = 0; i < requiredQuestions.length; i++) {
            for (var j = 0; j < jsonData.length; j++) {
              var t = jsonData[j];
              if (
                jsonData[j]["inspectionLineID"] ==
                requiredQuestions[i]["inspectionLineID"]
              ) {
                html = html + '<div class="three fields">';
                html = html + '<div class="field">';
                html = html + '<div class="field" id="survey_label">';
                html = html + "<label>Product</label>";
                html =
                  html +
                  '<label style="color:black;">' +
                  requiredQuestions[i]["exportRequirement"]["products"]["name"] +
                  "</label>";
                html =
                  html +
                  '<input type="text" style="display:none" id=' +
                  requiredQuestions[i]["inspectionLineID"] +
                  ' value="' +
                  requiredQuestions[i]["inspectionLineID"] +
                  '">';
                html =
                  html +
                  '<input type="text" style="display:none" id="inspectionHeaderID" value="' +
                  recordID +
                  '">';
                html = html + "</div>";
                html = html + "</div>";
                html = html + '<div class="field">';
                html = html + "<label>Requirement</label>";
                html =
                  html +
                  '<label style="color:black;">' +
                  requiredQuestions[i]["exportRequirement"]["description"] +
                  "</label>";
                html =
                  html +
                  '<input type="text" style="display:none" id="export_requirement_id" value="' +
                  requiredQuestions[i]["exportRequirement"][
                    "export_requirement_id"
                  ] +
                  '">';
                html = html + "</div>";
                html = html + '<div class="field">';
                html = html + "<label>Observations</label>";
                html =
                  html +
                  '<select onchange=controller.getobservations("' +
                  requiredQuestions[i]["status"] +
                  "_remarks" +
                  '") id="status" class="ui fluid dropdown">';
                html = html + '<option value="" selected>-Pending-</option>';
                html = html + '<option value="Yes">Yes</option>';
                html = html + '<option value="No">No</option>';
                html = html + "</select>";
                html = html + "</div>";
                html = html + "</div>";
                html = html + '<div class="field">';
                html = html + '<div class="field">';
                html = html + '<label style="color:black;">Remarks</label>';
                html =
                  html +
                  '<textarea id="remarks"  class="form-control" style=" min-width:500px !important; max-width:100%;min-height:50px;height:100%;width:100%;" ></textarea>';
                html = html + "</div>";
                html = html + "</div>";
              }
            }
          }
          tableHTML.html(html);
          $("#inspectionphytoform").show();
        },
        fail: function () {
          $("#blinder").hide();
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          $("#blinder").hide();
        },
      });
    },
    getproductForm: function (productID, formname) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=100";
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          option +=
            "<option value=" +
            data.productCategory.product_category_id +
            ">" +
            data.productCategory.name +
            "</option>";
          $("#product_category_id").html();
          $("#product_category_id").html(option);
        }
      );
    },
    getCertbyId: function (certId, formname) {
      var url =
        serverURL +
        "certificateType/getCertificateTypeByID?certificateTypeID=" +
        certId;
      var formData = {
        id: productID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.allPostRequest(url, formData, true, function (data, status) {
        $("#certificate_type_id").val(data.name);
      });
    },
    getofficeLocation: function (office_location_id, formName) {
      var url =
        serverURL + "officeLocation/officeLocationList?pageNo=0&pageSize=100";
      var option = "--Select Location--";
      controller.getAuthRequest(url, true, function (data, status) {
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].office_location_id +
            ">" +
            data[i].name +
            "</option>";
          $("#office_location_ID").html(option);
        }
      });
    },
    getproductslist: function () {
      var url = serverURL + "product/productList?pageNo=0&pageSize=10000";
      var option = "--Select Location--";
      controller.getAuthRequest(url, true, function (data, status) {
        $("#productId").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].products_id +
            ">" +
            data[i].name +
            "</option>";
          $("#productId").html(option);
        }
      });
    },
    getlicensingbodies: function () {
      var url =
        serverURL + "licensingBody/licensingBodyList?pageNo=0&pageSize=1000";
      var option = "--Select Location--";
      controller.getAuthRequest(url, true, function (data, status) {
        $("#licensingbodyid").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].licensingBodyID +
            ">" +
            data[i].name +
            "</option>";
          $("#licensingbodyid").html(option);
        }
      });
    },
    getregions: function (region_id, formName) {
      var url = serverURL + "region/regionList?pageNo=0&pageSize=100";
      var option = "";
      controller.getAuthRequest(url, true, function (data, status) {
        $("#region_id").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].regionID +
            ">" +
            data[i].name +
            "</option>";
          $("#region_id").html(option);
        }
      });
    },
    getconsigneedetailsOnModal: function () {
      var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        $("#countryid").html();
        option += "<option selected disabled >--Select Country--</option>";
        option += controller.loadSelect(data, "country_id", "name", "");
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option data-tokens=" +
            data[i].name +
            " value=" +
            data[i].country_id +
            ">" +
            data[i].name +
            "</option>";
          $("#countryid").html(option);
        }
      });
      controller.requestWithToken(
        serverURL + "exporter/getExporterByCompanyID",
        function (data1, status) {
          var exporterID = data1[0].exporterID;
          var name = data1[0].company.name;
          var option2 = "";
          $("#exporter_id").html(data1[0].company.name);
          for (var i = 0; i < data1.length; i++) {
            option2 +=
              "<option value=" +
              data1[i].exporterID +
              ">" +
              data1[i].company.name +
              "</option>";
            $("#exporter_id").html(option2);
          }
        }
      );
    },
    getlaboffice: function () {
      var url =
        serverURL + "officeLocation/officeLocationList?pageNo=0&pageSize=100";
      var option = "--Select Office Location--";
      controller.getAuthRequest(url, true, function (data, status) {
        $("#office_location_id").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].office_location_id +
            ">" +
            data[i].name +
            "</option>";
          $("#office_location_id").html(option);
        }
      });
    },
    getPhytopreprintDetails: function (country_id, formName) {
      controller.requestWithToken(
        serverURL + "api/validateuser",
        function (data1, status) {
          var users_id = data1.usedetails.users_id;
          var url =
            serverURL +
            "assignAuthorisation/getPhytoPrintedByUser?userID=" +
            users_id +
            "";
          controller.requestWithToken(url, function (data1, status) {
            var option2 = "";
            $("#pipApplicationID").html();
            for (var i = 0; i < data1.length; i++) {
              option2 +=
                "<option value=" +
                data1[i].exporterConsignment.exporterConsignmentID +
                ">" +
                data1[i].exporterConsignment.documentNumber +
                "</option>";
              $("#pipApplicationID").html(option2);
            }
          });
        }
      );
    },
    getPhytopreprintDetailsByExporter: function (country_id, formName) {
      controller.requestWithToken(
        serverURL + "exporter/getExporterByCompanyID",
        function (data1, status) {
          var exporterID = data1[0].exporterID;
          var url =
            serverURL +
            "exporterConsignment/getApprovedExporterConsignmentByExporter?exporterID=" +
            exporterID +
            "";
          controller.requestWithToken(url, function (data1, status) {
            var option2 = "";
            $("#pipApplicationID").html();
            for (var i = 0; i < data1.length; i++) {
              option2 +=
                "<option value=" +
                data1[i].exporterConsignmentID +
                ">" +
                data1[i].documentNumber +
                "</option>";
              $("#pipApplicationID").html(option2);
            }
          });
        }
      );
    },
    getPipreprintDetails: function (country_id, formName) {
      controller.requestWithToken(
        serverURL + "api/validateuser",
        function (data1, status) {
          var users_id = data1.usedetails.users_id;
          var url =
            serverURL +
            "assignAuthorisation/getPipPrintedByUser?userID=" +
            users_id +
            "";
          controller.requestWithToken(url, function (data1, status) {
            if (data1.length > 0) {
              controller.hide_progress();
              var option2 = "";
              $("#pipApplicationID").html();
              for (var i = 0; i < data1.length; i++) {
                option2 +=
                  "<option value=" +
                  data1[i].pipApplication.pipApplicationID +
                  ">" +
                  data1[i].pipApplication.documentNumber +
                  "</option>";
                $("#pipApplicationID").html(option2);
              }
            } else {
              option2 += "<option selected disabled >Select Country</option>";
            }
          });
        }
      );
    },
    getImportConsignmentReprintDetails: function (country_id, formName) {
      controller.requestWithToken(
        serverURL + "api/validateuser",
        function (data1, status) {
          var users_id = data1.usedetails.users_id;
          var url =
            serverURL +
            "assignAuthorisation/getConsignemntInspectionPrintedByUser?userID=" +
            users_id +
            "";
          controller.requestWithToken(url, function (data1, status) {
            var option2 = "";
            $("#pipApplicationID").html();
            for (var i = 0; i < data1.length; i++) {
              option2 +=
                "<option value=" +
                data1[i].consignmentInspectionRequest
                  .consignmentInspectionRequestID +
                ">" +
                data1[i].consignmentInspectionRequest.documentNumber +
                "</option>";
              $("#pipApplicationID").html(option2);
            }
          });
        }
      );
    },
    getexporterdetails: function (country_id, formName) {
      var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        $("#country_id").html();
        if (data.length > 0) {
          option += "<option selected disabled >Select Country</option>";
          option += controller.loadSelect(data, "country_id", "name", "");
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].country_id +
              ">" +
              data[i].name +
              "</option>";
          }
          $("#country_id").html(option);
          $("#country_id").html();
        } else {
          option += "<option selected disabled >Select Country</option>";
        }
      });
      controller.requestWithToken(
        serverURL + "importer/getImporterByCompanyID",
        function (data1, status) {
          var importerID = data1[0].importerID;
          var option2 = "";
          $("#importerID").html(data1[0].company.name);
          for (var i = 0; i < data1.length; i++) {
            option2 +=
              "<option value=" +
              data1[i].importerID +
              ">" +
              data1[i].company.name +
              "</option>";
            $("#importerID").html(option2);
          }
        }
      );
    },
    getImporterProductByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "importerProduct/getImporterProductByProductCategory?productID=" +
        productCategoryID;
      var formData = {
        productID: productCategoryID,
      };
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        if (data.length > 0) {
          $("#importer_product_id").html(data[0].ImporterProductID);
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].ImporterProductID +
              ">" +
              data[i].ImporterProductID +
              "</option>";
            $("#importer_product_id").html(option);
          }
        } else {
          option += "<option selected disabled >Select Product</option>";
        }
      });
    },
    getProductByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "product/findByProductCategory?productCategoryID=" +
        productCategoryID +
        "&pageNo=0&pageSize=100";
      var formData = {
        productCategoryID: productCategoryID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          if (data.length > 0) {
            option += "<option>-Select Commodity-</option>";
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].products_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            option += "<option selected disabled >Select Category</option>";
          }
          $("#products_id").html();
          $("#products_id").html(option);
        }
      );
    },
    getProductOTimeByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "product/findByProductCategory?productCategoryID=" +
        productCategoryID +
        "&pageNo=0&pageSize=100";
      var formData = {
        productCategoryID: productCategoryID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          if (data.length > 0) {
            option += "<option>-Select Commodity-</option>";
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].products_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            option += "<option selected disabled >Select Category</option>";
          }
          $("#productsID").html();
          $("#productsID").html(option);
        }
      );
    },
    getcommodityByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "product/findByProductCategory?productCategoryID=" +
        productCategoryID +
        "&pageNo=0&pageSize=100";
      var formData = {
        productCategoryID: productCategoryID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          if (data.length > 0) {
            option += "<option>-Select Commodity-</option>";
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].products_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            option += "<option selected disabled >Select Category</option>";
          }
          $("#productsID").html();
          $("#productsID").html(option);
        }
      );
    },
    getOTProductFormByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "productForm/findByProductCategory?productCategoryID=" +
        productCategoryID +
        "&pageNo=0&pageSize=100";
      var formData = {
        productCategoryID: productCategoryID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          if (data.length > 0) {
            option += "<option>-Select Commodity Form-</option>";
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].product_form_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            option += "<option selected disabled >Select a Category</option>";
          }
          $("#productFormID").html();
          $("#productFormID").html(option);
        }
      );
    },
    getProductFormByCategory: function (productCategoryID) {
      var url =
        serverURL +
        "productForm/findByProductCategory?productCategoryID=" +
        productCategoryID +
        "&pageNo=0&pageSize=100";
      var formData = {
        productCategoryID: productCategoryID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getProductPostRequest(
        url,
        formData,
        true,
        function (data, status) {
          var option = "";
          if (data.length > 0) {
            option += "<option>-Select Commodity Form-</option>";
            for (let i = 0; i < data.length; i++) {
              option +=
                "<option value=" +
                data[i].product_form_id +
                ">" +
                data[i].name +
                "</option>";
            }
          } else {
            option += "<option selected disabled >Select a Category</option>";
          }
          $("#product_form_id").html();
          $("#product_form_id").html(option);
        }
      );
    },
    getImporter_exporterCountry: function (importer_exporterid, formname) {
      var url =
        serverURL +
        "importerExporter/getImporterExporterByID?importerExporterID=" +
        importer_exporterid +
        "&pageNo=0&pageSize=100";
      var formData = {
        importerExporterID: importer_exporterid,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getImorterExportAuthRequest(url, true, function (data, status) {
        var option = "";
        option +=
          "<option value=" +
          data.country.country_id +
          ">" +
          data.country.name +
          "</option>";
        $("#country_of_exporter_id").html();
        $("#country_of_exporter_id").html(option);
      });
    },
    getproductbyID: function (productID) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=10000";
      controller.allPostgetproductRequest(url, true, function (data, status) {});
    },
    getproductbyviewID: function (productID) {
      var url =
        serverURL +
        "product/getProductsByID?id=" +
        productID +
        "&pageNo=0&pageSize=10000";
      controller.allPostgetproductviewRequest(
        url,
        true,
        function (data, status) {}
      );
    },
    getConsigneeCountry: function (consigneeID, formname) {
      var url =
        serverURL +
        "consignee/getConsigneeByID?consigneeID=" +
        consigneeID +
        "&pageNo=0&pageSize=10000";
      var formData = {
        consigneeID: consigneeID,
        pageNo: "1",
        pageSize: "100",
      };
      controller.getAuthRequest(url, true, function (data, status) {
        var option = $("<option>--Select Option--</option>");
        option.attr("value", data.country.country_id);
        option.text(data.country.name);
        $("#consigneeCountry_id").html();
        $("#consigneeCountry_id").html(option);
      });
    },
    getproductbyProductFormID: function (product_form_id) {
      var url =
        serverURL +
        "productForm/findByProduct?pageNo=0&pageSize=100&productID=" +
        product_form_id;
      controller.requestWithTokenPOST(url, "", function (data, status) {
        var option = "";
        if (data.length > 0) {
          option += "<option>-Select Commodity-</option>";
          for (let i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].products_id +
              ">" +
              data[i].name +
              "</option>";
            $("#product_form_id").html(option);
          }
        } else {
          option += "<option selected disabled >- No Commodity found</option>";
          $("#products_id").html(option);
        }
      });
    },
  
    getproducthscodebyProduct: function (product_form_id) {
      var url =
        serverURL +
        "hscodeMapping/findByProductForm?productFormId=" +
        product_form_id;
      controller.getAuthRequest(url, "", function (data, status) {
        if (data) {
          try {
            $("#hscode").val(data[0].hsCode.code);
          } catch (error) {}
        } else {
          $("#hscode").val("N/A");
        }
      });
    },
  
    getproductbyProduct: function (product_form_id) {
      var url =
        serverURL +
        "productForm/findByProduct?pageNo=0&pageSize=100&productID=" +
        product_form_id;
      controller.requestWithTokenPOST(url, "", function (data, status) {
        var option = "";
        if (data.length > 0) {
          option += "<option>-Select Commodity-</option>";
          for (let i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].product_form_id +
              ">" +
              data[i].name +
              "</option>";
            $("#product_form_id").html(option);
          }
        } else {
          option += "<option selected disabled >- No Commodity found</option>";
          $("#product_form_id").html(option);
        }
      });
    },
    gettradingBlockCountriesBytradingBlockID: function (tradingBlockID) {
      var url =
        serverURL +
        "tradingblockcountry/getTradingBlockCountryByTradingBlock?pageNo=0&pageSize=100000&tradingBlockID=" +
        tradingBlockID;
      controller.requestWithToken(url, function (data, status) {
        var option = "";
        if (data.length > 0) {
          option += "<option>-Select Country-</option>";
          for (let i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].country.country_id +
              ">" +
              data[i].country.name +
              "</option>";
            $("#country_id").html(option);
          }
        } else {
          option += "<option selected disabled >Select Country</option>";
        }
      });
    },
    getQProductsByQuarantinefacility: function (quarantineFacilityID) {
      var url =
        serverURL +
        "quarantineFacilityProduct/getQuarantineFacilityProductByQFacility?quarantineFacilityID=" +
        quarantineFacilityID;
      controller.requestWithToken(url, function (data, status) {
        var option = "";
        if (data.length > 0) {
          option += "<option>-Select Country-</option>";
          for (let i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].country.country_id +
              ">" +
              data[i].country.name +
              "</option>";
            $("#products").html(option);
          }
        } else {
          option += "<option selected disabled >Select Commodity</option>";
        }
      });
    },
    getimportRequirementsproductsfamily: function (productFamilyID) {
      var url =
        serverURL +
        "product/findByProductFamily?productFamilyID=" +
        productFamilyID +
        "&pageNo=0&pageSize=100";
      controller.requestWithTokenPOST(url, "", function (data, status) {
        var option = "";
        if (data.length > 0) {
          option += "<option>-Select Commodity-</option>";
          for (let i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].products_id +
              ">" +
              data[i].name +
              "</option>";
            $("#products_id").html(option);
          }
        } else {
          option += "<option selected disabled >- No Commodity found</option>";
          $("#products_id").html(option);
        }
      });
    },
    getTradingBlockBanListCountries: function (tradingBlockID, formname) {
      var url =
        serverURL +
        "tradingblockcountry/getTradingBlockCountryByTradingBlock?pageNo=0&pageSize=1000&tradingBlockID=" +
        tradingBlockID +
        "";
      controller.getAuthRequest(url, true, function (data, status) {
        var countries = [];
        countries = data;
        var option = $("<li>--Select Option--</li>");
        $("#country_idList").html("");
        if (data[0] == undefined || data[0] == "undefined") {
          $("#country_idList").html(option);
          $("#country_idList").multiselect("refresh");
          $("#country_idList").multiselect("rebuild");
          $("#country_idList").multiselect("refresh");
        } else {
          $("#country_idList").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option selected value=" +
              data[i].country.country_id +
              ">" +
              data[i].country.name +
              "</option>";
          }
          $("#country_idList").html(option);
          $("#country_idList").multiselect("refresh");
          $("#country_idList").multiselect("rebuild");
          $("#country_idList").multiselect("refresh");
        }
      });
    },
    getQProductsByQuarantinefacility: function (quarantineFacilityID) {
      var url =
        serverURL +
        "quarantineFacilityProduct/getQuarantineFacilityProductByQFacility?quarantineFacilityID=" +
        quarantineFacilityID +
        "";
      controller.getAuthRequest(url, true, function (data, status) {
        var countries = [];
        countries = data;
        var option = $("<li>--Select Option--</li>");
        $("#products").html("");
        if (data[0] == undefined || data[0] == "undefined") {
          $("#products").html(option);
          $("#products").multiselect("refresh");
          $("#products").multiselect("rebuild");
          $("#products").multiselect("refresh");
        } else {
          $("#products").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option selected value=" +
              data[i].products.products_id +
              ">" +
              data[i].products.name +
              "</option>";
          }
          $("#products").html(option);
          $("#products").multiselect("refresh");
          $("#products").multiselect("rebuild");
          $("#products").multiselect("refresh");
        }
      });
    },
    getcountries: function () {
      var url = serverURL + "countries/countryList?pageNo=0&pageSize=10000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        $("#countryOfDestinationselect").html();
        $("#countryOfOriginselect").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].country_id +
            ">" +
            data[i].name +
            "</option>";
          $("#countryOfDestinationselect").html(option);
          $("#countryOfOriginselect").html(option);
        }
      });
    },
    getAllproducts: function () {
      var url = serverURL + "product/productList?pageNo=0&pageSize=10000";
      controller.getAuthRequest(url, true, function (data, status) {
        var option = "";
        $("#productselect").html();
        for (var i = 0; i < data.length; i++) {
          option +=
            "<option value=" +
            data[i].products_id +
            ">" +
            data[i].name +
            "</option>";
          $("#productselect").html(option);
        }
      });
    },
    geteporterFarmDetails: function (farmID) {
      var url =
        serverURL +
        "exporterFarm/getExporterFarmByID?exporterFarmID=" +
        farmID +
        "";
      controller.getAuthRequest(url, true, function (data, status) {});
    },
    getTradingBlockCountries: function (tradingBlockID, formname) {
      var url =
        serverURL +
        "tradingblockcountry/getTradingBlockCountryByTradingBlock?pageNo=0&pageSize=1009&tradingBlockID=" +
        tradingBlockID +
        "";
      controller.getAuthRequest(url, true, function (data, status) {
        var countries = [];
        countries = data;
        var option = $("<li>--Select Option--</li>");
        $("#tradingcountries").html("");
        if (data[0] == undefined || data[0] == "undefined") {
          $("#tradingcountries").html(option);
          $("#tradingcountries").multiselect("refresh");
          $("#tradingcountries").multiselect("rebuild");
          $("#tradingcountries").multiselect("refresh");
        } else {
          $("#tradingcountries").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option selected value=" +
              data[i].country.country_id +
              ">" +
              data[i].country.name +
              "</option>";
          }
          $("#tradingcountries").html(option);
          $("#tradingcountries").multiselect("refresh");
          $("#tradingcountries").multiselect("rebuild");
          $("#tradingcountries").multiselect("refresh");
        }
      });
    },
    getConsigneeByCompany: function (company_id) {
      var option = "";
      var url =
        serverURL +
        "consignee/getConsigneeByCompany?companyID=" +
        company_id +
        "&pageNo=0&pageSize=100";
      controller.getAuthRequest(url, true, function (data, status) {
        if (data.length > 0) {
          option +=
            "<option selected value=" +
            "" +
            ">" +
            "--Select Consignee--" +
            "</option>";
          $("#consigneeID").html();
          for (var i = 0; i < data.length; i++) {
            option +=
              "<option value=" +
              data[i].consigneeID +
              ">" +
              data[i].name +
              "</option>";
            $("#consigneeID").html(option);
          }
        } else {
          option += "<option selected>" + "--No Consignee found--" + "</option>";
  
          $("#consigneeID").html(option);
        }
      });
      // controller.setUpObjInitializeSpecificOne(url, 'consignee', function (data) {
      //     controller.loadOptionsAfresh('consigneeID', 'consignee', 'consigneeID');
      // });
    },
    getImpExpByCompany: function (company_id) {
      var url =
        serverURL +
        "importerExporter/getImporterExporterByCompany?companyID=" +
        company_id;
      controller.setUpObjInitializeSpecificOne(
        url,
        "importerExporter",
        function (data) {
          controller.loadOptionsAfresh(
            "importer_exporterid",
            "importerExporter",
            "importerExporterID"
          );
        }
      );
    },
    getpipByCompany: function (company_id) {
      var url =
        serverURL +
        "pipApplication/getPIPApplicationByCompany?companyID=" +
        company_id;
      controller.setUpObjInitializeSpecificOne(
        url,
        "pipApplication",
        function (data) {
          controller.loadOptionsAfresh(
            "pip_application_id",
            "pipApplication",
            "pipApplicationID"
          );
        }
      );
    },
    loadOptionsAfresh: function (selectID, obj_name, val_name) {
      var options = "";
      if (setupObj[obj_name].length == 0) {
        options += "<option>No Value</option>";
      } else {
        for (i in setupObj[obj_name]) {
          if (setupObj[obj_name][i]["name"]) {
            options +=
              "<option value='" +
              setupObj[obj_name][i][val_name] +
              "'>'" +
              setupObj[obj_name][i]["name"] +
              "'</option>";
          } else if (setupObj[obj_name][i]["documentNumber"]) {
            options +=
              "<option value='" +
              setupObj[obj_name][i][val_name] +
              "'>'" +
              setupObj[obj_name][i]["documentNumber"] +
              "'</option>";
          }
        }
      }
      $("#" + selectID + "").html(options);
    },
    assignPostRelease: function (date) {
      var inspector = document.getElementById("nextInspector").value;
      var data = SelectedData[SelectedData.length - 1];
      var url = serverURL + "assignInspection/assignInspection";
      var async_status = true;
      if (date) {
        var nextDate = date;
        for (i in data) {
          data[i].consignment_inspection_request_id =
            data[i].consignmentInspectionRequestID;
          data[i].proposedInspectionDate = nextDate;
          data[i].users_id = inspector;
        }
      } else {
        for (i in data) {
          data[i].consignment_inspection_request_id =
            data[i].consignmentInspectionRequestID;
          data[i].proposedInspectionDate = data[i].preferedInspectionDate;
          data[i].users_id = inspector;
        }
      }
      controller.allPostRequest(url, data, async_status, function (data, status) {
        if (data) {
          controller.showToastMsg("Assigned Successfuly", "#1a5589");
        }
        SelectedData = [];
      });
    },
    assignPrinting: function (doc) {
      var inspector = document.getElementById("nextInspector").value;
      var data = SelectedData[SelectedData.length - 1];
      var url = serverURL + "assignAuthorisation/assignAuthorisation";
      var async_status = true;
      if (doc == "Phyto") {
        for (i in data) {
          data[i].exporterConsignmentID = data[i].exporterConsignmentID;
          data[i].pip = false;
          data[i].phyto = true;
          data[i].users_id = inspector;
          data[i].assigned = true;
        }
      } else if (doc == "Pip") {
        for (i in data) {
          data[i].pip_application_id = data[i].pipApplicationID;
          data[i].pip = true;
          data[i].phyto = false;
          data[i].users_id = inspector;
          data[i].assigned = true;
        }
      } else if ((doc = "importReleaseForm")) {
        for (i in data) {
          data[i].consignment_inspection_request_id =
            data[i].consignmentInspectionRequestID;
          data[i].pip = false;
          data[i].phyto = false;
          data[i].users_id = inspector;
          data[i].assigned = true;
        }
      }
      controller.assignPrintingFunc(
        url,
        data,
        async_status,
        function (data, status) {
          SelectedData = [];
        }
      );
    },
    signPrint: function (doc) {
      var data = SelectedData[SelectedData.length - 1];
      for (i in data) {
        ids.push({
          assignAuthorityID: data[i].assign_authorisation_id,
        });
      }
      var async_status = true;
      var url = serverURL + "print/" + doc + "";
      controller.postRequest(url, ids, async_status, function (data, status) {
        if (data.status == 500) {
          controller.showToastMsg(
            "Failed Printing Document, Try again...",
            "#ff6666"
          );
          controller.refreshCrudTables();
        } else if (data != null) {
          var binary = "";
          var responseTextLen = data.length;
          for (i = 0; i < responseTextLen; i++) {
            binary += String.fromCharCode(data.charCodeAt(i) & 255);
          }
          var base64 = btoa(binary);
  
          function downloadPDF() {
            const linkSource = `data:application/pdf;base64,${base64}`;
            const downloadLink = document.createElement("a");
            const fileName = "Application.pdf";
            downloadLink.href = linkSource;
            downloadLink.download = fileName;
            downloadLink.click();
          }
          downloadPDF();
          controller.refreshCrudTables();
          /**
           * Display a base64 URL inside an iframe in another window.
           */
        } else {
          controller.showToastMsg("Kindly Select Document to print", "#ff6666");
        }
        ids = [];
        SelectedData = [];
      });
    },
    getInspectors: function (tableRegisterID) {
      var inspectorList = "";
      var activity = [];
      var approvers = [];
      var users = [];
  
      // Add default option with the selected attribute
      inspectorList += "<option selected value=''>-Select Inspector-</option>";
  
      url1 = serverURL + "workflowActivity/getWorkFlowActivityByUser";
      var async_status = true;
      controller.getAuthRequest(url1, async_status, function (data, status) {
        try {
          for (let i = 0; i < data.length; i++) {
            const element = data[i];
            activity.push(data[i]);
  
            var nodeID = data[i].wFNode.wFNode_id;
            var users_id = data[i].initiator_id.users_id;
            var url =
              serverURL +
              "workflowActivity/getNextApproversList?nodeId=" +
              nodeID +
              "&initaitor_id=" +
              users_id +
              "&tableRegisterId=" +
              tableRegisterID;
            var async_status = true;
            controller.getAuthRequest(url, async_status, function (data, status) {
              if (data.length > 0) {
                for (let i = 0; i < data.length; i++) {
                  var duplicate = false;
                  for (let j = 0; j < approvers.length; j++) {
                    if (data[i].users_id == approvers[j].users_id) {
                      duplicate = true;
                      break;
                    }
                  }
                  if (!duplicate) {
                    approvers.push(data[i]);
                    inspectorList +=
                      "<option value=" +
                      data[i].users_id +
                      ">" +
                      data[i].firstName +
                      "   " +
                      data[i].lastName +
                      "</option>";
                    // $('.nextInspector').html(inspectorList);
                  }
                }
              } else {
              }
  
              // Once all data is processed, set the options in the select element
              $(".nextInspector").html(inspectorList);
            });
          }
        } catch (error) {}
      });
    },
    signPrintDraft: function (doc, data, typeReport) {
      controller.show_progress();
      var exporterconsid = data.exporterConsignmentID;
      if (data.exporterConsignmentID) {
        var async_status = true;
        var url =
          serverURL +
          "exporterConsignmentVarietyDetails/getExporterConsignmentVarietyDetailsByExporterConsignment?exporterConsignmentID=" +
          exporterconsid +
          "";
        controller.getAuthRequest(url, async_status, function (data1, status) {
          if (data1.length > 0) {
            var ids = "";
            var idsString = "";
            if (typeReport == 1) {
              ids = "exporter_consignment_id=" + data["exporterConsignmentID"];
            } else {
              ids = "exporter_consignment_id=" + data["exporterConsignmentID"];
            }
            var async_status = true;
            var url = serverURL + "print/" + doc + "?" + ids;
            controller.postRequest(
              url,
              ids,
              async_status,
              function (data, status) {
                if (data.status == 500) {
                  controller.showToastMsg(
                    "Kindly select the document and try again. If error persists contact EAA Admin",
                    "#ff6666"
                  );
                } else {
                  var binary = "";
                  var responseTextLen = data.length;
                  for (i = 0; i < responseTextLen; i++) {
                    binary += String.fromCharCode(data.charCodeAt(i) & 255);
                  }
                  var base64 = btoa(binary);
  
                  function downloadPDF() {
                    const linkSource = `data:application/pdf;base64,${base64}`;
                    const downloadLink = document.createElement("a");
                    const fileName = "Draft.pdf";
                    downloadLink.href = linkSource;
                    downloadLink.download = fileName;
                    downloadLink.click();
                  }
                  downloadPDF();
                  controller.refreshCrudTables();
                }
                ids = [];
              }
            );
          } else {
            controller.showToastMsg(
              "Kindly check If You have Filled Consignment Variety Details",
              "#ff6666"
            );
          }
        });
      } else if (data.exporterConsignment.exporterConsignmentID) {
        var exporterconsID = data.exporterConsignment.exporterConsignmentID;
        var async_status = true;
        var url =
          serverURL +
          "exporterConsignmentVarietyDetails/getExporterConsignmentVarietyDetailsByExporterConsignment?exporterConsignmentID=" +
          exporterconsID +
          "";
        controller.getAuthRequest(url, async_status, function (data1, status) {
          if (data1.length > 0) {
            var ids = "";
            var idsString = "";
            if (typeReport == 1) {
              ids = "exporter_consignment_id=" + data["exporterConsignmentID"];
            } else {
              ids =
                "exporter_consignment_id=" +
                data["exporterConsignment"]["exporterConsignmentID"];
            }
            var async_status = true;
            var url = serverURL + "print/" + doc + "?" + ids;
            controller.postRequest(
              url,
              ids,
              async_status,
              function (data, status) {
                if (data.status == 500) {
                  controller.showToastMsg(
                    "Kindly select the document and try again. If error persists contact EAA Admin",
                    "#ff6666"
                  );
                } else {
                  var binary = "";
                  var responseTextLen = data.length;
                  for (i = 0; i < responseTextLen; i++) {
                    binary += String.fromCharCode(data.charCodeAt(i) & 255);
                  }
                  var base64 = btoa(binary);
  
                  function downloadPDF() {
                    const linkSource = `data:application/pdf;base64,${base64}`;
                    const downloadLink = document.createElement("a");
                    const fileName = "Exporter Consignment Application.pdf";
                    downloadLink.href = linkSource;
                    downloadLink.download = fileName;
                    downloadLink.click();
                  }
                  downloadPDF();
                  controller.refreshCrudTables();
                  /**
                   * Display a base64 URL inside an iframe in another window.
                   */
                }
                ids = [];
              }
            );
          } else {
            controller.showToastMsg(
              "Kindly check If You have Filled Consignment Variety Details",
              "#ff6666"
            );
          }
        });
      } else {
        controller.showToastMsg(
          "Kindly click on the Item again, If error Persists, Contact EAA Admin",
          "#ff6666"
        );
      }
    },
    signPiPPrintDraft: function (doc, data, typeReport) {
      var pipApplicationID = data.pipApplicationID;
      if (data.pipApplicationID) {
        var ids = "";
        var idsString = "";
        if (typeReport == 1) {
          ids = "pipApplicationID=" + pipApplicationID;
        } else {
          ids = "pipApplicationID=" + data["pipApplicationID"];
        }
        var async_status = true;
        var url = serverURL + "print/" + doc + "?" + ids;
        controller.postRequest(url, ids, async_status, function (data, status) {
          if (data.status == 500) {
            controller.showToastMsg(
              "Kindly select the document and try again. If error persists contact EAA Admin",
              "#ff6666"
            );
          } else {
            var binary = "";
            var responseTextLen = data.length;
            for (i = 0; i < responseTextLen; i++) {
              binary += String.fromCharCode(data.charCodeAt(i) & 255);
            }
            var base64 = btoa(binary);
  
            function downloadPDF() {
              const linkSource = `data:application/pdf;base64,${base64}`;
              const downloadLink = document.createElement("a");
              const fileName = "PIP Application.pdf";
              downloadLink.href = linkSource;
              downloadLink.download = fileName;
              downloadLink.click();
            }
            downloadPDF();
            controller.refreshCrudTables();
          }
          ids = [];
        });
      } else {
        controller.showToastMsg(
          "Kindly click on the Item again, If error Persists, Contact EAA Admin",
          "#ff6666"
        );
      }
    },
    printInterceptionReport: function (doc, data, typeReport) {
      if (data.consignmentInspectionRequestID) {
        var ids = "";
        var idsString = "";
        if (typeReport == 1) {
          ids = data["consignmentInspectionRequestID"];
        } else {
          ids = data["importConsignment"]["consignmentInspectionRequestID"];
        }
        var async_status = true;
        var url = serverURL + "print/" + doc;
        var postData = [ids];
        controller.postRequest(
          url,
          postData,
          async_status,
          function (data, status) {
            if (data.status == 500) {
              controller.showToastMsg(
                "Failed Printing Report, Kindly Contact EAA Admin",
                "#ff6666"
              );
            } else if (data.status == 400) {
              controller.showToastMsg(
                "Failed Printing Report, Kindly Contact EAA Admin",
                "#ff6666"
              );
            } else {
              var binary = "";
              var responseTextLen = data.length;
              for (i = 0; i < responseTextLen; i++) {
                binary += String.fromCharCode(data.charCodeAt(i) & 255);
              }
              var base64 = btoa(binary);
  
              function downloadPDF() {
                const linkSource = `data:application/pdf;base64,${base64}`;
                const downloadLink = document.createElement("a");
                const fileName = "Interception Report.pdf";
                downloadLink.href = linkSource;
                downloadLink.download = fileName;
                downloadLink.click();
              }
              downloadPDF();
              controller.refreshCrudTables();
              /**
               * Display a base64 URL inside an iframe in another window.
               */
            }
            ids = [];
          }
        );
      } else {
        controller.showToastMsg(
          "Kindly click on the Item again, If error Persists, Contact EAA Admin",
          "#ff6666"
        );
      }
    },
    refreshCrudTables: function (formName = "") {
      if (formName == "") {
        for (i in allFormObj) {
          try {
            controller.renderCRUDTable(allFormObj[i], "GET");
          } catch (e) {}
        }
      } else {
        controller.renderCRUDTable(allFormObj[formName], "GET");
      }
    },
    refreshCrudTablesLoad: function (formName = "") {
      crudsaveLinesInspection = false;
      crudOnetimeExportImportLineeSaveInspection = false;
      crudeImportConsLineSaveInspection = false;
      crudexportLineSaveInspection = false;
    },
    refreshCrudTablesLoad_page: function () {
      window.location = "./#app/dashboard"; //redirect to user profile
      // window.location.reload();
      // if (window.history.replaceState) {
      //     window.history.replaceState(null, null, window.location.href);
      // }
    },
    populateChecklistInspection: function (recordID, data) {
      $(".crud_section_checklist").html("Inspection Loading... Please Wait");
      var url =
        serverURL +
        "inspectionLine/getInspectionLineByInspectionHeaderID?inspectionHeaderID=" +
        recordID;
      var html = "";
      controller.requestWithToken(url, function (data, status) {
        var jsonData = data;
        var documentTypesUploaded = [];
        var tableHTML = $("#crud_section_checklist");
        var num = 0;
        for (var i = 0; i < jsonData.length; i++) {
          num++;
          html = html + '<div class="three fields">';
          html = html + '<div class="field" id="inspectionRequirement_label">';
          html =
            html +
            '<label style="color:#black;">' +
            num +
            "." +
            jsonData[i]["inspectionRequirement"]["requirement"] +
            "</label>";
          html = html + "</div>";
          html = html + '<div class="field">';
          html = html + "<label>Observation </label>";
          html = html + '<select  class="ui fluid dropdown">';
          html = html + '<option value="false" selected>-Select-</option>';
          html = html + '<option value="true">Yes</option>';
          html = html + '<option value="false">No</option>';
          html = html + "</select>";
          html = html + "</div>";
          html = html + '<div class="field">';
          html = html + " <label>Remarks </label>";
          html =
            html +
            ' <input type="text" name="comments" id="comments" placeholder="Enter comments">';
          html = html + " </div>";
          html = html + "</div>";
        }
        tableHTML.html(html);
        $("#crud_section_checklist").show();
      });
    },
  
    displayLoading: function () {
      var html3 = "";
      html3 +=
        '<div class="ui segment inspectionssection" style="height: 600px">';
      html3 += '<div class="ui active inverted dimmer">';
      html3 += '<div class="ui text loader">Loading</div>';
      html3 += "</div>";
      html3 += "<p></p>";
      html3 += "</div>";
      $(".crud_section").html(html3);
    },
  
    displayMyActivies: function () {
      var crud_section_view = "";
      crud_section_view += '<div class="tab myapprovaldocuments">';
      crud_section_view +=
        '<button id="crudview" class="tablinks" onclick="myactivities()">My Approval Documents';
      crud_section_view += '<em class="icon-bell"></em>';
      crud_section_view +=
        '<span id="notification_Counts" class="label label-danger pull-right"></span>';
      crud_section_view += "</button>";
      crud_section_view += "</div>";
      var timeFoormat = "";
      $(".crud_section_header").html(crud_section_view);
    },
  
    displayMyActiviesAccounts: function () {
      var crud_section_view = "";
      crud_section_view += '<div class="tab myapprovaldocuments">';
      crud_section_view +=
        '<button id="crudview" class="tablinks" onclick="myactivitiesaccounts()">My Approval Documents';
      crud_section_view += '<em class="icon-bell"></em>';
      crud_section_view +=
        '<span id="notification_Counts" class="label label-danger pull-right"></span>';
      crud_section_view += "</button>";
      crud_section_view += "</div>";
      var timeFoormat = "";
      $(".crud_section_header").html(crud_section_view);
    },
  
    displayMyActiviesAssign: function () {
      var crud_section_view = "";
      crud_section_view += '<div class="tab myapprovaldocuments">';
      crud_section_view +=
        '<button id="crudview" class="tablinks" onclick="myactivitiesassign()">Applications to Assign';
      crud_section_view += '<em class="icon-bell"></em>';
      crud_section_view +=
        '<span id="notification_Counts" class="label label-danger pull-right"></span>';
      crud_section_view += "</button>";
      crud_section_view += "</div>";
      var timeFoormat = "";
      $(".crud_section_header").html(crud_section_view);
    },
  
    populateCommodities: function (data) {
      $(".requirementModalproducts").modal("show");
  
      $(".crud_section_lines2").html("Commodities Loading... Please Wait");
      var url =
        serverURL +
        "pipApplicationVariety/getPIPApplicationVarietyByPIPApplication?pipApplicationID=" +
        data.pipApplication.pipApplicationID;
      var html = "";
      controller.requestWithToken(url, function (data, status) {
        var requiredDocJSON = data;
        var documentTypesUploaded = [];
        var tableHTML = $(".crud_section_lines2");
        var num = 0;
  
        html =
          html +
          "<table class='table table-striped'><tr><td>Commodity</td><td>Quantity Weight</td></tr>";
        for (var i = 0; i < requiredDocJSON.length; i++) {
          html =
            html +
            "<tr><td>" +
            requiredDocJSON[i]["product"]["name"] +
            "</td><td>" +
            requiredDocJSON[i]["quantity"] +
            "</td>";
          html = html + "</tr>";
          html = html + "<tr>";
          html = html + "</tr>";
        }
  
        html = html + "</table>";
        tableHTML.html(html);
      });
    },
  
    populatePIPCommodities: function (data) {
      $(".requirementModalproducts").modal("show");
      $(".crud_section_lines2").html("Commodities Loading... Please Wait");
      var url =
        serverURL +
        "pipApplicationVariety/getPIPApplicationVarietyByPIPApplication?pipApplicationID=" +
        data.pipApplicationID;
      var html = "";
      controller.requestWithToken(url, function (data, status) {
        var requiredDocJSON = data;
        var documentTypesUploaded = [];
        var tableHTML = $(".crud_section_lines2");
        var num = 0;
  
        html =
          html +
          "<table class='table table-striped'><tr><td>Commodity</td><td>Quantity Weight</td></tr>";
        for (var i = 0; i < requiredDocJSON.length; i++) {
          html =
            html +
            "<tr><td>" +
            requiredDocJSON[i]["product"]["name"] +
            "</td><td>" +
            requiredDocJSON[i]["quantity"] +
            "</td>";
          html = html + "</tr>";
          html = html + "<tr>";
          html = html + "</tr>";
        }
  
        html = html + "</table>";
        tableHTML.html(html);
      });
    },
  
    InspectionApprove: function (cell) {
      $(".recommend").html("Approving.. Please Wait");
  
      setTimeout(function () {
        $(".recommend").html("Recommend");
      }, 5000);
  
      if (cell.exporterConsignment === undefined) {
        var exporterConsignmentID = 0;
      } else {
        var exporterConsignmentID =
          cell.exporterConsignment.exporterConsignmentID;
      }
      if (cell.exporterFarm === undefined) {
        var exporterFarmID = 0;
      } else {
        var exporterFarmID = cell.exporterFarm.exporterFarmID;
      }
      if (cell.exporterFirm === undefined) {
        var exporterFirmID = 0;
      } else {
        var exporterFirmID = cell.exporterFirm.exporterFirmID;
      }
      if (cell.exporter === undefined) {
        var exporterID = 0;
      } else {
        var exporterID = cell.exporter.exporterID;
      }
      if (cell.exporterInspectionRequest === undefined) {
        var exporterInspectionRequestID = 0;
      } else {
        var exporterInspectionRequestID =
          cell.exporterInspectionRequest.exporterInspectionRequestID;
      }
      if (cell.exporterLowRiskCommodity === undefined) {
        var exporterLowRiskCommodityID = 0;
      } else {
        var exporterLowRiskCommodityID =
          cell.exporterLowRiskCommodity.exportLowRiskCommodityID;
      }
      if (cell.importer === undefined) {
        var importerID = 0;
      } else {
        var importerID = cell.importer.importerID;
      }
      if (cell.importerInspectionRequest === undefined) {
        var importerInspectionRequestID = 0;
      } else {
        var importerInspectionRequestID =
          cell.importerInspectionRequest.importerInspectionRequestID;
      }
      if (cell.pipApplication === undefined) {
        var pipApplicationID = 0;
      } else {
        var pipApplicationID = cell.pipApplication.pipApplicationID;
      }
      if (cell.quarantineFacility === undefined) {
        var quarantineFacilityID = 0;
      } else {
        var quarantineFacilityID = cell.quarantineFacility.quarantineFacilityID;
      }
      var formJson = {
        companyID: cell.company.company_id,
        exporterConsignmentID: exporterConsignmentID,
        exporterFarmID: exporterFarmID,
        exporterFirmID: exporterFirmID,
        exporterID: exporterID,
        exporterInspectionRequestID: exporterInspectionRequestID,
        exporterLowRiskCommodityID: exporterLowRiskCommodityID,
        importerID: importerID,
        importerInspectionRequestID: importerInspectionRequestID,
        inspectionHeaderID: cell.inspectionHeaderID,
        inspectionTypeID: cell.inspectionType.inspectionTypeID,
        lowRiskCommodity: cell.isLowRiskCommodity,
        passedInsp: true,
        pipApplicationID: pipApplicationID,
        quarantineFacilityID: quarantineFacilityID,
        validUntil: "",
      };
  
      var url = serverURL + "inspectionHeader/updateInspectionHeader";
      var async_status = true;
      controller.inspectionChecklistPostRequest(
        url,
        formJson,
        async_status,
        function (data, status) {
          if (data.statusText == "error") {
            controller.showToastMsg(
              "error!" + data.responseJSON.message + "",
              "#1a5589"
            );
          } else {
            loadData();
            refresh();
          }
        }
      );
    },
  
    InspectionReject: function (cell) {
      $(".notrecommend").html("Rejecting.. Please Wait");
  
      setTimeout(function () {
        $(".notrecommend").html("Recommend");
      }, 5000);
      if (cell.exporterConsignment === undefined) {
        var exporterConsignmentID = 0;
      } else {
        var exporterConsignmentID =
          cell.exporterConsignment.exporterConsignmentID;
      }
      if (cell.exporterFarm === undefined) {
        var exporterFarmID = 0;
      } else {
        var exporterFarmID = cell.exporterFarm.exporterFarmID;
      }
      if (cell.exporterFirm === undefined) {
        var exporterFirmID = 0;
      } else {
        var exporterFirmID = cell.exporterFirm.exporterFirmID;
      }
      if (cell.exporter === undefined) {
        var exporterID = 0;
      } else {
        var exporterID = cell.exporter.exporterID;
      }
      if (cell.exporterInspectionRequest === undefined) {
        var exporterInspectionRequestID = 0;
      } else {
        var exporterInspectionRequestID =
          cell.exporterInspectionRequest.exporterInspectionRequestID;
      }
      if (cell.exporterLowRiskCommodity === undefined) {
        var exporterLowRiskCommodityID = 0;
      } else {
        var exporterLowRiskCommodityID =
          cell.exporterLowRiskCommodity.exportLowRiskCommodityID;
      }
      if (cell.importer === undefined) {
        var importerID = 0;
      } else {
        var importerID = cell.importer.importerID;
      }
      if (cell.importerInspectionRequest === undefined) {
        var importerInspectionRequestID = 0;
      } else {
        var importerInspectionRequestID =
          cell.importerInspectionRequest.importerInspectionRequestID;
      }
      if (cell.pipApplication === undefined) {
        var pipApplicationID = 0;
      } else {
        var pipApplicationID = cell.pipApplication.pipApplicationID;
      }
      if (cell.quarantineFacility === undefined) {
        var quarantineFacilityID = 0;
      } else {
        var quarantineFacilityID = cell.quarantineFacility.quarantineFacilityID;
      }
      var formJson = {
        companyID: cell.company.company_id,
        exporterConsignmentID: exporterConsignmentID,
        exporterFarmID: exporterFarmID,
        exporterFirmID: exporterFirmID,
        exporterID: exporterID,
        exporterInspectionRequestID: exporterInspectionRequestID,
        exporterLowRiskCommodityID: exporterLowRiskCommodityID,
        importerID: importerID,
        importerInspectionRequestID: importerInspectionRequestID,
        inspectionHeaderID: cell.inspectionHeaderID,
        inspectionTypeID: cell.inspectionType.inspectionTypeID,
        lowRiskCommodity: cell.isLowRiskCommodity,
        passedInsp: false, //variable to change based on user click
        pipApplicationID: pipApplicationID,
        quarantineFacilityID: quarantineFacilityID,
        validUntil: "",
      };
      var url = serverURL + "inspectionHeader/updateInspectionHeader";
      var async_status = true;
  
      controller.inspectionChecklistRejectPostRequest(
        url,
        formJson,
        async_status,
        function (data, status) {
          if (data.statusText == "error") {
            controller.showToastMsg(
              "error!" + data.responseJSON.message + "",
              "#1a5589"
            );
          } else {
            loadData();
            refresh();
          }
        }
      );
    },
  };
  
  setTimeout(function () {
    $("#crudsectiongeneratebtn").attr("disabled", false);
    $("#crudsectiongeneratebtn").html("Save");
  }, 2000);
  setTimeout(function () {
    $("#crudsectiongeneratebtn").attr("disabled", false);
    $("#crudsectiongeneratebtn").html("Save");
  }, 2000);
  
  setTimeout(function () {
    $("#crudsectiongeneratebtn").attr("disabled", false);
    $("#crudsectiongeneratebtn").html("Save");
  }, 2000);