var currentEditableVisibleIndexBS;
var preventEndEditOnLostFocusBS = false;
var lastBE_IDBS;
var setValueFlagBS;
var setpnlValueFlagBS;
var setpnlCodeValueFlagBS;
var setICValueFlagIncomeBS;
var setICCodeValueFlagIncomeBS;
var setJournalType;

// ########## Booking Entity Combo Selected index change
function IBS_BECombo_SelectedIndexChanged(s, e) {
    var currentValueBS = s.GetValue();
    GetIncomeBSSAP_PNLByBE();

    //######## Function to get SAP PNL by Booking Entity

    if (lastBE_IDBS == currentValueBS) {
        if (IncomeBSPC_IdCombo.GetSelectedIndex() < 0)
            IncomeBSPC_IdCombo.SetSelectedIndex(-1);

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

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

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

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

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

        return;
    }
    lastBE_IDBS = currentValueBS;
    if (IncomeBSBooking_Entity_Id.GetValue() != null) {
        //if (Check_IBS_permissibleEntry(currentValueBS)) {
        IncomeBSInterComp_Entity_Id.PerformCallback(); // Bind Intercompany
        IncomeBSInterComp_Code.PerformCallback(); // Bind Intercompany Code
        IncomeBSPC_IdCombo.PerformCallback();         // Bind Income PC
        IncomeBSPNLCombo.PerformCallback();  // Bind Income PNL Description
        IncomeBSPNLCodeCombo.PerformCallback();  // Bind Income PNL Code
        IncomeBSJournalType.PerformCallback();
        //}
        //else {
        //    alert('You can\'t create entry for this Entity');
        //    IncomeBSBooking_Entity_Id.SetValue(null);
        //    lastBE_IDBS = null;
        //    IncomeBSSAP_Account_Id.SetText(null);
        //    IncomeBSInterComp_Entity_Id.SetValue(null);
        //    IncomeBSInterComp_Code.SetValue(null);
        //    IncomeBSPNLCombo.SetValue(null);
        //    IncomeBSPNLCodeCombo.SetValue(null);
        //    IncomeBSPC_IdCombo.SetValue(null);
        //}
    }
}

function IncomeBSGoodsCombo_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 Income Section
                //$('#AccShipmentstringIncomeData').html("Contract String : " + result);
                //$('#AccShipmentstringIncomeData').show();
            }
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn
            $("#PopDiv2").html('Error occurred while getting data');
            $("#PopDiv1").fadeOut(8000);
        }
    });
    IncomeBSBooking_Entity_Id.PerformCallback();
}

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

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

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

// ########## Profit Center Combo Begin Callback
function IncomeBSPcCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDBS;
}

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

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

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

// ########## Initialize all variables for Gridview
function IntializeBSGlobalVariables(gvAccountIncomeBalanceSheet) {
    lastBE_IDBS = -1;
    currentEditableVisibleIndexBS = -1;
    setValueFlagBS = -1;
    setpnlValueFlagBS = -1;
    setpnlCodeValueFlagBS = -1;
    setICValueFlagIncomeBS = -1;
    setICCodeValueFlagIncomeBS = -1;
    setJournalType = -1;
}

// ########## Gridview Init
function OnBSInit(s, e) {
    IntializeBSGlobalVariables(s);
}

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

function IncomeBSBookingId_EndCallback(s, e) {
    IncomeBSBooking_Entity_Id.SetSelectedItem(IncomeBSBooking_Entity_Id.FindItemByValue(lastBE_IDBS));
}

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

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

// ########## Profit Center Combo End Callback
function IncomeBSPcCombo_EndCallback(s, e) {
    if (setValueFlagBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setValueFlagBS > -1) {
        IncomeBSPC_IdCombo.SetSelectedItem(IncomeBSPC_IdCombo.FindItemByValue(setValueFlagBS));
        setValueFlagBS = -1;
    }
}

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

// ########## PNL Account description Combo End Callback
function IncomeBSPNL_EndCallback(s, e) {
    if (setpnlValueFlagBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlValueFlagBS > -1) {
        IncomeBSPNLCombo.SetSelectedItem(IncomeBSPNLCombo.FindItemByValue(setpnlValueFlagBS));
        setpnlValueFlagBS = -1;
    }
}

// ########## PNL Account code Combo End Callback
function IncomeBSPNLCode_EndCallback(s, e) {
    if (setpnlCodeValueFlagBS == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlCodeValueFlagBS > -1) {
        IncomeBSPNLCodeCombo.SetSelectedItem(IncomeBSPNLCodeCombo.FindItemByValue(setpnlCodeValueFlagBS));
        setpnlCodeValueFlagBS = -1;
    }
}
// ########## Gridview Edit Start
function OnBSBatchEditStartEditing(s, e) {
    if (e.visibleIndex < 0) {
        gvAccountIncomeBalanceSheet.GetEditor("Invoice_Date").SetEnabled(true);
        gvAccountIncomeBalanceSheet.GetEditor("Due_Date").SetEnabled(true);
        gvAccountIncomeBalanceSheet.GetEditor("Amount").SetEnabled(true);
        gvAccountIncomeBalanceSheet.GetEditor("L2").SetEnabled(true);
        gvAccountIncomeBalanceSheet.GetEditor("SAP_FX_Rate").SetEnabled(true);
        gvAccountIncomeBalanceSheet.GetEditor("Fx_Rate").SetEnabled(true);
        IncomeBSBooking_Entity_Id.SetEnabled(true);
        IncomeBSCountry_Id.SetEnabled(true);
        IncomeBSInterComp_Entity_Id.SetEnabled(true);
        IncomeBSInterComp_Code.SetEnabled(true);
        IncomeBSPC_IdCombo.SetEnabled(true);
        Currency_IdCost.SetEnabled(true);
        IncomeBSPNLCodeCombo.SetEnabled(true);
        IncomeBSPNLCombo.SetEnabled(true);
        IncomeBSJournalType.SetEnabled(true);
    }

    else {
        gvAccountIncomeBalanceSheet.GetEditor("Invoice_Date").SetEnabled(false);
        gvAccountIncomeBalanceSheet.GetEditor("Due_Date").SetEnabled(false);
        gvAccountIncomeBalanceSheet.GetEditor("Amount").SetEnabled(false);
        gvAccountIncomeBalanceSheet.GetEditor("L2").SetEnabled(false);
        gvAccountIncomeBalanceSheet.GetEditor("SAP_FX_Rate").SetEnabled(false);
        gvAccountIncomeBalanceSheet.GetEditor("Fx_Rate").SetEnabled(false);
        IncomeBSBooking_Entity_Id.SetEnabled(false);
        IncomeBSCountry_Id.SetEnabled(false);
        IncomeBSInterComp_Entity_Id.SetEnabled(false);
        IncomeBSInterComp_Code.SetEnabled(false);
        IncomeBSPC_IdCombo.SetEnabled(false);
        Currency_IdIncomeBS.SetEnabled(false);
        //IncomeBSPNLCodeCombo.SetEnabled(false);
        //IncomeBSPNLCombo.SetEnabled(false);
        IncomeBSJournalType.SetEnabled(false);
    }

    var accountingId = s.GetRowKey(e.visibleIndex);
    if (accountingId != null) {
        var currentBEID = gvAccountIncomeBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndex, "Booking_Entity_Id");
        var isBalance = 1;
        var data = {
            selectedId: parseInt(accountingId),
            isBalance: parseInt(isBalance)
        }
        $.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)
                    StartIBSEditing(s, e)
                else
                    gvAccountIncomeBalanceSheet.CancelEdit();
            }
        });
    }
    else
        StartIBSEditing(s, e);
}

function StartIBSEditing(s, e) {
    currentEditableVisibleIndexBS = e.visibleIndex;
    $('#hdnValidateInterCompanyCode').val('');
    var currentBEID = gvAccountIncomeBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndexBS, "Booking_Entity_Id");
    lastGoodsId = gvAccountIncomeBalanceSheet.batchEditApi.GetCellValue(currentEditableVisibleIndexBS, "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_IDBS == currentBEID) {
        if (IncomeBSBooking_Entity_Id.FindItemByValue(bookingIdcellInfo.value) != null)
            IncomeBSBooking_Entity_Id.SetValue(bookingIdcellInfo.value);
        else
            RefreshBSIncomeBookingEntityData(bookingIdcellInfo);

        if (IncomeBSJournalType.FindItemByValue(JournalTypeInfo.value) != null)
            IncomeBSJournalType.SetValue(JournalTypeInfo.value);
        else
            RefreshIncomeBSJournalTypeData(JournalTypeInfo);

        if (IncomeBSPC_IdCombo.FindItemByValue(cellInfo.value) != null)
            IncomeBSPC_IdCombo.SetValue(cellInfo.value);
        else
            RefreshBSData(cellInfo);

        if (IncomeBSPNLCombo.FindItemByValue(pnlcellInfo.value) != null)
            IncomeBSPNLCombo.SetValue(pnlcellInfo.value);
        else
            RefreshBSPNLData(pnlcellInfo);

        if (IncomeBSPNLCodeCombo.FindItemByValue(pnlCodecellInfo.value) != null)
            IncomeBSPNLCodeCombo.SetValue(pnlCodecellInfo.value);
        else
            RefreshIncomeBSPNLCodeData(pnlCodecellInfo);

        if (IncomeBSInterComp_Entity_Id.FindItemByValue(ICcellInfo.value) != null)
            IncomeBSInterComp_Entity_Id.SetValue(ICcellInfo.value);
        else
            RefreshIncomeBSIntercompanyData(ICcellInfo);

        if (IncomeBSInterComp_Code.FindItemByValue(ICCodecellInfo.value) != null)
            IncomeBSInterComp_Code.SetValue(ICCodecellInfo.value);
        else
            RefreshIncomeBSIntercompanyCodeData(ICCodecellInfo);
    }
    else {
        if (currentBEID == null) {
            IncomeBSPC_IdCombo.SetSelectedIndex(-1);
            IncomeBSPNLCombo.SetSelectedIndex(-1);
            IncomeBSPNLCodeCombo.SetSelectedIndex(-1);
            IncomeBSInterComp_Entity_Id.SetSelectedIndex(-1);
            IncomeBSInterComp_Code.SetSelectedIndex(-1);
            IncomeBSJournalType.SetSelectedIndex(-1);
            return;
        }
        lastBE_IDBS = currentBEID;
        RefreshBSIncomeBookingEntityData(bookingIdcellInfo);
        RefreshBSPNLData(pnlcellInfo);
        RefreshIncomeBSPNLCodeData(pnlCodecellInfo);
        RefreshIncomeBSIntercompanyData(ICcellInfo);
        RefreshIncomeBSIntercompanyCodeData(ICCodecellInfo);
        RefreshBSData(cellInfo);
        RefreshIncomeBSJournalTypeData(JournalTypeInfo);
    }
}
// ##########  Gridview End Edit
function OnBSBatchEditEndEditing(s, e) {
    currentEditableVisibleIndexBS = -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 = IncomeBSBooking_Entity_Id.GetValue();
    bookingIdcellInfo.text = IncomeBSBooking_Entity_Id.GetText();
    IncomeBSBooking_Entity_Id.SetValue(null);

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

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

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

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

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

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

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

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

// ####### Intercompany Combo Reload
function RefreshIncomeBSIntercompanyData(ICcellInfo) {
    setICValueFlagIncomeBS = ICcellInfo.value;
    IncomeBSInterComp_Entity_Id.PerformCallback();
}

// ####### Intercompany Code Combo Reload
function RefreshIncomeBSIntercompanyCodeData(ICCodecellInfo) {
    setICCodeValueFlagIncomeBS = ICCodecellInfo.value;
    IncomeBSInterComp_Code.PerformCallback();
}

// ########## Profit Center Combo Reload
function RefreshBSData(cellInfo) {
    setValueFlagBS = cellInfo.value;
    IncomeBSPC_IdCombo.PerformCallback();
}

// ########## PNL Account Combo Reload
function RefreshBSPNLData(pnlcellInfo) {
    setpnlValueFlagBS = pnlcellInfo.value;
    IncomeBSPNLCombo.PerformCallback();
}

// ########## PNL Account code Combo Reload
function RefreshIncomeBSPNLCodeData(pnlCodecellInfo) {
    setpnlCodeValueFlagBS = pnlCodecellInfo.value;
    IncomeBSPNLCodeCombo.PerformCallback();
}

function IncomeBSBookingId_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = true;
    }
}

function IncomeBSInterCo_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = true;
    }
}

function IncomeBSICCode_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocus = false;
    }
}

function IncomeBSPcCombo_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusBS = true;
    }
}

function IncomeBSPNL_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusBS = true;
    }
}

function IncomeBSPNLCode_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 (gvAccountIncomeBalanceSheet.batchEditApi[moveActionName]()) {
        ASPxClientUtils.PreventEventAndBubble(e.htmlEvent);
        preventEndEditOnLostFocusBS = true;
    }
}

function IncomeBSPNL_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('');
    }
    IncomeBSPNLCodeCombo.SetValue(BSId);
}

// ########## Get PNL Code on PNL Account Combo Selected Index change or Lost Focus
function IncomeBSPNL_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('');
    }
    IncomeBSPNLCodeCombo.SetValue(BSId);
}

function IncomeBSPNLCode_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('');
    }
    IncomeBSPNLCombo.SetValue(BSId);
}

// Check Whether Account Entry is permissible or not
function Check_IBS_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 GetIncomeBSSAPFx() {
    var cId = Currency_IdIncomeBS.GetValue();
    var postingDate = IncomeBSPosting_Date.GetText();
    var urlGetFxRate = $('#urlGetSAPFxRateBasedonCurrency').val() + "?currencyID=" + cId + "&pDate=" + postingDate;
    $.ajax({
        type: "GET",
        contentType: "application.JSON",
        url: urlGetFxRate,
        cache: false,
        success: function (result) {
            if (!isNaN(parseFloat(result))) {
                var sapfxrate = result;
                IncomeBSSAP_FX_Rate.SetValue(sapfxrate);
                UpdateIncomeBS();
            }
            else {
                location.reload();
            }

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

function GetIncomeBSSAPFxRate() {
    var FxRate = IncomeBSFx_Rate.GetText();
    IncomeBSSAP_FX_Rate.SetText(FxRate.replace(/,/g, ''));
}

function UpdateIncomeBS() {
    var income = parseFloat(IncomeBSAmount.GetText().replace(/,/g, ''));
    var FxRate = parseFloat(IncomeBSSAP_FX_Rate.GetText().replace(/,/g, ''));
    var total = parseFloat(income * FxRate).toFixed(2);//var total = parseFloat(income / FxRate).toFixed(2);
    IncomeBSAmount_In_USD.SetText(total);
}

//#################### Get Country Based on Intercompany Entity  ####################//
function GetIncomeBSCountry_ICCode() {
    var CompanyId = IncomeBSInterComp_Entity_Id.GetValue();
    //var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId;
    var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId + "$" + IncomeBSBooking_Entity_Id.GetValue();
    if (CompanyId != null) {
        //if (CheckBSIncomeForInterCoEntry(CompanyId))
        $.ajax({
            type: 'GET',
            data: null,
            contentType: 'application/json',
            url: url,
            chache: false,
            success: function (result) {
                IncomeBSCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                //IncomeBSInterComp_Code.SetValue(CompanyId);
                IncomeBSInterComp_Code.SetValue(result.CP_Code);
                //else
                //    IncomeBSInterComp_Code.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}

function GetIncomeBSCountry_IC() {
    var CompanyId = IncomeBSInterComp_Code.GetValue();
    var sapsunId = IncomeBSInterComp_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) {
                IncomeBSCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                //IncomeBSInterComp_Entity_Id.SetValue(CompanyId);
                IncomeBSInterComp_Entity_Id.SetValue(result.CP_Short_Name);
                //else
                //    IncomeBSInterComp_Entity_Id.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}

function CheckBSIncomeForInterCoEntry(CompanyId) {
    var permissibleEntites = $('#hdnParamforAccountIncomeIEValidation').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 checkIncomeBSCompRequired(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 validateIncomeBSAmt(s, e) {
    var amt = s.GetValue();
    if (amt == '0.00')
        e.isValid = false;
    else
        e.isValid = true;
}

function validateIncomeBSSAPFx(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 GetIncomeBSSAP_PNLByBE() {
    var CompanyId = IncomeBSBooking_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) {
            IncomeBSSAP_Account_Id.SetText(result);
        },
        Error: function () { }
    });
}
// #################### Get PNL Code Based on PNL No  ####################//

function GetIncomePNL_BSCodeByNo() {
    var BSId = IncomeBSPNL_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) {
            IncomeBS_Account_code.SetText(result);
        },
        Error: function () { }
    });
}
// #################### Check if Posting date is greater than or less than Trading date  ####################//
function ValidateIncomeBSTradeDate(s, e) {
    if (IncomeBSPosting_Date.GetValue() != null) {
        if (TradeDate.GetValue() != null) {
            //Getting year
            var Trade_Year = TradeDate.GetValue().getFullYear();
            //Getting month
            var TradeMonth = TradeDate.GetValue().getMonth();

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

    }
}

// ################ Get Fx Rate based on currency #################//
function getIncomeBSSAPFxRate() {
    var cId = Currency_IdIncomeBS.GetValue();
    var postingDate = IncomeBSPosting_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;
                IncomeBSFx_Rate.SetValue(total);
                GetIncomeBSSAPFx();
            }
            else {
                location.reload();
            }

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