var currentEditableVisibleIndexCBS;
var preventEndEditOnLostFocusCBS = false;
var lastBE_IDCBS;
var setValueFlagCBS;
var setpnlValueFlagCBS;
var setpnlCodeValueFlagCBS;
var setICValueFlagCostBS;
var setICCodeValueFlagCostBS;
var setJournalType;

// ########## Booking Entity Combo Selected index change
function CBS_BECombo_SelectedIndexChanged(s, e) {

    var currentValueBS = s.GetValue();
    if (lastBE_IDCBS == currentValueBS) {
        if (CostBSPC_IdCombo.GetSelectedIndex() < 0)
            CostBSPC_IdCombo.SetSelectedIndex(-1);

        if (CostBSJournalType.GetSelectedIndex() < 0)
            CostBSJournalType.SetSelectedIndex(-1);

        if (CostBSPNLCombo.GetSelectedIndex() < 0)
            CostBSPNLCombo.SetSelectedIndex(-1);

        if (CostBSPNLCodeCombo.GetSelectedIndex() < 0)
            CostBSPNLCodeCombo.SetSelectedIndex(-1);

        if (CostBSInterComp_Entity_Id.GetSelectedIndex() < 0)
            CostBSInterComp_Entity_Id.SetSelectedIndex(-1);

        if (CostBSInterComp_Code.GetSelectedIndex() < 0)
            CostBSInterComp_Code.SetSelectedIndex(-1);

        return;
    }
    lastBE_IDCBS = currentValueBS;
    if (CostBSBooking_Entity_Id.GetValue() != null) {
        //if (Check_CBS_permissibleEntry(currentValueBS)) {
        GetCostBSSAP_PNLByBE(); //Get SAP PNL by Booking Entity
        CostBSInterComp_Entity_Id.PerformCallback(); // Bind Intercompany
        CostBSInterComp_Code.PerformCallback(); // Bind Intercompany Code
        CostBSPC_IdCombo.PerformCallback();         // Bind Income PC
        CostBSPNLCombo.PerformCallback();  // Bind Income PNL Description
        CostBSPNLCodeCombo.PerformCallback();  // Bind Income PNL Code
        CostBSJournalType.PerformCallback();

        //}
        //else {
        //    alert('You can\'t create entry for this Entity');
        //    CostBSBooking_Entity_Id.SetValue(null);
        //    lastBE_IDCBS = null;
        //    CostBSSAP_Account_Id.SetText(null);
        //    CostBSInterComp_Entity_Id.SetValue(null);
        //    CostBSInterComp_Code.SetValue(null);
        //    CostBSPNLCombo.SetValue(null);
        //    CostBSPNLCodeCombo.SetValue(null);
        //    CostBSPC_IdCombo.SetValue(null);
        //}
    }
}

function CostBSGoodsCombo_SelectedIndexChanged(s, e) {
    
    var currentValue = s.GetValue();
    var sfmNo = SFM_Ref_Number.GetValue();
    var data = {
        goodsId: Number(currentValue),
        sfmNo: sfmNo
    }
    lastGoodsId = Number(currentValue)

    $.ajax({
        type: "POST",
        url: 'Trade/GetAccountShipmentString1',
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {
            if (result == '')
                alert('Please create contruct string for SFM NO : ' + sfmNo + ' And Good: ' + s.GetText())
            else {
                // Fill Cost Section
                //$('#AccShipmentstringCostData').html("Contract String : " + result);
                //$('#AccShipmentstringCostData').show();
            }
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn
            $("#PopDiv2").html('Error occurred while getting data');
            $("#PopDiv1").fadeOut(8000);
        }
    });
    CostBSBooking_Entity_Id.PerformCallback();
}

// ####### BookingId Combo Begin Callback
function CostBSBookingId_BeginCallback(s, e) {
    e.customArgs['goodsId'] = lastGoodsId;
    e.customArgs['sfmRefNo'] = SFM_Ref_Number.GetValue();
}

// ####### Intercompany Combo Begin Callback
function CostBSInterCo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
    e.customArgs['sfmRefNo'] = SFM_Ref_Number.GetValue();
}

// ####### Intercompany Combo Begin Callback
function CostBSICCode_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
    e.customArgs['sfmRefNo'] = SFM_Ref_Number.GetValue();
}
// ########## Profit Center Combo Begin Callback
function CostBSPcCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
}

// ########## PNL Account Description Combo Begin Callback
function CostBSPNLCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
}

// ########## PNL Account Code Combo Begin Callback
function CostBSPNLCodeCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
}

function JournalTypeBSPayableCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCBS;
}

// ########## Initialize all variables for Gridview
function IntializeCBSGlobalVariables(gvAccountCostBalanceSheet) {
    lastBE_IDCBS = -1;
    currentEditableVisibleIndexCBS = -1;
    setValueFlagCBS = -1;
    setpnlValueFlagCBS = -1;
    setpnlCodeValueFlagCBS = -1;
    setICValueFlagCostBS = -1;
    setICCodeValueFlagCostBS = -1;
    setJournalType = -1;
}

// ########## Gridview Init
function OnCBSInit(s, e) {
    IntializeCBSGlobalVariables(s);
}

// ########## Gridview End Callback
function OnCBSEndCallback(s, e) {
    IntializeCBSGlobalVariables(s);
    //gvBookingEntityBS.PerformCallback();  // Reload Balance Sheet BS
    EnableDisablePostButton();
}

function CostBSBookingId_EndCallback(s, e) {
    CostBSBooking_Entity_Id.SetSelectedItem(CostBSBooking_Entity_Id.FindItemByValue(lastBE_IDBS));
}

// ####### InterCompany Combo End Callback
function CostBSInterCo_EndCallback(s, e) {
    if (setICValueFlagCostBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else {
        CostBSInterComp_Entity_Id.SetSelectedItem(CostBSInterComp_Entity_Id.FindItemByValue(setICValueFlagCostBS));
        setICValueFlagCostBS = -1;
    }
}

// ####### InterCompany Combo End Callback
function CostBSICCode_EndCallback(s, e) {
    if (setICCodeValueFlagCostBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else {
        CostBSInterComp_Code.SetSelectedItem(CostBSInterComp_Code.FindItemByValue(setICCodeValueFlagCostBS));
        setICCodeValueFlagCostBS = -1;
    }
}

// ####### Journal Type Combo End Callback
function JournalTypeCostBS_EndCallback(s, e) {
    if (setJournalType == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else {
        CostBSJournalType.SetSelectedItem(CostBSJournalType.FindItemByValue(setJournalType));
        setJournalType = -1;
    }
}

// ########## Profit Center Combo End Callback
function CostBSPcCombo_EndCallback(s, e) {
    if (setValueFlagCBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setValueFlagCBS > -1) {
        CostBSPC_IdCombo.SetSelectedItem(CostBSPC_IdCombo.FindItemByValue(setValueFlagCBS));
        setValueFlagCBS = -1;
    }
}
// ########## PNL Account Combo End Callback
function CostBSPNLCombo_EndCallback(s, e) {
    if (setpnlValueFlagCBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlValueFlagCBS > -1) {
        CostBSPNLCombo.SetSelectedItem(CostBSPNLCombo.FindItemByValue(setpnlValueFlagCBS));
        setpnlValueFlagCBS = -1;
    }
}

// ########## PNL Account Combo End Callback
function CostBSPNLCodeCombo_EndCallback(s, e) {
    if (setpnlCodeValueFlagCBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlCodeValueFlagCBS > -1) {
        CostBSPNLCodeCombo.SetSelectedItem(CostBSPNLCodeCombo.FindItemByValue(setpnlCodeValueFlagCBS));
        setpnlCodeValueFlagCBS = -1;
    }
}


// ########## Gridview Edit Start
function OnCBSBatchEditStartEditing(s, e) {
    if (e.visibleIndex < 0) {
        gvAccountCostBalanceSheet.GetEditor("Invoice_Date").SetEnabled(true);
        gvAccountCostBalanceSheet.GetEditor("Due_Date").SetEnabled(true);
        gvAccountCostBalanceSheet.GetEditor("Amount").SetEnabled(true);
        gvAccountCostBalanceSheet.GetEditor("L2").SetEnabled(true);
        gvAccountCostBalanceSheet.GetEditor("SAP_FX_Rate").SetEnabled(true);
        gvAccountCostBalanceSheet.GetEditor("Fx_Rate").SetEnabled(true);
        CostBSBooking_Entity_Id.SetEnabled(true);
        CostBSCountry_Id.SetEnabled(true);
        CostBSInterComp_Entity_Id.SetEnabled(true);
        CostBSInterComp_Code.SetEnabled(true);
        CostBSPC_IdCombo.SetEnabled(true);
        Currency_IdCost.SetEnabled(true);
        CostBSPNLCodeCombo.SetEnabled(true);
        CostBSPNLCombo.SetEnabled(true);
        CostBSJournalType.SetEnabled(true);
    }

    else {
        gvAccountCostBalanceSheet.GetEditor("Invoice_Date").SetEnabled(false);
        gvAccountCostBalanceSheet.GetEditor("Due_Date").SetEnabled(false);
        gvAccountCostBalanceSheet.GetEditor("Amount").SetEnabled(false);
        gvAccountCostBalanceSheet.GetEditor("L2").SetEnabled(false);
        gvAccountCostBalanceSheet.GetEditor("SAP_FX_Rate").SetEnabled(false);
        gvAccountCostBalanceSheet.GetEditor("Fx_Rate").SetEnabled(false);
        CostBSBooking_Entity_Id.SetEnabled(false);
        CostBSCountry_Id.SetEnabled(false);
        CostBSInterComp_Entity_Id.SetEnabled(false);
        CostBSInterComp_Code.SetEnabled(false);
        CostBSPC_IdCombo.SetEnabled(false);
        Currency_IdCostBS.SetEnabled(false);
        //CostBSPNLCodeCombo.SetEnabled(false);
        //CostBSPNLCombo.SetEnabled(false);
        CostBSJournalType.SetEnabled(false);
    }

    var accountingId = s.GetRowKey(e.visibleIndex);
    if (accountingId != null) {
        var currentBEID = gvAccountCostBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndex, "Booking_Entity_Id");

        var data = {
            selectedId: parseInt(accountingId),
            isBalance: parseInt(1)
        }
        $.ajax({
            method: 'POST',
            url: 'Trade/IsPosted',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {
                if (result == 0)
                    StartCBSEditing(s, e)
                else
                    gvAccountCostBalanceSheet.CancelEdit();
            }
        });
    }
    else
        StartCBSEditing(s, e);
}

function StartCBSEditing(s, e) {
    
    currentEditableVisibleIndexCBS = e.visibleIndex;
    $('#hdnValidateInterCompanyCode').val('');
    var currentBEID = gvAccountCostBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndexCBS, "Booking_Entity_Id");
    lastGoodsId = gvAccountCostBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndex, "Goods_Id");

    var bookingIDColumn = s.GetColumnByField("Booking_Entity_Id");
    var pcIDColumn = s.GetColumnByField("PC_Id");
    var pnlIDColumn = s.GetColumnByField("BS_Account_No");
    var pnlCodeIDColumn = s.GetColumnByField("BS_Account_code");
    var IC_IDColumn = s.GetColumnByField("InterComp_Entity_Id");
    var ICCode_IDColumn = s.GetColumnByField("InterComp_Code");
    var JournalTypeColumn = s.GetColumnByField("Journal_Type");

    if (!e.rowValues.hasOwnProperty(bookingIDColumn.index) || !e.rowValues.hasOwnProperty(pcIDColumn.index) || !e.rowValues.hasOwnProperty(pnlIDColumn.index) || !e.rowValues.hasOwnProperty(IC_IDColumn.index) || !e.rowValues.hasOwnProperty(pnlCodeIDColumn.index) || !e.rowValues.hasOwnProperty(ICCode_IDColumn.index) || !e.rowValues.hasOwnProperty(JournalTypeColumn.index)) {
        return;
    }

    var bookingIdcellInfo = e.rowValues[bookingIDColumn.index];
    var cellInfo = e.rowValues[pcIDColumn.index];
    var pnlcellInfo = e.rowValues[pnlIDColumn.index];
    var pnlCodecellInfo = e.rowValues[pnlCodeIDColumn.index];
    var ICcellInfo = e.rowValues[IC_IDColumn.index];
    var ICCodecellInfo = e.rowValues[ICCode_IDColumn.index];
    var JournalTypeInfo = e.rowValues[JournalTypeColumn.index];

    if (lastBE_IDCBS == currentBEID) {
        if (CostBSBooking_Entity_Id.FindItemByValue(bookingIdcellInfo.value) != null)
            CostBSBooking_Entity_Id.SetValue(bookingIdcellInfo.value);
        else
            RefreshCostBookingEntityData(bookingIdcellInfo);

        if (CostBSJournalType.FindItemByValue(JournalTypeInfo.value) != null)
            CostBSJournalType.SetValue(JournalTypeInfo.value);
        else
            RefreshCostBSJournalTypeData(JournalTypeInfo);

        if (CostBSPNLCombo.FindItemByValue(pnlcellInfo.value) != null)
            CostBSPNLCombo.SetValue(pnlcellInfo.value);
        else
            RefreshCBSPNLData(pnlcellInfo);

        if (CostBSPNLCodeCombo.FindItemByValue(pnlCodecellInfo.value) != null)
            CostBSPNLCodeCombo.SetValue(pnlCodecellInfo.value);
        else
            RefreshBSPNLCodeData(pnlCodecellInfo);

        if (CostBSInterComp_Entity_Id.FindItemByValue(ICcellInfo.value) != null)
            CostBSInterComp_Entity_Id.SetValue(ICcellInfo.value);
        else
            RefreshCostBSIntercompanyData(ICcellInfo);

        if (CostBSInterComp_Code.FindItemByValue(ICCodecellInfo.value) != null)
            CostBSInterComp_Code.SetValue(ICCodecellInfo.value);
        else
            RefreshCostBSIntercompanyCodeData(ICCodecellInfo);

        if (CostBSPC_IdCombo.FindItemByValue(cellInfo.value) != null)
            CostBSPC_IdCombo.SetValue(cellInfo.value);
        else
            RefreshCBSData(cellInfo);
    }
    else {
        if (currentBEID == null) {
            CostBSPC_IdCombo.SetSelectedIndex(-1);
            CostBSPNLCombo.SetSelectedIndex(-1);
            CostBSPNLCodeCombo.SetSelectedIndex(-1);
            CostBSInterComp_Entity_Id.SetSelectedIndex(-1);
            CostBSInterComp_Code.SetSelectedIndex(-1);
            CostBSJournalType.SetSelectedIndex(-1);
            return;
        }
        lastBE_IDCBS = currentBEID;
        RefreshCostBookingEntityData(bookingIdcellInfo);
        RefreshCBSPNLData(pnlcellInfo);
        RefreshBSPNLCodeData(pnlCodecellInfo);
        RefreshCostBSIntercompanyData(ICcellInfo);
        RefreshCostBSIntercompanyCodeData(ICCodecellInfo);
        RefreshCBSData(cellInfo);
        RefreshCostBSJournalTypeData(JournalTypeInfo);
    }
}
// ##########  Gridview End Edit
function OnCBSBatchEditEndEditing(s, e) {
    currentEditableVisibleIndexCBS = -1;
    var bookingEntityId = s.GetColumnByField("Booking_Entity_Id");
    var pcIDColumn = s.GetColumnByField("PC_Id");
    var pnlIDColumn = s.GetColumnByField("BS_Account_No");
    var pnlCodeIDColumn = s.GetColumnByField("BS_Account_code");
    var IC_IDColumn = s.GetColumnByField("InterComp_Entity_Id");
    var ICCode_IDColumn = s.GetColumnByField("InterComp_Code");
    var journalTypeColumn = s.GetColumnByField("Journal_Type");

    if (!e.rowValues.hasOwnProperty(bookingEntityId.index) || !e.rowValues.hasOwnProperty(pcIDColumn.index) || !e.rowValues.hasOwnProperty(pnlIDColumn.index) || !e.rowValues.hasOwnProperty(IC_IDColumn.index) || !e.rowValues.hasOwnProperty(pnlCodeIDColumn.index) || !e.rowValues.hasOwnProperty(ICCode_IDColumn.index) || !e.rowValues.hasOwnProperty(journalTypeColumn.index))
        return;

    var bookingIdcellInfo = e.rowValues[bookingEntityId.index];
    var cellInfo = e.rowValues[pcIDColumn.index];
    var pnlcellInfo = e.rowValues[pnlIDColumn.index];
    var pnlCodecellInfo = e.rowValues[pnlCodeIDColumn.index];
    var ICcellInfo = e.rowValues[IC_IDColumn.index];
    var ICCodecellInfo = e.rowValues[ICCode_IDColumn.index];
    var JournaltypeInfo = e.rowValues[journalTypeColumn.index];

    bookingIdcellInfo.value = CostBSBooking_Entity_Id.GetValue();
    bookingIdcellInfo.text = CostBSBooking_Entity_Id.GetText();
    CostBSBooking_Entity_Id.SetValue(null);

    JournaltypeInfo.value = CostBSJournalType.GetValue();
    JournaltypeInfo.text = CostBSJournalType.GetText();
    CostBSJournalType.SetValue(null);

    cellInfo.value = CostBSPC_IdCombo.GetValue();
    cellInfo.text = CostBSPC_IdCombo.GetText();
    CostBSPC_IdCombo.SetValue(null);

    pnlcellInfo.value = CostBSPNLCombo.GetValue();
    pnlcellInfo.text = CostBSPNLCombo.GetText();
    CostBSPNLCombo.SetValue(null);

    pnlCodecellInfo.value = CostBSPNLCodeCombo.GetValue();
    pnlCodecellInfo.text = CostBSPNLCodeCombo.GetText();
    CostBSPNLCodeCombo.SetValue(null);

    ICcellInfo.value = CostBSInterComp_Entity_Id.GetValue();
    ICcellInfo.text = CostBSInterComp_Entity_Id.GetText();
    CostBSInterComp_Entity_Id.SetValue(null);

    ICCodecellInfo.value = CostBSInterComp_Code.GetValue();
    ICCodecellInfo.text = CostBSInterComp_Code.GetText();
    CostBSInterComp_Code.SetValue(null);

}

// ####### Booking Entity Combo Reload
function RefreshCostBookingEntityData(bookingIdcellInfo) {
    lastBE_IDBS = bookingIdcellInfo.value;
    CostBSBooking_Entity_Id.PerformCallback();
}

// ####### Journal Type Combo Reload
function RefreshCostBSJournalTypeData(JournalTypecellInfo) {
    setJournalType = JournalTypecellInfo.value;
    CostBSJournalType.PerformCallback();
}

// ####### Intercompany Combo Reload
function RefreshCostBSIntercompanyData(ICcellInfo) {
    setICValueFlagCostBS = ICcellInfo.value;
    CostBSInterComp_Entity_Id.PerformCallback();
}

function RefreshCostBSIntercompanyCodeData(ICCodecellInfo) {
    setICCodeValueFlagCostBS = ICCodecellInfo.value;
    CostBSInterComp_Code.PerformCallback();
}
// ########## Profit Center Combo Reload
function RefreshCBSData(cellInfo) {
    setValueFlagCBS = cellInfo.value;
    CostBSPC_IdCombo.PerformCallback();
}

// ########## PNL Account Combo Reload
function RefreshCBSPNLData(pnlcellInfo) {
    setpnlValueFlagCBS = pnlcellInfo.value;
    CostBSPNLCombo.PerformCallback();
}

function RefreshBSPNLCodeData(pnlCodecellInfo) {
    setpnlCodeValueFlagCBS = pnlCodecellInfo.value;
    CostBSPNLCodeCombo.PerformCallback();
}

function CostBSBookingId_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) return;
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountIncome.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = true;
    }
}

function CostBSInterCo_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) return;
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountCostBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = true;
    }
}

function CostBSICCode_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) return;
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountCostBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = true;
    }
}
function CostCBSPcCombo_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) {
        return;
    }
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountCostBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusCBS = true;
    }
}

function CostBSPNLCombo_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) return;
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountCostBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusCBS = true;
    }
}

function CostBSPNLCodeCombo_KeyDown(s, e) {
    var keyCode = ASPxClientUtils.GetKeyCode(e.htmlEvent);
    if (keyCode !== ASPxKey.Tab && keyCode !== ASPxKey.Enter) return;
    var moveActionName = e.htmlEvent.shiftKey ? "MoveFocusBackward" : "MoveFocusForward";
    if (gvAccountCostBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusCBS = true;
    }
}

function CostBSPNLCombo_LostFocus(s, e) {
    var BSId = s.GetValue();
    //Check If the account description is “Purchase Intercomp. Or Sales Intercomp”
    if (s.GetText().includes('Intercomp')) {
        $('#hdnValidateInterCompanyCode').val('1');
    }
    else {
        $('#hdnValidateInterCompanyCode').val('');
    }
    CostBSPNLCodeCombo.SetValue(BSId);
}

// ########## Get PNL Code on PNL Account Combo Selected Index change or Lost Focus
function CostBSPNL_SelectedIndexChanged(s, e) {
    var BSId = s.GetValue();
    //Check If the account description is “Purchase Intercomp. Or Sales Intercomp”
    if (s.GetText().includes('Intercomp')) {
        $('#hdnValidateInterCompanyCode').val('1');
    }
    else {
        $('#hdnValidateInterCompanyCode').val('');
    }
    CostBSPNLCodeCombo.SetValue(BSId);
}

function CostBSPNLCode_SelectedIndexChanged(s, e) {
    var BSId = s.GetValue();
    //Check If the account description is “Purchase Intercomp. Or Sales Intercomp”
    if (s.GetText().includes('Intercomp')) {
        $('#hdnValidateInterCompanyCode').val('1');
    }
    else {
        $('#hdnValidateInterCompanyCode').val('');
    }
    CostBSPNLCombo.SetValue(BSId);
}

// Check Whether Account Entry is permissible or not
function Check_CBS_permissibleEntry(currentValueBS) {
    var permissibleEntites = $('#hdnParamforAccountBEValidation').val();
    var arr = permissibleEntites.split(',');
    for (i = 0; i < arr.length; i++) {
        if (arr[i] == currentValueBS)
            return true;
    }
    return false;
}

//#################### Set Related Values ####################//
// Set Fx Rate to SAP Fx Rate
function GetCostBSSAPFx() {
    var FxRate = CostBSFx_Rate.GetText();
    CostBSSAP_FX_Rate.SetText(FxRate.replace(/,/g, ''));
}
function UpdateCostBS() {
    var Cost = parseFloat(CostBSAmount.GetText().replace(/,/g, ''));
    var SAPFxRate = parseFloat(CostBSSAP_FX_Rate.GetText().replace(/,/g, ''));
    if (SAPFxRate != null && SAPFxRate != '' && SAPFxRate != Infinity && SAPFxRate != undefined) {
        var total = parseFloat(Cost / SAPFxRate).toFixed(2);
        CostBSAmount_In_USD.SetText(total);
    }
    else {
        CostBSAmount_In_USD.SetText('0');
    }
}

//#################### Get Country Based on Intercompany Entity ####################//
function GetCostBSCountry_ICCode() {
    var CompanyId = CostBSInterComp_Entity_Id.GetValue();
    //var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId;
    var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId + "$" + CostBSBooking_Entity_Id.GetValue();
    if (CompanyId != null) {
        $.ajax({
            type: 'GET',
            data: null,
            contentType: 'application/json',
            url: url,
            chache: false,
            success: function (result) {
                CostBSCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                //CostBSInterComp_Code.SetValue(CompanyId);
                CostBSInterComp_Code.SetValue(result.CP_Code);
                //else
                //    CostBSInterComp_Code.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}
function GetCostBSCountry_IC() {
    var CompanyId = CostBSInterComp_Code.GetValue();
    var sapsunId = CostBSInterComp_Code.GetValue();
    //var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId;
    var url = $('#urlAccountCountry').val() + "?sapsunCode=" + sapsunId;
    if (CompanyId != null) {
        $.ajax({
            type: 'GET',
            data: null,
            contentType: 'application/json',
            url: url,
            chache: false,
            success: function (result) {
                CostBSCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                CostBSInterComp_Entity_Id.SetValue(result.CP_Short_Name);
                //else
                //    CostBSInterComp_Entity_Id.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}

function CheckForInterCoEntry(CompanyId) {
    var permissibleEntites = $('#hdnParamforAccountCostIEValidation').val();
    var arr = permissibleEntites.split(',');
    for (i = 0; i <= arr.length; i++) {
        if (arr[i] == CompanyId)
            return true;
        else
            return false;
    }
}

//################ Check If the account description is “Purchase Intercomp. Or Sales Intercomp” ####################//
function checkCostBSCompRequired(s, e) {
    if ($('#hdnValidateInterCompanyCode').val() == '1') {
        if (e.value == null)
            e.isValid = false;
        var pnlAc = String(e.value);
        if (pnlAc == "")
            e.isValid = false;
        e.errorText = "Intercompany Entity required!";
    }
    else {
        e.isValid = true;
    }
}

function validateCostBSAmt(s, e) {
    var amt = s.GetValue();
    if (amt == '0.00')
        e.isValid = false;
    else
        e.isValid = true;
}
//    function validateCostBSFx(s, e) {
//        var amt = s.GetValue();
//        if (amt == '0.000000')
//            e.isValid = false;
//        else
//            e.isValid = true;
//    }
function validateCostBSSAPFx(s, e) {
    var amt = s.GetValue();
    if (amt == '0.000000')
        e.isValid = false;
    else
        e.isValid = true;
}
//#################### Get SAP and PNL Based on  Booking Entity ####################//

function GetCostBSSAP_PNLByBE() {
    var CompanyId = CostBSBooking_Entity_Id.GetValue();
    var url = "Trade/GetSAP_PNLByBookingEntity";
    var data = {
        entityId: CompanyId
    }
    $.ajax({
        type: 'GET',
        data: data,
        contentType: 'application/json',
        url: url,
        chache: false,
        success: function (result) {
            CostBSSAP_Account_Id.SetText(result);
        },
        Error: function () { }
    });
}

// #################### Get PNL Code Based on PNL No  ####################//

function GetCostPNL_BSCodeByNo() {
    var BSId = CostBSPNL_Account_No.GetValue();
    var url = $('#urlGetPNL_BSCodeByPNL_BSNo').val() + "?PNL_No=" + BSId;
    $.ajax({
        type: 'GET',
        data: null,
        contentType: 'application/json',
        url: url,
        chache: false,
        success: function (result) {
            CostBS_Account_code.SetText(result);
        },
        Error: function () { }
    });
}
//#################### Check if Posting date is greater than or less than Trading date ####################//
function ValidateCostBSTradeDate(s, e) {
    if (CostBSPosting_Date.GetValue() != null) {
        if (TradeDate.GetValue() != null) {
            //Getting year
            var Trade_Year = TradeDate.GetValue().getFullYear();
            //Getting month
            var TradeMonth = TradeDate.GetValue().getMonth();

            if (CostBSPosting_Date.GetValue() < new Date(Trade_Year, TradeMonth, 1)) {
                alert('Transaction date/month should be greater than Trade date/month which is:' + TradeDate.GetValue());
                CostBSPosting_Date.SetValue(null);
            }
            else
                getCostBSSAPFxRate();
        }
        else
            getCostBSSAPFxRate();


    }
}

// ################ Get Fx Rate based on currency #################//
function getCostBSSAPFxRate() {
    var cId = Currency_IdCostBS.GetValue();
    var postingDate = CostBSPosting_Date.GetText();
    var urlGetFxRate = $('#urlGetFxRateBasedonCurrency').val() + "?currencyID=" + cId + "&pDate=" + postingDate;
    $.ajax({
        type: "GET",
        contentType: "application.JSON",
        url: urlGetFxRate,
        cache: false,
        success: function (result) {
            if (!isNaN(parseFloat(result))) {
                var total = result;
                CostBSFx_Rate.SetValue(total);
                CostBSSAP_FX_Rate.SetValue(total);
                UpdateCostBS();
            }
            else {
                location.reload();
            }

        },
        error: function () { }
    });
}
