var currentEditableVisibleIndexCost;
var preventEndEditOnLostFocusCost = false;
var lastBE_IDCost;
var setValueFlagCost;
var setpnlValueFlagCost;
var setpnlCodeValueFlagCost;
var setICValueFlagCost;
var setICCodeValueFlagCost;
var currentValue;
var lastGoodsId = ''
var setJournalType;

// ########## Booking Entity Combo Selected index change
function CostBECombo_SelectedIndexChanged(s, e) {
    currentValue = s.GetValue();

    //GetCostSAP_PNLByBE(); //Get SAP PNL by Booking Entity
    //CostBooking_Entity_Id.SetSelectedItem(CostBooking_Entity_Id.FindItemByValue(currentValue));

    if (lastBE_IDCost == currentValue) {
        if (CostPCIdCombo.GetSelectedIndex() < 0)
            CostPCIdCombo.SetSelectedIndex(-1);

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

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

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

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

        if (CostInterComp_Code.GetSelectedIndex() < 0)
            CostInterComp_Code.SetSelectedIndex(-1);
        return;
    }
    lastBE_IDCost = currentValue;
    if (CostBooking_Entity_Id.GetValue() != null) {
        //if (CheckPermissibleCostEntry(currentValue)) {
        CostInterComp_Entity_Id.PerformCallback(); // Bind Intercompany
        CostInterComp_Code.PerformCallback(); // Bind Intercompany
        CostPCIdCombo.PerformCallback();         // Bind Cost PC
        CostPNLCombo.PerformCallback();  // Bind Cost PNL Description
        CostPNLCodeCombo.PerformCallback();  // Bind Cost PNL Code
        GetCostSAP_PNLByBE();
        CostBooking_Entity_Id.SetSelectedItem(CostBooking_Entity_Id.FindItemByValue(lastBE_ID));
        CostJournalType.PerformCallback();
        // }
        /* else {
             alert('You can\'t create entry for this Entity');
             CostBooking_Entity_Id.SetValue(null);
             lastBE_IDCost = null;
             CostSAP_Account_Id.SetText(null);
             CostInterComp_Entity_Id.SetValue(null);
             CostInterComp_Code.SetValue(null);
             CostPCIdCombo.SetValue(null);
             CostPNLCombo.SetValue(null);
             CostPNLCodeCombo.SetValue(null);
         }*/
    }
}

//function onRowClick(s, e) {
//    //if (e.htmlEvent.target.hasAttribute('cancel-click'))
//        e.cancel = true;
//    alert('The row is clicked, but it shouldnt!');
//}
function CostGoodsCombo_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);
        }
    });
    CostBooking_Entity_Id.PerformCallback();
}

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

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

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

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

// ########## PNL Account description Combo Begin Callback
function CostPNLCombo_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCost;
}

// ####### PNL Account code Combo Begin Callback
function CostPNLCode_BeginCallback(s, e) {
    e.customArgs['CompanyID'] = lastBE_IDCost;
}

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

// ########## Initialize all variables for Gridview
function IntializeCostGlobalVariables(gvAccountCost) {
    lastBE_IDCost = -1;
    currentEditableVisibleIndexCost = -1;
    setValueFlagCost = -1;
    setpnlValueFlagCost = -1;
    setpnlCodeValueFlagCost = -1;
    setICValueFlagCost = -1;
    setICCodeValueFlagCost = -1;
    setJournalType = -1;
}

// ########## Gridview Init
function OnCostInit(s, e) {
    IntializeCostGlobalVariables(s);
}

// ########## Gridview End Callback
function OnCostEndCallback(s, e) {
    IntializeCostGlobalVariables(s);
    // Get summary and check whether Account Entry Exist or not
    GetCostSummary();
    // CheckCostAccountForBSEntry(SFM_Ref_Number.GetValue(), 'C');
    gvAccountCostBalanceSheet.PerformCallback();
    gvAccountCostBalanceSheet.PerformCallback();
    EnableDisablePostButton();
}

// ####### BookingEntity Combo End Callback
function CostBookingId_EndCallback(s, e) {
    CostBooking_Entity_Id.SetSelectedItem(CostBooking_Entity_Id.FindItemByValue(lastBE_IDCost));
}

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

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

// ####### InterCompany code Combo End Callback
function CostICCode_EndCallback(s, e) {
    if (setICCodeValueFlagCost == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else {
        CostInterComp_Code.SetSelectedItem(CostInterComp_Code.FindItemByValue(setICCodeValueFlagCost));
        setICCodeValueFlagCost = -1;
    }
}

// ########## Profit Center Combo End Callback
function CostPcCombo_EndCallback(s, e) {
    if (setValueFlagCost == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setValueFlagCost > -1) {
        CostPCIdCombo.SetSelectedItem(CostPCIdCombo.FindItemByValue(setValueFlagCost));
        setValueFlagCost = -1;
    }
}
// ########## PNL Account Combo End Callback
function CostPNLCombo_EndCallback(s, e) {
    if (setpnlValueFlagCost == -1) {
        if (s.GetSelectedIndex() == -1) {
            s.SetSelectedIndex(-1);
        }
    }
    else if (setpnlValueFlagCost > -1) {
        CostPNLCombo.SetSelectedItem(CostPNLCombo.FindItemByValue(setpnlValueFlagCost));
        setpnlValueFlagCost = -1;
    }
}

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

// ########## Gridview Edit Start
function OnCostBatchEditStartEditing(s, e) {
    if (e.visibleIndex < 0) {
        gvAccountCost.GetEditor("Invoice_Date").SetEnabled(true);
        gvAccountCost.GetEditor("Due_Date").SetEnabled(true);
        gvAccountCost.GetEditor("Amount").SetEnabled(true);
        gvAccountCost.GetEditor("L2").SetEnabled(true);
        gvAccountCost.GetEditor("SAP_FX_Rate").SetEnabled(true);
        gvAccountCost.GetEditor("Fx_Rate").SetEnabled(true);
        CostBooking_Entity_Id.SetEnabled(true);
        CostCountry_Id.SetEnabled(true);
        CostInterComp_Entity_Id.SetEnabled(true);
        CostInterComp_Code.SetEnabled(true);
        CostPCIdCombo.SetEnabled(true);
        Currency_IdCost.SetEnabled(true);
        CostPNLCodeCombo.SetEnabled(true);
        CostPNLCombo.SetEnabled(true);
        CostJournalType.SetEnabled(true);
    }

    else {
        gvAccountCost.GetEditor("Invoice_Date").SetEnabled(false);
        gvAccountCost.GetEditor("Due_Date").SetEnabled(false);
        gvAccountCost.GetEditor("Amount").SetEnabled(false);
        gvAccountCost.GetEditor("L2").SetEnabled(false);
        gvAccountCost.GetEditor("SAP_FX_Rate").SetEnabled(false);
        gvAccountCost.GetEditor("Fx_Rate").SetEnabled(false);
        CostBooking_Entity_Id.SetEnabled(false);
        CostCountry_Id.SetEnabled(false);
        CostInterComp_Entity_Id.SetEnabled(false);
        CostInterComp_Code.SetEnabled(false);
        CostPCIdCombo.SetEnabled(false);
        Currency_IdCost.SetEnabled(false);
        CostPNLCodeCombo.SetEnabled(false);
        CostPNLCombo.SetEnabled(false);
        CostJournalType.SetEnabled(false);
    }
    
    var accountingId = s.GetRowKey(e.visibleIndex);
    if (accountingId != null) {
        var currentBEID = gvAccountCost.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)
                    StartCEditing(s, e)
                else
                    gvAccountCost.CancelEdit();
            }
        });
    }
    else
        StartCEditing(s, e);
}

function StartCEditing(s, e) {
    currentEditableVisibleIndexCost = e.visibleIndex;
    $('#hdnValidateInterCompanyCode').val('');
    var currentBEID = gvAccountCost.batchEditApi.GetCellValue(currentEditableVisibleIndexCost, "Booking_Entity_Id");
    lastGoodsId = gvAccountCost.batchEditApi.GetCellValue(currentEditableVisibleIndexCost, "Goods_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(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_IDCost == currentBEID) {
        if (CostBooking_Entity_Id.FindItemByValue(bookingIdcellInfo.value) != null)
            CostBooking_Entity_Id.SetValue(bookingIdcellInfo.value);
        else
            RefreshBookingEntityData(bookingIdcellInfo);

        if (CostJournalType.FindItemByValue(JournalTypeInfo.value) != null)
            CostJournalType.SetValue(JournalTypeInfo.value);
        else
            RefreshCostJournalTypeData(JournalTypeInfo);

        if (CostPCIdCombo.FindItemByValue(cellInfo.value) != null)
            CostPCIdCombo.SetValue(cellInfo.value);
        else
            RefreshCostData(cellInfo);

        if (CostPNLCombo.FindItemByValue(pnlcellInfo.value) != null)
            CostPNLCombo.SetValue(pnlcellInfo.value);
        else
            RefreshCostPNLData(pnlcellInfo);

        if (CostPNLCodeCombo.FindItemByValue(pnlCodecellInfo.value) != null)
            CostPNLCodeCombo.SetValue(pnlCodecellInfo.value);
        else
            RefreshCostPNLCodeData(pnlCodecellInfo);

        if (CostInterComp_Entity_Id.FindItemByValue(ICcellInfo.value) != null)
            CostInterComp_Entity_Id.SetValue(ICcellInfo.value);
        else
            RefreshCostIntercompanyData(ICcellInfo);

        if (CostInterComp_Code.FindItemByValue(ICCodecellInfo.value) != null)
            CostInterComp_Code.SetValue(ICCodecellInfo.value);
        else
            RefreshCostIntercompanyCodeData(ICCodecellInfo);
    }
    else {
        if (currentBEID == null) {
            CostPCIdCombo.SetSelectedIndex(-1);
            CostPNLCombo.SetSelectedIndex(-1);
            CostPNLCodeCombo.SetSelectedIndex(-1);
            CostInterComp_Entity_Id.SetSelectedIndex(-1);
            CostInterComp_Code.SetSelectedIndex(-1);
            CostJournalType.SetSelectedIndex(-1);
            return;
        }
        lastBE_IDCost = currentBEID;
        RefreshBookingEntityData(bookingIdcellInfo);
        RefreshCostData(cellInfo);
        RefreshCostPNLData(pnlcellInfo);
        RefreshCostPNLCodeData(pnlCodecellInfo);
        RefreshCostIntercompanyData(ICcellInfo);
        RefreshCostIntercompanyCodeData(ICCodecellInfo);
        RefreshCostJournalTypeData(JournalTypeInfo);
    }
}

// ##########  Gridview End Edit
function OnCostBatchEditEndEditing(s, e) {
    currentEditableVisibleIndexCost = -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 = CostBooking_Entity_Id.GetValue();
    bookingIdcellInfo.text = CostBooking_Entity_Id.GetText();
    CostBooking_Entity_Id.SetValue(null);

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

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

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

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

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

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

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

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

// ####### Intercompany Combo Reload
function RefreshCostIntercompanyData(ICcellInfo) {
    setICValueFlagCost = ICcellInfo.value;
    CostInterComp_Entity_Id.PerformCallback();
}

// ####### Intercompany Code Combo Reload
function RefreshCostIntercompanyCodeData(ICCodecellInfo) {
    setICCodeValueFlagCost = ICCodecellInfo.value;
    CostInterComp_Code.PerformCallback();
}


// ########## Profit Center Combo Reload
function RefreshCostData(cellInfo) {
    setValueFlagCost = cellInfo.value;
    CostPCIdCombo.PerformCallback();
}

// ########## PNL Account Combo Reload
function RefreshCostPNLData(pnlcellInfo) {
    setpnlValueFlagCost = pnlcellInfo.value;
    CostPNLCombo.PerformCallback();
}
function RefreshCostPNLCodeData(pnlCodecellInfo) {
    setpnlCodeValueFlagCost = pnlCodecellInfo.value;
    CostPNLCodeCombo.PerformCallback();
}

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

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

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

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

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

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

function CostPNLCombo_LostFocus(s, e) {
    var BSId = s.GetValue();
    //    var url = $('#urlGetPNL_BSCodeByPNL_BSNo').val() + "?PNL_No=" + BSId;

    //Check If the account description is “Purchase Intercomp. Or Sales Intercomp”
    if (s.GetText().includes('Intercomp')) {
        $('#hdnValidateInterCompanyCode').val('1'); //Means It Requires Inter-Company
    }
    else {
        $('#hdnValidateInterCompanyCode').val('');
    }
    CostPNLCodeCombo.SetValue(BSId);
}

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

    CostPNLCodeCombo.SetValue(BSId);
}

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

// Check Whether Account Entry is permissible or not
function CheckPermissibleCostEntry(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 Fx Rate to SAP Fx Rate
function GetCostSAPFx() {
    var cId = Currency_IdCost.GetValue();
    var postingDate = CostPosting_Date.GetText();
    var urlGetFxRate = $('#urlGetSAPFxRateBasedonCurrency').val() + "?currencyID=" + cId + "&pDate=" + postingDate;
    $.ajax({
        type: "GET",
        contentType: "application.JSON",
        url: urlGetFxRate,
        cache: false,
        success: function (result) {
            debugger;
            if (!isNaN(parseFloat(result))) {
                var SapFxRate = result;
                CostSAP_FX_Rate.SetValue(SapFxRate);
                UpdateCost();
            }
            else {
                location.reload();
            }

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

function GetCostSAPFxRate() {
    var FxRate = CostSAP_FX_Rate.GetText();
    CostSAP_FX_Rate.SetText(FxRate.replace(/,/g, ''));  
}


// change for SAP FX Rate
function UpdateCost() {
    debugger;
    var cId = Currency_IdCost.GetValue();
    var Cost = parseFloat(CostAmount.GetText().replace(/,/g, ''));
    var FxRate = parseFloat(CostSAP_FX_Rate.GetText().replace(/,/g, ''));
    var total = parseFloat(Cost * FxRate).toFixed(2); //var total = parseFloat(Cost / FxRate).toFixed(2);
    var divideByR
    if (cId == "1049")//IDR 
        divideByR = parseFloat(total / 10000.00).toFixed(2);
    else if (cId == "14" || cId == "1042" || cId == "1045" || cId == "9" || cId == "10" || cId == "1050" || cId == "1051" || cId == "1058" || cId == "14" || cId == "1044")//DZD GYD INR JPY KRW KZT PYG THB XOF 
        divideByR = parseFloat(total / 100.00).toFixed(2);
    CostAmount_In_USD.SetText(divideByR);    
}

//#################### Get Country Name Based on Inter Company Entity #################### //
function GetCostCountry_ICCode() {
    var CompanyId = CostInterComp_Entity_Id.GetValue();
    //var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId;
    var url = $('#urlAccountCountry').val() + "?EntityId=" + CompanyId + "$" + CostBooking_Entity_Id.GetValue();
    if (CompanyId != null) {
        $.ajax({
            type: 'GET',
            data: null,
            contentType: 'application/json',
            url: url,
            chache: false,
            success: function (result) {
                CostCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                //CostInterComp_Code.SetValue(CompanyId);
                CostInterComp_Code.SetValue(result.CP_Code);
                //else
                //    CostInterComp_Code.SetValue(null);
            },
            Error: function () { }
        });
    }
    else { }

}

//#################### Get Country Name Based on Inter Company Entity #################### //
function GetCostCountry_IC() {
    var CompanyId = CostInterComp_Code.GetValue();
    var sapsunId = CostInterComp_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) {
                CostCountry_Id.SetValue(result.CP_Country);
                //if (CompanyId.includes('L'))
                //CostInterComp_Entity_Id.SetValue(CompanyId);
                CostInterComp_Entity_Id.SetValue(result.CP_Short_Name);
                //else
                //    CostInterComp_Entity_Id.SetValue(null);
            },
            Error: function () { }
        });
    }
    else { }
}
//################# To See whether logged in user can add/update entry for selected Intercompany Entity
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 checkCostCompRequired(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 validateCostAmt(s, e) {
    var amt = s.GetValue();
    if (amt == '0.00')
        e.isValid = false;
    else
        e.isValid = true;
}
//    function validateCostFx(s, e) {
//        var amt = s.GetValue();
//        if (amt == '0.000000')
//            e.isValid = false;
//        else
//            e.isValid = true;
//    }
function validateCostSAPFx(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 used in PC_PNLCost.js #################### //

function GetCostSAP_PNLByBE() {
    var CompanyId = CostBooking_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) {
            CostSAP_Account_Id.SetText(result);
            CostBooking_Entity_Id.SetValue(CompanyId);
        },
        Error: function () { }
    });
}

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

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


}

//#################### Automatically fill CFS Ref No to Assignment Field ####################//
//    function getCostReference() {
//        var ref = SFM_Ref_Number.GetText();
//        CostAssignment_No.SetText(ref);
//        CostAssignment_No.SetEnabled(false);
//    }

// #################### Get Cost related data #################### //
function GetCostSummary() {
    
    //        var RefNo = $('#hdnGlobalRef').val();
    var RefNo = SFM_Ref_Number.GetValue();
    var entityId = FilterEntity.GetValue();
    if (entityId == null) { entityId = '' }
    var transactionDate = TransactionDateFilter.GetText();

    var urlAccountCost = $('#urlAccountCost').val() + "?sfmRefNo=" + RefNo + "&entity=" + entityId + "&transactionDate=" + transactionDate;
    $.ajax({
        type: "GET",
        contentType: "application.json",
        url: urlAccountCost,
        data: null,
        cache: false,
        success: function (data) {
            $('#AccountCostData').html(data);
        },
        error: function (xhr, status, error) {
            $('#AccountCostData').html("");
            //$('#PopDiv1').css('color', 'red');
            //$("#PopDiv1").fadeIn();
            //$("#PopDiv2").html('Error Getting cost 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);
        }
    });
}
// #################### Get PNL Code Based on PNL No  ####################//

function GetCostPNLCodeByNo() {
    var BSId = CostPNL_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) {
            CostPNL_Account_code.SetText(result);
        },
        Error: function () { }
    });
}
// #################### to check whether account has entry or not to show balance sheet section used in PNL_PCCost js  #################### //
function CheckCostAccountForBSEntry(ref, CostCost) {
    var urlCheckAccountForBSEntry = $('#urlCheckAccountForBSEntry').val() + "?_sfmRefNo=" + ref + "&CostCost=" + CostCost;
    $.ajax({
        type: "GET",
        contentType: "application.JSON",
        url: urlCheckAccountForBSEntry,
        cache: false,
        success: function (data) {
            if (data == true)
                $('#CostBalanceSheet').css("display", "block");
            else
                $('#CostBalanceSheet').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 getCostSAPFxRate() {
    var cId = Currency_IdCost.GetValue();
    var postingDate = CostPosting_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;
                CostFx_Rate.SetValue(total);
                GetCostSAPFx();
            }
            else {
                location.reload();
            }

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