$(document).ready(function () {
    $("#accounting").click(function () {
        var RefNo = $('#hdnGlobalRef').val();

        //   URL to Get SFM String in Account Section
        var urlAccountSFMString = $('#urlAccountString').val() + "?SFMRefNo=" + RefNo;
        var urlAccountPNLSummary = $('#urlAccountPNLSummary').val() + "?sfmRefNo=" + RefNo;
        var urlAccountBSSummary = $('#urlAccountBSSummary').val() + "?sfmRefNo=" + RefNo;
        var urlAccountVessel = $('#urlAccountVessel').val() + "?_sfmRefNo=" + RefNo;

        //Hide Add button if SFM Reference number is empty!!!
        if (RefNo == null || RefNo == '') {
            $('#btnAddNewCost').hide();
            $('#btnAddNewIncome').hide();
        }

        //######### Fill Vessel name in Account Partial #########//
        $.ajax({
            type: "GET",
            contentType: "application.json",
            url: urlAccountVessel,
            data: null,
            cache: false,
            success: function (data) {
                txtAccountVessel.SetText(data);
            },
            error: function (xhr) {
                $('#PopDiv1').css('color', 'red');
                $("#PopDiv1").fadeIn
                $("#PopDiv2").html('Error occurred while getting vessel');
                $("#PopDiv1").fadeOut(8000);
            }
        });

        // ######### Get String for both Income & Cost ######### //
        $.ajax({
            type: "GET",
            contentType: "application.json",
            data: null,
            url: urlAccountSFMString,
            cache: false,
            success: function (data) {
                if (data.indexOf('-&gt') !== -1) {
                    // Fill Income Section
                    $('#AccShipmentstringIncomeData').html(data);
                    // Fill Cost Section
                    $('#AccShipmentstringCostData').html(data);
                    $('#AccShipmentstringIncomeData').show();
                    $('#AccShipmentstringCostData').show();
                    $('#AccountFilter').show();
                    $('#AccIncomeData').hide();
                }
                else {
                    $('#AccIncomeData').show();
                    $('#AccShipmentstringIncomeData').hide();
                    $('#AccShipmentstringCostData').hide();
                    $('#AccountFilter').hide();
                }
            },
            error: function (xhr) {
                $('#PopDiv1').css('color', 'red');
                $("#PopDiv1").fadeIn
                $("#PopDiv2").html('Error occurred while getting data');
                $("#PopDiv1").fadeOut(8000);
            }
        });

        // Get PNL Summary for Account
        $.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);
            }
        });
        GetValidationForEntry();
        /// GetValidationForIEntityEntry();  For Now We are not checking validation we are getting only thoes entity in Intercompany for which entry need to be made
    });
});

//######### Code to Update/Insert Vessel in Origination/Trade #########//
function UpdateVesselToTrade() {

    var RefNo = $('#hdnGlobalRef').val();

    if (RefNo == null || RefNo == '') {
        alert('Please Select Trade');
        return false;
    }
    else {
        var vessel = txtAccountVessel.GetText();
        var urlUpdateVesselToTrade = $('#urlUpdateVesselToTrade').val() + "?_sfmRefNo=" + RefNo + "&vesselName=" + vessel;
        $.ajax({
            type: "GET",
            contentType: "application.json",
            data: null,
            url: urlUpdateVesselToTrade,
            cache: false,
            success: function (data) {
                $('#PopDiv1').css('color', 'green');
                $("#PopDiv1").fadeIn
                $("#PopDiv2").html(data);
                $("#PopDiv1").fadeOut(4000);
            },
            error: function (xhr) {
                $('#PopDiv1').css('color', 'red');
                $("#PopDiv1").fadeIn
                $("#PopDiv2").html('Error adding Vessel to Trade');
                $("#PopDiv1").fadeOut(4000);
            }
        })
    }
}

function GetPostType() {
    var value = chkCostManualPost.GetValue();
    $('#hdnPostType').val(value);
    if (value == 'S')
        txtPostingJVNo.SetVisible(false);
    else
        txtPostingJVNo.SetVisible(true);
}

function GetSAPPostType() {
    var value = chkSapManualPost.GetValue();
    $('#hdnPostType').val(value);
    if (value == 'S')
        txtPostingJVNo1.SetVisible(false);
    else
        txtPostingJVNo1.SetVisible(true);
}

function GetAccountTypeToPost(type) {
    $('#hdnDataType').val(type);
}

//############ Get Accessible Booking Entity for Account Entry with comma separated string
//### This function has also been called in TradeIndex.js for User coming from Accounting menu
function GetValidationForEntry() {
    var RefNo = SFM_Ref_Number.GetValue();
    var url = $('#urlGetEntitiesForValidation').val() + "?sfmRefNo=" + RefNo;
    $.ajax({
        type: 'GET',
        data: null,
        contentType: 'application/json',
        url: url,
        success: function (result) {
            $('#hdnParamforAccountBEValidation').val(result);
        },
        Error: function () { }
    });
}

//################### Get name/id of selected Company in Posting list
var selectedIDs;
var AccMergedId;
var BSMergedId;
var singEntityId;
function onSelectionChanged(s, e) {
    s.GetSelectedFieldValues("Booking_Entity_Id", GetSelectedFieldValuesCallback);
    s.GetSelectedFieldValues("Acc_Merged_Id", GetSelectedAcc_Merged_IdValuesCallback);
    s.GetSelectedFieldValues("BS_Merged_Id", GetSelectedBS_Merged_IdValuesCallback);
}

function GetSelectedFieldValuesCallback(values) {
    $('#hdnCompanyName').val(values[0]);
}

function GetSelectedAcc_Merged_IdValuesCallback(values) {
    AccMergedId = "";
    for (var i = 0; i < values.length; i++) {
        if (AccMergedId == "")
            AccMergedId = AccMergedId + values[i];
        else
            AccMergedId = AccMergedId + "," + values[i];
    }
    if (AccMergedId)
        $('#hdnAcc_Merged_Id').val(AccMergedId);
}
function GetSelectedBS_Merged_IdValuesCallback(values) {
    BSMergedId = "";
    for (var i = 0; i < values.length; i++) {
        if (BSMergedId == "")
            BSMergedId = BSMergedId + values[i];
        else
            BSMergedId = BSMergedId + "," + values[i];
    }
    if (BSMergedId)
        $('#hdnBS_Merged_Id').val(BSMergedId);
}
// Check if JV No entered or not in manual posting
function PostTrade() {
    var JvNo = txtPostingJVNo.GetText();
    var _url = $('#urlPostData').val();
    var data = {
        JV_No: txtPostingJVNo.GetText(),
        Posting_Type: chkCostManualPost.GetValue(),
        BalanceSheetIds: $('#hdnBS_Merged_Id').val(),
        AccountingIds: $('#hdnAcc_Merged_Id').val()
    };
    if (txtPostingJVNo.GetVisible()) {
        if (JvNo == null || JvNo == '') {
            alert('Please enter JV No.');
        }
        else {
            // Post Trade Data
            $.ajax({
                url: _url,
                type: "POST",
                dataType: 'json',
                data: JSON.stringify(data),
                contentType: "application/json; charset=utf-8",
                cache: false,
                success: function (result) {
                    alert(result);
                    if (result == 'JV Number already Exist!') {
                        return false;
                    }
                    else {
                        $('#hdnBS_Merged_Id').val('');
                        $('#hdnAcc_Merged_Id').val('');
                        CostPostAlert.Hide();

                        // Reload all grids 
                        gvAccountIncome.PerformCallback();
                        gvAccountIncomeBalanceSheet.PerformCallback();
                        gvAccountCost.PerformCallback();
                        gvAccountCostBalanceSheet.PerformCallback();
                        //gvBookingEntityBS.PerformCallback();  // PerformCallback for Booking Entity Balance Sheet
                        gvPostedAccount.PerformCallback(); // Perform Callback for Posted Data
                    }
                },
                error: function (result) {
                    alert(result);
                }
            });
        }
    }
    else {
        //SAP Posting
        alert('SAP Posting not allowed as of now!');
    }
}

// Clear Hidden field if user cancel posting operation
function ClearDataIfPostClose() {
    $('#hdnBS_Merged_Id').val('');
    $('#hdnAcc_Merged_Id').val('');
}
// Print selected page.
function PrintThis(posting) {
    var divToPrint = document.getElementById(posting);
    newWin = window.open("");
    newWin.document.write(divToPrint.outerHTML);
    newWin.print();
    newWin.close();
}
// Set Vessel Name on posting page
function setVassel() {
    var vessel = txtAccountVessel.GetText();
    document.getElementById("spnPostingVessel").textContent = vessel;
}

function ShowFinalPostingScreen() {
    //gvPostingDetails.PerformCallback({ companyId: 'AAPL' });
    var hdnAcc_Merged_Id = $('#hdnAcc_Merged_Id').val();
    var hdnBS_Merged_Id = $('#hdnBS_Merged_Id').val();
    var hdnCompanyName = $('#hdnCompanyName').val();
    if (!hdnCompanyName && !hdnAcc_Merged_Id && !hdnBS_Merged_Id)
        alert("Please select data for posting");
    else {
        DataToPost.Hide();
        CostPostAlert.Show();
        gvPostingDetails.PerformCallback({ companyId: $('#hdnCompanyName').val() });
    }
}

var selectedJV;
function SelectionChanged(s, e) {
    s.GetSelectedFieldValues("JV_No", GetSelectedFieldsValuesCallback);
}
function GetSelectedFieldsValuesCallback(values) {
    try {
        selectedJV = "";
        for (var i = 0; i < values.length; i++) {
            selectedJV = values[i];
        }
    } finally {
        $('#hdnJVNo').val(selectedJV);
    }
}

//************* Reverse Post Account Date

function ReversePostData() {
    var _url = $('#urlReversePostData').val();
    var JvNo = $('#hdnJVNo').val();
    var data = {
        JV_No: $('#hdnJVNo').val()
    }
    if (JvNo == null || JvNo == '') {
        alert('Please select data to reverse');
    }
    else {
        $.ajax({
            method: 'POST',
            url: _url,
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {
                alert(result);
                $('#hdnJVNo').val('');
                ReversePost.Hide();

                // Reload all grids 
                gvAccountIncome.PerformCallback();
                gvAccountIncomeBalanceSheet.PerformCallback();
                gvAccountCost.PerformCallback();
                gvAccountCostBalanceSheet.PerformCallback();
                //gvBookingEntityBS.PerformCallback();  // Perform Callback for Booking Entity Balance Sheet
                gvPostedAccount.PerformCallback(); // Perform Callback for Posted Data
            },
            error: function () {
                alert('error!');
            }
        });
    }
}

//******** Cear hidden fields when posted entries printed Ref:PostingDataPrintPartial
function ClearDataIfPrintClose() {

}

// Set Vessel Name on posting print page
function setVasselForPrint() {
    var vessel = txtAccountVessel.GetText();
    document.getElementById("spnPrintVessel").textContent = vessel;
}

function PrintDetails(jvNo) {
    $('#hdnAcc_JVNo').val(jvNo);
    AccountPrintPopup.Show();
    gvPostingPrintDetails.PerformCallback({ jvNo: jvNo });
}

// Show posting data
var sunSelectedAccounts
var sunSfmNo
var status
function ShowPostData() {  
    sunPostResult = null;
    sunSfmNo = null;
    var selectedIncomeKeys = gvAccountIncome.GetSelectedKeysOnPage();
    var selectedCostKeys = gvAccountCost.GetSelectedKeysOnPage();
    var selectedKeys;
    if (selectedIncomeKeys == '')
        selectedKeys = selectedCostKeys.toString()
    else if (selectedCostKeys == '')
        selectedKeys = selectedIncomeKeys.toString()
    else if ((selectedCostKeys != '') && (selectedIncomeKeys != ''))
        selectedKeys = selectedIncomeKeys.toString() + ',' + selectedCostKeys.toString()

    if (selectedKeys == '')
        alert('Please select from accounting section')
    else {
        PostLoadingModal.Show();
        var data = {
            accountingIds: selectedKeys,
        }
        ClearDataIfPostClose();
        $.ajax({
            method: 'POST',
            url: 'Trade/ValidateSelectedRecords',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {              
                PostLoadingModal.Hide();
                if (result.Status == 0) {
                    status = 0;
                    sunSfmNo = SFM_Ref_Number.GetValue();
                    sunSelectedAccounts = selectedKeys
                    if (result.IsSAP == true) {SapPostPopUp.Show();}
                    else {SunPostPopUp.Show();}
                }
                else if (result.Status == 1)
                    alert('Please select single entity for posting')
                else if (result.Status == 2)
                    alert('Please add BS account for posting')
                else if (result.Status == 3)
                    alert('Please add journal type for posting')
                else if (result.Status == 4)
                    alert('Please add BS account and journal type for posting')
                else if (result.Status == 5)
                    alert('PNL amount and Balance sheet amount do not balance each other for the posting.Please correct them')
                else if (result.Status == 6) {
                    status = 6;
                    sunSfmNo = SFM_Ref_Number.GetValue();
                    sunSelectedAccounts = selectedKeys
                    if (result.IsSAP == true) { SapPostPopUp.Show(); }
                    else { SunPostPopUp.Show(); }
                }
                else if (result.Status == 7)
                    alert('Both PNL amount and PNL USD amount are not balanced by Balance sheet amount and USD amount.Please correct them')
            },
            error: function () {
                alert('error!');
            }
        });
    }
}

// Post accounting data
function PostData(isSAP) {
    PostNotificationModal.Show();
    var postingType = "";
    var journalNo = "";
    if (isSAP == 'true') {
        postingType = chkSapManualPost.GetValue();
        journalNo = txtPostingJVNo1.GetText();
    }
    else {
        postingType = chkCostManualPost.GetValue();
        journalNo = txtPostingJVNo.GetText();
    }
    if (postingType == "M" && journalNo == "") {
        PostNotificationModal.Hide();
        alert("Please enter jv number for the manual entry");
        return false;
    }
    else {
        if (isSAP == 'true') {
            SapPostPopUp.Hide();
            //postingType = chkSapManualPost.GetValue();
            //journalNo = txtPostingJVNo1.GetText();
        }
        else {
            SunPostPopUp.Hide();
            //postingType = chkCostManualPost.GetValue();
            //journalNo = txtPostingJVNo.GetText();
        }
        sunSfmNo = SFM_Ref_Number.GetValue();
        btnConfCostPost.SetEnabled(false);

        var data = {
            accountingIds: sunSelectedAccounts,
            sfmRefNo: sunSfmNo,
            postingType: postingType,
            journalNo: journalNo,
            isSAP: isSAP
        }
        ClearDataIfPostClose();
        $.ajax({
            method: 'POST',
            url: 'Trade/PostAccount',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {
                PostNotificationModal.Hide();
                alert(result.message);
                var substring = 'Trade?';
                var url = document.URL;
                var domain = url.substr(0, url.lastIndexOf(substring));
                window.location.href = domain + 'Trade?SFMRefNo=' + result.sfmNo;
            },
            error: function () {
                alert('error!');
            }
        });
    }
}

function SunPostingDetail_BeginCallback(s, e) {
    e.customArgs['accountingIds'] = sunSelectedAccounts;
    e.customArgs['sfmNo'] = sunSfmNo;
    e.customArgs['status'] = status;
}

function ReversePostData(s, e) {
    var selectedKey = s.GetRowKey(e.visibleIndex);;
    sunSfmNo = SFM_Ref_Number.GetValue();
    var data = {
        accountingId: String(selectedKey),
        sfmNo: sunSfmNo
    }
    PostNotificationModal.Show();
    $.ajax({
        method: 'POST',
        url: 'Trade/AccountReversePosting',
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {
            PostNotificationModal.Hide();
            alert(result);
            // Reload all grids 
            gvAccountIncome.PerformCallback();
            gvAccountIncomeBalanceSheet.PerformCallback();
            gvAccountCost.PerformCallback();
            gvAccountCostBalanceSheet.PerformCallback();
            gvPostedAccount.PerformCallback(); 

            //var substring = 'Trade?';
            //var url = document.URL;
            //var domain = url.substr(0, url.lastIndexOf(substring));
            //window.location.href = domain + 'Trade?SFMRefNo=' + sunSfmNo;
        },
        error: function () {
            alert('error!');
        }
    });
}

function EnableDisablePostButton() {
    var sfmNo = SFM_Ref_Number.GetValue();
    if (sfmNo != null) {
        var data = {
            sfmNo: String(sfmNo)
        }
        $.ajax({
            method: 'POST',
            url: 'Trade/ValidatePosting',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {
                if (result == false) {
                    //var sessionIBS = $("#sessionIBS").val();
                    //var sessionCBS = $("#sessionCBS").val();
                    //var sessionI = $("#sessionI").val();
                    //var sessionC = $("#sessionC").val();

                    //if (sessionIBS != '' || sessionCBS != '' || sessionI != '' || sessionC != '') {
                    //    alert("PNL and balance sheet values are different");
                    //    $("#sessionIBS").val("");
                    //    $("#sessionCBS").val("");
                    //    $("#sessionI").val("");
                    //    $("#sessionC").val("");
                    //}
                    btnPostIncome.SetEnabled(false);
                    $(lblAccPost).text("PNL and Balance Sheet values are different. Posting is not allowed.");
                }
                else {
                    btnPostIncome.SetEnabled(true);
                    $(lblAccPost).text("");
                }
            },
            error: function () {
                alert('error!');
            }
        });
    }
}

function FilterAccounting() {
    gvAccountIncome.PerformCallback();
    gvAccountCost.PerformCallback();
    gvAccountCostBalanceSheet.PerformCallback();
    gvAccountIncomeBalanceSheet.PerformCallback();
    //gvBookingEntityBS.PerformCallback();
}

function SaveSFMString() {
    var sfmNo = SFM_Ref_Number.GetValue();
    var entity1 = Entity1.GetValue();
    var entity2 = Entity2.GetValue();
    var entity3 = Entity3.GetValue();
    var entity4 = Entity4.GetValue();
    var entity5 = Entity5.GetValue();
    var entity6 = Entity6.GetValue();

    if (entity1 == null || entity2 == null || entity3 == null)
        alert("Please enter atleast three entities");
    else {
        var data = {
            sfmNo: sfmNo,
            entity1: String(entity1),
            entity2: String(entity2),
            entity3: String(entity3),
            entity4: String(entity4),
            entity5: String(entity5),
            entity6: String(entity6)
        }
        $.ajax({
            method: 'POST',
            url: 'Trade/SaveSFMString',
            dataType: 'json',
            data: JSON.stringify(data),
            contentType: "application/json; charset=utf-8",
            cache: false,
            success: function (result) {
                Entity1.SetValue(null);
                Entity2.SetValue(null);
                Entity3.SetValue(null);
                Entity4.SetValue(null);
                Entity5.SetValue(null);
                Entity6.SetValue(null);

                var substring = 'Trade?';
                var url = document.URL;
                var domain = url.substr(0, url.lastIndexOf(substring));
                window.location.href = domain + 'Trade?SFMRefNo=' + sfmNo;
            },
            error: function () {
                alert('error!');
            }
        });
    }
}

function IsDuplicateEntity(s,e,sequence)
{
    var entities = [];
    var currentEntity = s.GetValue();

    for (var j = 1; j <= 6 ; j++) {
        if (j != sequence) {
            var entityEditor = ASPxClientControl.GetControlCollection().GetByName('Entity' + j);
            entities.push(entityEditor.GetValue());
        }
    }

    for (var i = 0; i < entities.length; i++) {
        if (entities[i] == currentEntity) {
            alert("This entity has been entered already. Choose another one")
            s.SetValue("");
        }
    }
}