$(document).ready(function () {
    var count = parseInt(0);

    $('#show').click(function () {
        var hasDeleteControl = $("#txtDeleteControls").val();
        count = parseInt($("#EntityCount").val());
        if (count == 6)
            alert("Can't add more blocks")
        else {
            if (count > 3)
                $("#div" + (count) + "Hide").hide();
            //if (hasDeleteControl == 'true') {
            $("#div" + (count + 1) + "Hide").show();
            //}
            $("#div" + (count + 1)).fadeIn("fast");
            //$('#trContractNo' + (count + 1)).show();
            //$('#lblContractNo' + (count + 1)).show();
            //$('#trInvoiceNo' + (count + 1)).show();

            count = count + 1;
            $("#EntityCount").val(count);
            return;
        }
    });
});

function HideBlock(count) {
    //var savedEntityCount = parseInt(sessionStorage.getItem('EntityCount'))
    //if (count <= 0)
    //    count = savedEntityCount
    $("#div" + count).fadeOut("slow");
    $('#trContractNo' + count).hide();
    $('#lblContractNo' + count).hide();
    $('#trDrCrNo' + count).hide();
    $('#lblDrCrNo' + count).hide();
    $('#trInvoiceNo' + count).hide();
    $('#btnContract' + count).hide();
    $('#btnInvoice' + count).hide();
    $('#btn_Debit_Credit_Note' + count).hide();
    $('#btnfinalizeOp' + count).hide();
    $('#btn_Payment_Instruction' + count).hide();
    $('#btnCertificate' + count).hide();
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + count);
    entityEditor.SetValue(null);

    count = count - 1;
    if (count > 3 && parseBoolean($("#deleteControls").val()))
        $("#div" + (count) + "Hide").show();
    $("#EntityCount").val(count);
}

function RemoveBlock(section) {
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var entity = entityEditor.GetValue();

    if (entity != null) {
        IsFinalized(section, 1);
    }
    else
        HideBlock(section);
}

function GetDefaulValue(section, goodsBlock) {
    var RefNo = SFM_Ref_Number.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo)
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'GetDefaultValue',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data)
            for (var i = section; i <= 6; i++) {
                for (var j = 1; j <= goodsBlock; j++) {
                    var goodsEditor = ASPxClientControl.GetControlCollection().GetByName('Goods' + i + "_" + j);
                    var goodsIdEditor = ASPxClientControl.GetControlCollection().GetByName('GoodsId' + i + "_" + j);
                    var vesselEditor = ASPxClientControl.GetControlCollection().GetByName('Vessel' + i + "_" + j);
                    var shipmentIdEditor = ASPxClientControl.GetControlCollection().GetByName('ShipmentId' + i + "_" + j);
                    var tradeFlowEditor = ASPxClientControl.GetControlCollection().GetByName('TradeFlow' + i + "_" + j);
                    var quantityEditor = ASPxClientControl.GetControlCollection().GetByName('Quantity' + i + "_" + j);
                    var loadingEditor = ASPxClientControl.GetControlCollection().GetByName('Loading' + i + "_" + j);
                    var destinationEditor = ASPxClientControl.GetControlCollection().GetByName('Destination' + i + "_" + j);

                    goodsEditor.SetText(data[j - 1].Goods_Name);
                    goodsIdEditor.SetText(data[j - 1].Goods_Id);
                    quantityEditor.SetText(data[j - 1].Quantity);
                    vesselEditor.SetText(data[j - 1].Vessel);
                    shipmentIdEditor.SetValue(data[j - 1].Shipment_Id);
                    tradeFlowEditor.SetText(data[j - 1].Trade_Flow_NO);
                    loadingEditor.SetValue(data[j - 1].Origin_Id);
                    destinationEditor.SetValue(data[j - 1].Destination_Id);
                }
            }
            if (section == 1) {
                $('#div4').hide();
                $('#div5').hide();
                $('#div6').hide();
                sessionStorage.setItem("EntityCount", 3);
                $("#EntityCount").val(3);
            }
            else {
                for (var k = section; k < 6; k++) {
                    $('#div' + (k + 1)).hide();
                }
            }
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

function CalculateAmount(section, goodsBlock) {
    var goodsCount = sessionStorage.getItem("GoodsCount");
    var unitPrice = 0;
    var quantity = 0;
    var subAmount = 0;
    var totalAmount = 0;

    var quantityEditor = ASPxClientControl.GetControlCollection().GetByName('Quantity' + section + "_" + goodsBlock);
    var unitPriceEditor = ASPxClientControl.GetControlCollection().GetByName('UnitPrice' + section + "_" + goodsBlock);
    var subAmountEditor = ASPxClientControl.GetControlCollection().GetByName('SubAmount' + section + "_" + goodsBlock);
    var totalAmountEditor = ASPxClientControl.GetControlCollection().GetByName('TotalAmount' + section);

    unitPrice = unitPriceEditor.GetValue();
    quantity = quantityEditor.GetValue();
    subAmount = unitPrice * quantity;

    //subAmount = Math.round(unitPrice * quantity * 100) / 100;

    //subAmount = subAmount * 100;
    //var subAmt = subAmount.toString().split('.')[0];
    //subAmount = parseFloat(subAmt) / 100;

    subAmountEditor.SetValue(subAmount);

    for (var j = 1; j <= goodsCount; j++) {
        var priceEditor = ASPxClientControl.GetControlCollection().GetByName('SubAmount' + section + "_" + j);
        totalAmount = totalAmount + priceEditor.GetValue();
    }

    totalAmountEditor.SetText(totalAmount);

    if (section == 1) {
        for (var i = 1; i <= 6; i++) {
            var quantEditor = ASPxClientControl.GetControlCollection().GetByName('Quantity' + i + "_" + goodsBlock);
            var priceEditor = ASPxClientControl.GetControlCollection().GetByName('UnitPrice' + i + "_" + goodsBlock);
            var amountEditor = ASPxClientControl.GetControlCollection().GetByName('SubAmount' + i + "_" + goodsBlock);
            var totalamtEditor = ASPxClientControl.GetControlCollection().GetByName('TotalAmount' + i);

            priceEditor.SetValue(unitPrice);
            if (section != i) {
                quantEditor.SetValue(quantity);
                amountEditor.SetValue(subAmount);
                totalamtEditor.SetText(totalAmount);
            }
        }
    }
}

function PopulateContractstring(accessControl) {
    var RefNo = SFM_Ref_Number.GetValue();
    $('#trTradeFlowData').show();

    var parameters = {
        sfmRefNo: String(RefNo),
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'GetData',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data)
            var section = data.RecordCount;
            var goodsBlock = data.GoodsCount;
            sessionStorage.setItem("GoodsCount", goodsBlock);
            sessionStorage.setItem("EntityCount", section);
            $("#EntityCount").val(section);

            if (section == 0) {
                // fill all blocks with default values
                GetDefaulValue(1, goodsBlock);
            }
            else {
                for (var i = 0; i < section; i++) {
                    var invoiceNo = data.Record[i].InvoiceNo;
                    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + (i + 1));
                    var totalAmountEditor = ASPxClientControl.GetControlCollection().GetByName('TotalAmount' + (i + 1));
                    var currencyEditor = ASPxClientControl.GetControlCollection().GetByName('Currency' + (i + 1));
                    var shipmentEditor = ASPxClientControl.GetControlCollection().GetByName('Shipment' + (i + 1));
                    var DeliveryEditor = ASPxClientControl.GetControlCollection().GetByName('Delivery' + (i + 1));
                    var PaymentConditionEditor = ASPxClientControl.GetControlCollection().GetByName('PaymentCondition' + (i + 1));
                    var FinalizeBotton = ASPxClientControl.GetControlCollection().GetByName('btnfinalizeOp' + (i + 1));

                    entityEditor.SetValue(data.Record[i].EntityID);
                    totalAmountEditor.SetValue(data.Record[i].TotalAmount);
                    //totalAmountEditor.GetInputElement().readOnly = true;
                    currencyEditor.SetValue(data.Record[i].Currency);
                    var shipment = new Date(parseInt(data.Record[i].Shipment.substr(6)));
                    shipmentEditor.SetText(shipment);
                    DeliveryEditor.SetValue(data.Record[i].Delivery);
                    PaymentConditionEditor.SetValue(data.Record[i].PaymentCondition);
                    $('#lblContractNo' + (i + 1)).text(data.Record[i].ContractNo);
                    $('#lblInvoiceNo' + (i + 1)).text(data.Record[i].InvoiceNo);
                    $('#lblDrCrNo' + (i + 1)).text(data.Record[i].DrCrNo);

                    if (data.Record[i].MailSent) {
                        $('#btnfinalizeOp' + (i + 1)).css('color', 'gray');
                        $('#btnfinalizeOp' + (i + 1)).text('Submitted By Ops');
                    }

                    if (invoiceNo == "Not Created" || data.Record[i].IsAllInvoiceFinalized) {                        
                        FinalizeBotton.SetEnabled(false);
                        $('#btnfinalizeOp' + (i + 1)).css('color', 'lightgray');
                        $('#btnfinalizeOp' + (i + 1)).css("cursor", "not-allowed");
                    }

                    var itemDetail = data.Record[i].ContractStringDetail
                    for (var j = 0; j < goodsBlock; j++) {
                        var goodsEditor = ASPxClientControl.GetControlCollection().GetByName('Goods' + (i + 1) + "_" + (j + 1));
                        var goodsIdEditor = ASPxClientControl.GetControlCollection().GetByName('GoodsId' + (i + 1) + "_" + (j + 1));
                        var vesselEditor = ASPxClientControl.GetControlCollection().GetByName('Vessel' + (i + 1) + "_" + (j + 1));
                        var shipmentIdEditor = ASPxClientControl.GetControlCollection().GetByName('ShipmentId' + (i + 1) + "_" + (j + 1));
                        var tradeFlowEditor = ASPxClientControl.GetControlCollection().GetByName('TradeFlow' + (i + 1) + "_" + (j + 1));
                        var tenorEditor = ASPxClientControl.GetControlCollection().GetByName('Tenor' + (i + 1) + "_" + (j + 1));
                        var quantityEditor = ASPxClientControl.GetControlCollection().GetByName('Quantity' + (i + 1) + "_" + (j + 1));
                        var unitPriceEditor = ASPxClientControl.GetControlCollection().GetByName('UnitPrice' + (i + 1) + "_" + (j + 1));
                        var amountEditor = ASPxClientControl.GetControlCollection().GetByName('SubAmount' + (i + 1) + "_" + (j + 1));
                        var loadingEditor = ASPxClientControl.GetControlCollection().GetByName('Loading' + (i + 1) + "_" + (j + 1));
                        var destinationEditor = ASPxClientControl.GetControlCollection().GetByName('Destination' + (i + 1) + "_" + (j + 1));
                        var subAmount = itemDetail[j].UnitPrice * itemDetail[j].Quantity;
                        //var subAmount = Math.round(itemDetail[j].UnitPrice * itemDetail[j].Quantity * 100) / 100;
                        //var subAmount = parseFloat(itemDetail[j].UnitPrice * itemDetail[j].Quantity).toFixed(2)
                        goodsEditor.SetValue(itemDetail[j].GoodsName);
                        goodsIdEditor.SetValue(itemDetail[j].GoodsID);
                        vesselEditor.SetValue(itemDetail[j].Vessel);
                        shipmentIdEditor.SetValue(itemDetail[j].ShipmentId);
                        tradeFlowEditor.SetValue(itemDetail[j].TradeFlow);
                        quantityEditor.SetText(itemDetail[j].Quantity);
                        unitPriceEditor.SetText(itemDetail[j].UnitPrice);
                        amountEditor.SetText(subAmount);
                        loadingEditor.SetValue(itemDetail[j].Loading);
                        destinationEditor.SetValue(itemDetail[j].Destination);
                        var tenor = "";
                        if (itemDetail[j].Tenor != null)
                            var tenor = new Date(parseInt(itemDetail[j].Tenor.substr(6)));
                        tenorEditor.SetText(tenor);

                        goodsEditor.GetInputElement().readOnly = true;
                        vesselEditor.GetInputElement().readOnly = true;
                    }
                }

                //fill rest of the block with default values
                GetDefaulValue(section + 1, goodsBlock);

                if (accessControl == 'True')
                    $('#btnUpdate').show();
                else
                    $('#btnUpdate').hide();

                $('#buttonDiv1').show(); //for first 3 contract,invoice button
                $('#buttonDiv2').show(); //for last 3 contract,invoice button               
                $('#btnSubmit').hide();
                // hide remove links for 4th ,5th and 6th blocks
                for (var k = 4; k <= 6; k++) {
                    if (k != section)
                        $('#div' + k + 'Hide').hide();
                    if (section > 3)
                        $('#div' + section + 'Hide').show();
                }

                for (var k = 0; k < section; k++) {
                    $('#div' + (k + 1)).show();
                    $('#trContractNo' + (k + 1)).show();
                    $('#lblContractNo' + (k + 1)).show();
                    $('#trInvoiceNo' + (k + 1)).show();
                    $('#trDrCrNo' + (k + 1)).show();
                }
                for (var k = section; k < 6; k++) {
                    $('#div' + (k + 1)).hide();
                    $('#btnContract' + (k + 1)).hide();
                    $('#btnInvoice' + (k + 1)).hide();
                    $('#btn_Debit_Credit_Note' + (k + 1)).hide();
                    $('#btn_Payment_Instruction' + (k + 1)).hide();
                    $('#btnCertificate' + (k + 1)).hide();
                    $('#btnfinalizeOp' + (k + 1)).hide();
                }
            }
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

function ShowContractString() {
    var RefNo = SFM_Ref_Number.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo),
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'IsOpenTrade',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data)
            if (data == true) {
                alert("It is an open trade or Shipment has been deleted.");
                window.location.href = '';
            }
            else
                window.location.href = '\Show?sfmRefNo=' + RefNo;
        },
    });
}

var errorMessage = "";

function validate() {
    errorMessage = "";
    var sfmRef = SFM_Ref_Number.GetText();

    if (sfmRef == "")
        errorMessage = errorMessage + "Please select SFM Ref Number \n ";

    for (var i = 1; i <= 6; i++) {
        var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + i);
        var entity = entityEditor.GetValue();

        if (entity == null) {
            if (i < 4)
                errorMessage = errorMessage + "  Please select Entity " + i + " \n ";
        }
        else
            ValidateGoodsBlock(i)
    }

    if (errorMessage != "") {
        alert("Please see below Error: \n" + errorMessage);
        return false;
    }
    else {
        var entities = [];
        for (var i = 1; i <= 6; i++) {
            var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + i);
            var entity = entityEditor.GetText();
            if (entity != '')
                entities.push(entity);
        }
        var valuesSoFar = [];
        for (var i = 0; i < entities.length; ++i) {
            var value = entities[i];
            if (valuesSoFar.indexOf(value) !== -1) {
                alert("counter party - " + value + " is entered more than once.")
                return false;
            }
            valuesSoFar.push(value);
        }
    }
    return true;
}

function ValidateGoodsBlock(section) {
    var goodsBlock = sessionStorage.getItem("GoodsCount");
    for (var j = 1; j <= goodsBlock; j++) {
        var goodsEditor = ASPxClientControl.GetControlCollection().GetByName('Goods' + section + "_" + j);
        var unitPriceEditor = ASPxClientControl.GetControlCollection().GetByName('UnitPrice' + section + "_" + j);

        var goods = goodsEditor.GetValue();
        var unitPrice = unitPriceEditor.GetValue();

        //if (goods == null)
        //    errorMessage = errorMessage + "  Please select " + j + "th Goods for " + section + "th entity \n ";
        if (unitPrice == 0)
            errorMessage = errorMessage + "  Please select " + j + "th unit Price for " + section + "th entity \n ";
    }
}

function validateEntity(section) {
    // Check if the invoice for this counter party is finalized
    IsFinalized(section, 0);
}

function IsFinalized(section, isDelete) {
    var refNo = SFM_Ref_Number.GetValue();
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var cpId = entityEditor.GetValue();

    var parameters = {
        sfmRefNo: String(refNo),
        sequence: section,
        cpId: cpId
    }
    var StringID = '';
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'CheckIfFinalized',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data);
            //if counter party's invoice is finalized
            if (data.Status == 1) {
                alert(data.Message);
                if (isDelete == 0) {
                    // if it is for counterparty update
                    entityEditor.SetValue(data.CpId);
                }
            }
            else
                if (isDelete == 1) {
                    // if it is for remove and counter party is not finalized
                    HideBlock(section);
                }
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

function ValidateGoods(s, e, section, goodsBlock) {
    var goodsBlocks = sessionStorage.getItem("GoodsCount");
    var goods = [];
    if (goodsBlocks > 1) {
        var currentGoods = s.GetValue();

        for (var j = 1; j <= goodsBlocks; j++) {
            if (j != goodsBlock) {
                var goodsEditor = ASPxClientControl.GetControlCollection().GetByName('Goods' + section + "_" + j);
                goods.push(goodsEditor.GetValue());
            }
        }

        for (var i = 0; i < goods.length; i++) {
            if (goods[i] == currentGoods) {
                alert("This Goods has been entered already For the current Entity. Choose another one")
                s.SetValue("");
            }
        }
    }
}

//function PopulateCurrency(s, e, section) {
//    if(section == 1){
//    var currentCurrency = s.GetValue();

//    for (var i = 1; i <= 6; i++) {
//        var currencyEditor = ASPxClientControl.GetControlCollection().GetByName('Currency' + i);
//        currencyEditor.SetValue(currentCurrency);
//    }
//    }
//}
function CreateDebitCreditNote(section) {
    var entityCount = sessionStorage.getItem("EntityCount");
    var RefNo = SFM_Ref_Number.GetValue();
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var cpId = entityEditor.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo),
        sequence: section,
        entityId: cpId
    }
    // window.location = '/Debit_Credit_Note?SFM_Ref_No=' + SFM_Ref_Number.GetValue() + '&Entity=' + cpId
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'ValidateDebitCreditNote',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data);
            if (data.Status == 1) {
                var companyId = data.CompanyId
                //window.location = '/Debit_Credit_Note?SFM_Ref_No=' + RefNo + '&Entity=' + companyId
                window.location = $('#url_debit_credit').val() + '?SFM_Ref_No=' + RefNo + '&Entity=' + companyId + '&RedirectToContractString=1'
            }
            else
                alert(data.Message);
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

function CreateContract(section) {
    var entityCount = sessionStorage.getItem("EntityCount");
    var RefNo = SFM_Ref_Number.GetValue();
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var cpId = entityEditor.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo),
        sequence: section,
        entityId: cpId
    }
    var StringID = '';
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'AddContract',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data);
            alert(data.Message);
            if (data.Status == 1) {
                $('#lblContractNo' + section).text(data.ContractNo);
            }
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });

}

function CreateInvoice(section) {
    var entityCount = sessionStorage.getItem("EntityCount");
    var RefNo = SFM_Ref_Number.GetValue();
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var cpId = entityEditor.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo),
        sequence: section,
        entityId: cpId
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'ValidateInvoice',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data);
            if (data.Status == 1) {
                var companyId = data.CompanyId
                window.location.href = '\AddInvoice?sfmRefNo=' + RefNo + '&companyId=' + companyId
            }
            else
                alert(data.Message);
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

function ShowCertificatePopup(section) {
    var RefNo = SFM_Ref_Number.GetValue();
    //var invoiceEditor = ASPxClientControl.GetControlCollection().GetByName('Invoice' + section);
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);

    //var invoiceNo = invoiceEditor.GetValue();
    var entityId = entityEditor.GetValue();

    if (!RefNo || !entityId) {
        alert("Missing required values.");
        return;
    }

    var url = '\CertificatePopup?sfmRefNo=' + encodeURIComponent(RefNo)
        //+ '&invoiceNo=' + encodeURIComponent(invoiceNo)
        + '&entityId=' + encodeURIComponent(entityId);

    window.location.href = url;
}


function IsOpentrade(event) {
    var RefNo = SFM_Ref_No.GetValue();

    var parameters = {
        sfmRefNo: String(RefNo),
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'ContractString/IsOpenTrade',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data)
            if (data == true) {
                alert("It is an open trade");
                SFM_Ref_No.SetValue("")
            }
        },
    });
}

function ChangeAmount(s, e, section) {
    var currencyEditor = ASPxClientControl.GetControlCollection().GetByName('Currency' + section);
    var currencyId = currencyEditor.GetValue();

    var parameters = {
        currencyId: parseInt(currencyId),
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'GetFxRate',
        data: parameters,
        cache: 'false',
        success: function (data) {
            console.log(data)
            var goodCount = parseInt(sessionStorage.getItem("GoodsCount"));
            var fxRate = parseFloat(data)
            for (var i = 1; i <= goodCount; i++) {
                var unitPriceEditor = ASPxClientControl.GetControlCollection().GetByName('UnitPrice' + section + "_" + i);
                var unitPrice = parseFloat(unitPriceEditor.GetValue());

                unitPriceEditor.SetText(itemDetail[j].UnitPrice);
            }
        },
    });
}

function FinalizeByOps(section) {
    var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + section);
    var cpId = entityEditor.GetValue();

    NotificationModal.Show();
    var RefNo = SFM_Ref_Number.GetValue();
    var parameters = {
        sfmRefNo: String(RefNo),
        counterPartyId: cpId
    }
    $.ajax({
        type: 'GET',
        contentType: 'application/json',
        url: 'Finalize',
        data: parameters,
        cache: 'false',
        success: function (data) {
            NotificationModal.Hide();
            if (data.Status == 1) {
                $('#btnfinalizeOp' + section).css('color', 'gray');
                $('#btnfinalizeOp' + section).text('Submitted By Ops');
            }
            alert(data.Message);
        },
        error: function () {
            NotificationModal.Hide();
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('error!');
            $("#PopDiv1").fadeOut(8000);
        }
    });

}