var currentEditableVisibleIndex;
var preventEndEditOnLostFocus = false;
var lastBE_ID;
var setValueFlag;
var setpnlValueFlag;
var setpnlCodeValueFlag;
var setICValueFlagIncome;
var setICCodeValueFlagIncome;
var setJournalType;
var currentValue;
var lastGoodsId

// ########## Booking Entity Combo Selected index change
function BECombo_SelectedIndexChanged(s, e) {
    currentValue = s.GetValue();
    //######## Function to get SAP PNL by Booking Entity
    GetIncomeSAP_PNLByBE();

    if (lastBE_ID == currentValue) {
        if (IncomePC_Id.GetSelectedIndex() < 0)
            IncomePC_Id.SetSelectedIndex(-1);

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

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

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

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

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

        return;
    }
    lastBE_ID = currentValue;
    if (IncomeBooking_Entity_Id.GetValue() != null) {
        //if (CheckpermissibleEntry(currentValue)) {
        IncomeInterComp_Entity_Id.PerformCallback(); // Bind Intercompany
        IncomeInterComp_Code.PerformCallback(); // Bind Intercompany Code
        IncomePC_Id.PerformCallback();         // Bind Income PC
        IncomePNLCombo.PerformCallback();  // Bind Income PNL Description
        IncomePNLCodeCombo.PerformCallback();  // Bind Income PNL Code
        IncomeBooking_Entity_Id.SetSelectedItem(IncomeBooking_Entity_Id.FindItemByValue(lastBE_ID));
        IncomeJournalType.PerformCallback();
        //}
        //else {
        //    alert('You can\'t create entry for this Entity');
        //    IncomeBooking_Entity_Id.SetValue(null);
        //    lastBE_ID = null;
        //    IncomeSAP_Account_Id.SetText(null);
        //    IncomeInterComp_Entity_Id.SetValue(null);
        //    IncomeInterComp_Code.SetValue(null);
        //    IncomePNLCombo.SetValue(null);
        //    IncomePNLCodeCombo.SetValue(null);
        //    IncomePC_Id.SetValue(null);
        //}
    }
}
function IncomeGoodsCombo_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);
        }
    });
    IncomeBooking_Entity_Id.PerformCallback();
}

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

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

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

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

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

function JournalTypeCode_BeginCallback(s, e) {
    
    e.customArgs['CompanyID'] = lastBE_ID;
    //if (s.GetSelectedIndex() != -1) {
    //    IncomeJournalType.SetSelectedItem(IncomeJournalType.FindItemByValue(s.GetSelectedIndex()));
    //}
}

// ########## Initialize all variables for Gridview
function IntializeGlobalVariables(gvAccountIncome) {
    lastBE_ID = -1;
    currentEditableVisibleIndex = -1;
    setJournalType = -1;
    setValueFlag = -1;
    setpnlValueFlag = -1;
    setpnlCodeValueFlag = -1;
    setICValueFlagIncome = -1;
    setICCodeValueFlagIncome = -1;
}

// ########## Gridview Init
function OnIncomeInit(s, e) {
    IntializeGlobalVariables(s);
}

// ########## Gridview End Callback
function OnIncomeEndCallback(s, e) {
    IntializeGlobalVariables(s);
    // Get summary and check whether Account Entry Exist or not
    GetIncomeSummary();
    //CheckIncomeAccountForBSEntry(SFM_Ref_Number.GetValue(), 'I');
    gvAccountCost.PerformCallback();
    gvAccountIncomeBalanceSheet.PerformCallback();
    gvAccountCostBalanceSheet.PerformCallback();
    gvPostedAccount.PerformCallback();
    EnableDisablePostButton();
}

function IncomeBookingId_EndCallback(s, e) {
    IncomeBooking_Entity_Id.SetSelectedItem(IncomeBooking_Entity_Id.FindItemByValue(lastBE_ID));
}

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

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

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

// ########## Profit Center Combo End Callback
function IncomePcCombo_EndCallback(s, e) {
    if (setValueFlag == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setValueFlag > -1) {
        IncomePC_Id.SetSelectedItem(IncomePC_Id.FindItemByValue(setValueFlag));
        setValueFlag = -1;
    }
}
// ########## PNL Account description Combo End Callback
function IncomePNL_EndCallback(s, e) {
    if (setpnlValueFlag == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlValueFlag > -1) {
        IncomePNLCombo.SetSelectedItem(IncomePNLCombo.FindItemByValue(setpnlValueFlag));
        setpnlValueFlag = -1;
    }
}

// ########## PNL Account code Combo End Callback
function IncomePNLCode_EndCallback(s, e) {
    if (setpnlCodeValueFlag == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlCodeValueFlag > -1) {
        IncomePNLCodeCombo.SetSelectedItem(IncomePNLCodeCombo.FindItemByValue(setpnlCodeValueFlag));
        setpnlCodeValueFlag = -1;
    }
}


// ########## Gridview Edit Start
function OnIncomeBatchEditStartEditing(s, e) {
    if (e.visibleIndex < 0) {
        gvAccountIncome.GetEditor("Invoice_Date").SetEnabled(true);
        gvAccountIncome.GetEditor("Due_Date").SetEnabled(true);
        gvAccountIncome.GetEditor("Amount").SetEnabled(true);
        gvAccountIncome.GetEditor("L2").SetEnabled(true);
        gvAccountIncome.GetEditor("Fx_Rate").SetEnabled(true);
        gvAccountIncome.GetEditor("SAP_FX_Rate").SetEnabled(true);
        IncomeBooking_Entity_Id.SetEnabled(true);
        IncomeCountry_Id.SetEnabled(true);
        IncomeInterComp_Entity_Id.SetEnabled(true);
        IncomeInterComp_Code.SetEnabled(true);
        IncomePC_Id.SetEnabled(true);
        Currency_IdIncome.SetEnabled(true);
        IncomePNLCodeCombo.SetEnabled(true);
        IncomePNLCombo.SetEnabled(true);
        IncomeJournalType.SetEnabled(true);
    }

    else {
        gvAccountIncome.GetEditor("Invoice_Date").SetEnabled(false);
        gvAccountIncome.GetEditor("Due_Date").SetEnabled(false);
        gvAccountIncome.GetEditor("Amount").SetEnabled(false);
        gvAccountIncome.GetEditor("L2").SetEnabled(false);
        gvAccountIncome.GetEditor("SAP_FX_Rate").SetEnabled(false);
        gvAccountIncome.GetEditor("Fx_Rate").SetEnabled(false);
        IncomeBooking_Entity_Id.SetEnabled(false);
        IncomeCountry_Id.SetEnabled(false);
        IncomeInterComp_Entity_Id.SetEnabled(false);
        IncomeInterComp_Code.SetEnabled(false);
        IncomePC_Id.SetEnabled(false);
        Currency_IdIncome.SetEnabled(false);
        IncomePNLCodeCombo.SetEnabled(false);
        IncomePNLCombo.SetEnabled(false);
        IncomeJournalType.SetEnabled(false);
    }
        
    var accountingId = s.GetRowKey(e.visibleIndex);
    if (accountingId != null) {
        var currentBEID = gvAccountIncome.batchEditApi.GetCellValue(currentEditableVisibleIndex, "Booking_Entity_Id");

        var data = {
            selectedId: parseInt(accountingId),
            isBalance: parseInt(0)
        }
        $.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)
                    StartIEditing(s, e)
                else
                    gvAccountIncome.CancelEdit();
            }
        });
    }
    else
        StartIEditing(s, e);
}

function StartIEditing(s, e) {
    
    currentEditableVisibleIndex = e.visibleIndex;
    console.log(status)
    $('#hdnValidateInterCompanyCode').val('');
    var currentBEID = gvAccountIncome.batchEditApi.GetCellValue(currentEditableVisibleIndex, "Booking_Entity_Id");

    var bookingIDColumn = s.GetColumnByField("Booking_Entity_Id");
    var pcIDColumn = s.GetColumnByField("PC_Id");
    var pnlIDColumn = s.GetColumnByField("PNL_Account_No");
    var pnlCodeIDColumn = s.GetColumnByField("PNL_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_ID == currentBEID) {
        if (IncomeBooking_Entity_Id.FindItemByValue(bookingIdcellInfo.value) != null)
            IncomeBooking_Entity_Id.SetValue(bookingIdcellInfo.value);
        else
            RefreshIncomeBookingEntityData(bookingIdcellInfo);

        if (IncomeJournalType.FindItemByValue(JournalTypeInfo.value) != null)
            IncomeJournalType.SetValue(JournalTypeInfo.value);
        else
            RefreshIncomeJournalTypeData(JournalTypeInfo);

        if (IncomePC_Id.FindItemByValue(cellInfo.value) != null)
            IncomePC_Id.SetValue(cellInfo.value);
        else
            RefreshPCData(cellInfo);

        if (IncomePNLCombo.FindItemByValue(pnlcellInfo.value) != null)
            IncomePNLCombo.SetValue(pnlcellInfo.value);
        else
            RefreshPNLData(pnlcellInfo);

        if (IncomePNLCodeCombo.FindItemByValue(pnlCodecellInfo.value) != null)
            IncomePNLCodeCombo.SetValue(pnlCodecellInfo.value);
        else
            RefreshPNLCodeData(pnlCodecellInfo);

        if (IncomeInterComp_Entity_Id.FindItemByValue(ICcellInfo.value) != null)
            IncomeInterComp_Entity_Id.SetValue(ICcellInfo.value);
        else
            RefreshIntercompanyData(ICcellInfo);

        if (IncomeInterComp_Code.FindItemByValue(ICCodecellInfo.value) != null)
            IncomeInterComp_Code.SetValue(ICCodecellInfo.value);
        else
            RefreshIntercompanyCodeData(ICCodecellInfo);
    }
    else {
        if (currentBEID == null) {
            IncomePC_Id.SetSelectedIndex(-1);
            IncomePNLCombo.SetSelectedIndex(-1);
            IncomePNLCodeCombo.SetSelectedIndex(-1);
            IncomeInterComp_Entity_Id.SetSelectedIndex(-1);
            IncomeInterComp_Code.SetSelectedIndex(-1);
            IncomeJournalType.SetSelectedIndex(-1);
            return;
        }
        lastBE_ID = currentBEID;
        RefreshIncomeBookingEntityData(bookingIdcellInfo);
        RefreshPCData(cellInfo);
        RefreshPNLData(pnlcellInfo);
        RefreshPNLCodeData(pnlCodecellInfo);
        RefreshIntercompanyData(ICcellInfo);
        RefreshIntercompanyCodeData(ICCodecellInfo);
        RefreshIncomeJournalTypeData(JournalTypeInfo);
    }
}

// ##########  Gridview End Edit
function OnIncomeBatchEditEndEditing(s, e) {
    currentEditableVisibleIndex = -1;
    var bookingEntityId = s.GetColumnByField("Booking_Entity_Id");
    var pcIDColumn = s.GetColumnByField("PC_Id");
    var pnlIDColumn = s.GetColumnByField("PNL_Account_No");
    var pnlCodeIDColumn = s.GetColumnByField("PNL_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 = IncomeBooking_Entity_Id.GetValue();
    bookingIdcellInfo.text = IncomeBooking_Entity_Id.GetText();
    IncomeBooking_Entity_Id.SetValue(null);

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

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

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

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

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

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

// ####### Booking Entity Combo Reload
function RefreshIncomeBookingEntityData(bookingIdcellInfo) {
    lastBE_ID = bookingIdcellInfo.value;
    IncomeBooking_Entity_Id.PerformCallback();
}

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

// ####### Intercompany Combo Reload
function RefreshIntercompanyData(ICcellInfo) {
    setICValueFlagIncome = ICcellInfo.value;
    IncomeInterComp_Entity_Id.PerformCallback();
}
// ####### Intercompany Code Combo Reload
function RefreshIntercompanyCodeData(ICCodecellInfo) {
    setICCodeValueFlagIncome = ICCodecellInfo.value;
    IncomeInterComp_Code.PerformCallback();
}

// ########## Profit Center Combo Reload
function RefreshPCData(cellInfo) {
    setValueFlag = cellInfo.value;
    IncomePC_Id.PerformCallback();
}

// ########## PNL Account Combo Reload
function RefreshPNLData(pnlcellInfo) {
    setpnlValueFlag = pnlcellInfo.value;
    IncomePNLCombo.PerformCallback();
}
// ########## PNL Account Code Combo Reload
function RefreshPNLCodeData(pnlCodecellInfo) {
    setpnlCodeValueFlag = pnlCodecellInfo.value;
    IncomePNLCodeCombo.PerformCallback();
}

function IncomeBookingId_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 IncomeInterCo_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 IncomeICCode_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 = false;
    }
}

function IncomePcCombo_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 IncomePNL_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 IncomePNLCode_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 IncomePNL_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('');
    }
    IncomePNLCodeCombo.SetValue(BSId);
}

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

function IncomePNLCode_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('');
    }
    IncomePNLCombo.SetValue(BSId);
}
// Check Whether Account Entry is permissible or not
function CheckpermissibleEntry(currentValue) {
    var permissibleEntites = $('#hdnParamforAccountBEValidation').val();
    var arr = permissibleEntites.split(',');
    for (i = 0; i < arr.length; i++) {
        if (arr[i] == currentValue)
            return true;
    }
    return false;
}

// #################### Set Related Values  ####################//
var validatecode = '';
function ValidateRegexIncome() {
    var Incomeamt = IncomeAmount.GetText();
    var IncomeAmttUsd = IncomeAmount_In_USD.GetText();
    var FxRate = IncomeFx_Rate.GetText();
    var SAPFxRate = IncomeSAP_FX_Rate.GetText();

    var numericReg = /^\d{0,8}(\.\d{0,2})?$/;
    var numericRegFx = /^\d{0,4}(\.\d{0,4})?$/;

    if (numericReg.test(Incomeamt) && numericReg.test(IncomeAmttUsd) && numericRegFx.test(FxRate) && numericRegFx.test(SAPFxRate))
        return true;
    else
        return false;
}

// ############ Set Fx Rate to SAP Fx Rate ############
function GetIncomeSAPFx() {
    var cId = Currency_IdIncome.GetValue();
    var postingDate = IncomePosting_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;               
                IncomeSAP_FX_Rate.SetValue(sapfxrate);
                UpdateIncome();
            }
            else {
                location.reload();
            }
        },
        error: function () { }
    });
}

function GetIncomeSAPFxRate() {
    var FxRate = IncomeFx_Rate.GetText();
    IncomeSAP_FX_Rate.SetText(FxRate.replace(/,/g, ''));
}

function UpdateIncome() {
    var income = parseFloat(IncomeAmount.GetText().replace(/,/g, '')); // Remove masking
    var FxRate = parseFloat(IncomeSAP_FX_Rate.GetText().replace(/,/g, ''));
    var total = parseFloat(income * FxRate).toFixed(2);//var total = parseFloat(income / FxRate).toFixed(2);
    IncomeAmount_In_USD.SetText(total);
}

//function UpdateIncome() {
//    var income = parseFloat(IncomeAmount.GetText().replace(/,/g, '')); // Remove masking
//    var FxRate = parseFloat(IncomeSAP_FX_Rate.GetText().replace(/,/g, ''));
//    var total = parseFloat(income / FxRate).toFixed(2);
//    IncomeAmount_In_USD.SetText(total);
//}
// ############ Get Country and Intercompany Code Based on Intercompany Entity ############//
function GetIncomeCountry_ICCode() {
    var CompanyId = IncomeInterComp_Entity_Id.GetValue();
    var sapsunId = IncomeInterComp_Code.GetValue();
    //var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId;
    var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId + "$" + IncomeBooking_Entity_Id.GetValue();
    if (CompanyId != null) {
        $.ajax({
            type: 'GET',
            data: null,
            contentType: 'application/json',
            url: url,
            chache: false,
            success: function (result) {
                IncomeCountry_Id.SetValue(result.CP_Country);
                //########## If the account description is “Purchase Intercomp. Or Sales Intercomp” then fill the corresponding Company Code
                //if (CompanyId.includes('L'))
                // IncomeInterComp_Code.SetValue(CompanyId);
                IncomeInterComp_Code.SetValue(result.CP_Code);
                //else
                //    IncomeInterComp_Code.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}
// ############ Get Country and Intercompany Based on Intercompany Entity ############//
function GetIncomeCountry_IC() {
    var CompanyId = IncomeInterComp_Code.GetValue();
    var sapsunId = IncomeInterComp_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) {
                IncomeCountry_Id.SetValue(result.CP_Country);
                //########## If the account description is “Purchase Intercomp. Or Sales Intercomp” then fill the corresponding Company
                //if (CompanyId.includes('L'))
                //IncomeInterComp_Entity_Id.SetValue(CompanyId);
                IncomeInterComp_Entity_Id.SetValue(result.CP_Short_Name);
                //else
                //    IncomeInterComp_Entity_Id.SetValue(null);
            },
            Error: function () { }
        });
    }
    else {
    }
}
// Not checking, now getting accessible entry to dropdown
function CheckForIncomeInterCoEntry(CompanyId) {
    var permissibleIEntites = $('#hdnParamforAccountIncomeIEValidation').val();
    var arr = permissibleIEntites.split(',');
    for (i = 0; i <= arr.length; i++) {
        if (arr[i] == CompanyId)
            return true;
    }
    return false;
}

//################ Check If the account description is “Purchase Intercomp. Or Sales Intercomp”  ####################//
function checkIncomeCompRequired(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 = "Please select intercompany!";
    }
    else {
        e.isValid = true;
    }
}

//############### VALIDATE AMOUNT AND SAP FX RATE ##############//
function validateAmt(s, e) {
    var amt = s.GetValue();
    if (amt == '0.00')
        e.isValid = false;
    else
        e.isValid = true;
}

function validateSAPFx(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 GetIncomeSAP_PNLByBE() {
    var CompanyId = IncomeBooking_Entity_Id.GetValue();
    var url = "Trade/GetSAP_PNLByBookingEntity";
    var data = {
        entityId: CompanyId
    }
    $.ajax({
        type: 'POST',
        data: data,
        url: url,
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {
            IncomeSAP_Account_Id.SetText(result);
        },
        Error: function () { }
    });
}

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

function GetIncomePNLCodeByNo() {

    var BSId = IncomePNL_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) {
            IncomePNL_Account_code.SetText(result);
        },
        Error: function () { }
    });
}

// #################### Check if Posting date is greater than or less than Trading date  ####################//
function ValidateIncomeTradeDate(s, e) {
    if (IncomePosting_Date.GetValue() != null) {
        if (TradeDate.GetValue() != null) {
            //Getting year
            var Trade_Year = TradeDate.GetValue().getFullYear();
            //Getting month
            var TradeMonth = TradeDate.GetValue().getMonth();

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

//  #################### Get Income related data  ####################//
function GetIncomeSummary() {
    var RefNo = SFM_Ref_Number.GetValue();
    var entityId = FilterEntity.GetValue();
    if (entityId == null) { entityId = '' }
    var transactionDate = TransactionDateFilter.GetText();

    var urlAccountIncome = $('#urlAccountIncome').val() + "?sfmRefNo=" + RefNo + "&entity=" + entityId + "&transactionDate=" + transactionDate;;
    $.ajax({
        type: "GET",
        contentType: "application.json",
        data: null,
        url: urlAccountIncome,
        cache: false,
        success: function (data) {
            $('#AccountIncomeData').html(data);
        },
        error: function (xhr) {
            $('#AccountIncomeData').html("");
            //$('#PopDiv1').css('color', 'red');
            //$("#PopDiv1").fadeIn();
            //$("#PopDiv2").html('Error Getting income summary');
            //$("#PopDiv1").fadeOut(8000);
        }
    })

    var urlAccountPNLSummary = $('#urlAccountPNLSummary').val() + "?sfmRefNo=" + RefNo + "&entity=" + entityId + "&transactionDate=" + transactionDate;

    $.ajax({
        type: "GET",
        contentType: "application.json",
        data: null,
        url: urlAccountPNLSummary,
        cache: false,
        success: function (data) {
            $('#AccountPNLData').html(data);
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn
            $("#PopDiv2").html('Error getting PNL data');
            $("#PopDiv1").fadeOut(8000);
        }
    })
}

//#################### Check Whether Account Entry Exist and Show Balance Sheet  ####################//

function CheckIncomeAccountForBSEntry(ref, incomeCost) {
    var urlCheckAccountForBSEntry = $('#urlCheckAccountForBSEntry').val() + "?_sfmRefNo=" + ref + "&incomeCost=" + incomeCost;
    $.ajax({
        type: "GET",
        contentType: "application.JSON",
        url: urlCheckAccountForBSEntry,
        cache: false,
        success: function (data) {
            if (data == true)
                $('#IncomeBalanceSheet').css("display", "block");
            else
                $('#IncomeBalanceSheet').css("display", "none");
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn
            $("#PopDiv2").html('Error Getting Account Entry for Balance Sheet.');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

// ################ Get Fx Rate based on currency #################//
function getSAPFxRate() {
    var cId = Currency_IdIncome.GetValue();
    var postingDate = IncomePosting_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;
                IncomeFx_Rate.SetValue(total);
                GetIncomeSAPFx();
            }
            else {
                location.reload();
            }
        },
        error: function () { }
    });
}


// Get value from Query string
function getQueryStringValue(key) {
    return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}