var _trade_flows = [];
var notremovedTradeFlow = "";
var nogoodsTradeFlow = "";
var _trade_flows_new;
var running = false;
var waiting = false;
var latestvalue = [];
var tf_count = 0;
var tf_c = 0;
//#########  ADD, UPDATE ORIGINATION #########//
var RefNo;
var queue = [];
function OriginationOperation(doWhat) {
    var _url = $('#urlOriginationOperation').val() + "?whichOperation=" + doWhat;
    if (TradeDate.GetDate() == null || TransactionType_Id.GetValue() == null || CPId.GetValue() == null || RiskCountry.GetValue() == null || Currency.GetValue() == null
        || Currency1_Amount.GetValue() == null || InstrumentType.GetValue() == null || TradeFlow.GetValue() == null || StrategyType.GetValue() == null || StrategySubType.GetValue() == null || FxRate.GetText() == null || FxRate.GetText() == '' || Tenure_Days.GetValue() == null)
        return false; // RiskIssuerID.GetValue() == null || 
    var ids = "";
    var IsAdminis = "";
    var IsAdminisValue = "";
    $.each(TradeFlow.GetValue(),
        function () {
            if (ids == "") {
                ids = this;
            }
            else {
                ids = ids + "," + this;
            }
        }); //console.log(ids)

    /***Check If Administrational***/
    IsAdminis = StrategyType.GetValue();
        
            if (IsAdminis == "1019") {
                IsAdminisValue = 1 ;
            }
            else {
                IsAdminisValue = 0;
            }
        

    var data = {
        SFM_Ref_No: $("#hdnGlobalRef").val() != '' ? $("#hdnGlobalRef").val() : "1",
        CP_Id: CPId.GetValue() != '' ? CPId.GetValue() : "0",
        Transaction_Type_Id: TransactionType_Id.GetValue() != '' ? TransactionType_Id.GetValue() : "0",
        Country_Id: RiskCountry.GetValue() != '' ? RiskCountry.GetValue() : "0",
        Risk_Issuer_Id: RiskIssuerID.GetValue() != '' ? RiskIssuerID.GetValue() : "0",
        InstrumentType_Id: InstrumentType.GetValue() != '' ? InstrumentType.GetValue() : "0",
        Trade_Flow_No: "",// != '' ? ids : "0",
        HdTradeFlow: ids,
        AdministrationalTrade: IsAdminisValue,
        Tenure_Days: Tenure_Days.GetText() != '' ? Tenure_Days.GetText() : '270',
        Strategy_Id: StrategyType.GetValue() != '' ? StrategyType.GetValue() : "0",
        StrategySub_Id: StrategySubType.GetValue() != '' ? StrategySubType.GetValue() : "0",
        //Estimated_Execution_Month: Estimated_Execution_Month.GetValue(),
        //Estimated_Execution_Year: Estimated_Execution_Year.GetText(),
        //Estimated_Execution_PNL: Estimated_Execution_PNL.GetText().replace(/,/g, ''),
        Trade_Date: TradeDate.GetText(),
        Currency1_Id: Currency.GetValue() != '' ? Currency.GetValue() : "0",
        Currency2_Amount: Currency2Amount.GetValue() != '' ? Currency2Amount.GetValue().replace(/,/g, '') : "0",
        Currency1_Amount: Currency1_Amount.GetText().replace(/,/g, ''),
        Fx_Rate: FxRate.GetText().replace(/,/g, ''),
        Bloomberg_Trade: Bloomberg_Trade.GetText(),
        Comments: Comments.GetText()
    };
    $.ajax({
        url: _url,
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {
            
            if (result.indexOf('|') > 0)
            {
                var x = result.split('|');
                if (x[0].search("Error :") == -1) {
                    $('#PopDiv1').css('color', 'green');
                    $("#PopDiv1").fadeIn();
                    $("#PopDiv2").html(x[0]);
                    $("#PopDiv1").fadeOut(8000);

                    var url = document.URL;
                    //if (!url.includes('SFMRefNo'))
                    url = document.URL.split('?')[0] + "?SFMRefNo=" + x[1];
                    
                    window.location.href = url;
                }
                else {
                    $('#PopDiv1').css('color', 'red');
                    $("#PopDiv1").fadeIn();
                    $("#PopDiv2").html(x[0]);
                    $("#PopDiv1").fadeOut(8000);
                }
            }
            else {
                $('#PopDiv1').css('color', 'red');
                $("#PopDiv1").fadeIn();
                $("#PopDiv2").html(result);
                $("#PopDiv1").fadeOut(8000);
            }
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html(xhr.responseText);
            $("#PopDiv1").fadeOut(8000);
        }
    });
    //return true;
}

//#########  Clear Fields #########//
function CancelOrigination() {
    //************ Search Partial ***********//
    $("#hdnGlobalRef").val('');
    SFM_Ref_Number.SetValue('');
    $('#spSFM_Ref_No').text('');
    $('#spParent_SFM_Ref_No').text('');
    $('#spTrade_Status_Name').text('');
    $('#spCreated_By').text('');
    $('#spCreated_On').text('');
    $('#hdnGlobalRef').val('');
    $('#TransactionalCPID').val('');
    //************* Origination ***********// 
    TradeDate.SetValue(null);
    FxRate.SetValue('1'); // STATIC FOR Fx Rate
    CPId.SetValue('');
    Currency2Amount.SetValue('');
    RiskIssuerID.SetValue('');
    $('#RiskISId').val('');
    RiskCountry.SetValue('');
    TransactionType_Id.SetValue('');
    //Estimated_Execution_Month.SetValue(new Date().getUTCMonth() + 1); //Get Month By default
    Currency.SetValue('17'); // STATIC FOR USD
    InstrumentType.SetValue('');
    //TradeFlow.SetValue(null);
    //TradeFlow.SetEnabled(true);
    setGLValue(TradeFlow, [], btnSaveOrigin);
    _trade_flows = [];
    $('#TradeFID').val('');
    StrategyType.SetValue('');
    StrategySubType.SetValue('');
    $('#Strategy_SubTypeID').val('');
    //Estimated_Execution_Year.SetValue(new Date().getFullYear()); //Get Year By default
    Currency1_Amount.SetValue('0');
    Tenure_Days.SetText('270'); // STATIC FOR Tenure Days
    //Estimated_Execution_PNL.SetValue('');
    Comments.SetText('');
}

//#########  For Copy, Clone, Settle, Finalize & Activate #########//
function PerformTradeOperation(doWhat) {
    // alert(1);
    var _url = $('#urlPerformTrade').val() + "?whichOperation=" + doWhat;
    var sfm = $("#hdnGlobalRef").val() != '' ? $("#hdnGlobalRef").val() : "1";
    var reason = '';
    // if activate existing trade
    var ActivateExisting = '';
    if (doWhat == 'Activate Existing') {
        var value = ActivateList.GetValue();
        ActivateExisting = value == 'Finalize' ? 'F' : value == 'Both' ? 'B' : 'S';
    }

    if (sfm == "1") {
        alert("Please Select Origination Data to " + doWhat);
        return false;
    }

    if (doWhat == 'Print' || doWhat == 'Copy' || doWhat == 'Clone' || doWhat == 'Void' || doWhat == 'Sign Off' || doWhat == 'Finalize' || doWhat == 'Activate Existing') {
        //alert(2);
        askforOperation = confirm('Do you want to ' + doWhat + ' trade?');
        if (!askforOperation)
            return false;
        else {
            if (doWhat == 'Void') {
                reason = prompt("Enter The reason : ", "");
                if (reason == null) {
                    alert("User cancelled the operation.");
                    return false;
                }
            }
        }
    }
    var data = {
        SFM_Ref_No: $("#hdnGlobalRef").val() != null ? $("#hdnGlobalRef").val() : "1",
        ActivateSFB: ActivateExisting,
        voidanceReason: reason
    };

    $.ajax({
        url: _url,
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {
        
            if (result.indexOf('New') > 0 || result.indexOf('finalized') > 0) {
                if (doWhat == 'Void') {
                    if (result == 'Trade voided') {
                        location.href = $('#urlVoidUrl').val();
                    }
                }
                else {
                    location.reload(true);
                }

                if (doWhat == 'Activate Existing') {
                    popActivate.Hide();
                }
                $('#PopDiv1').css('color', 'green');
                $("#PopDiv1").fadeIn();
                $("#PopDiv2").html(result);
                $("#PopDiv1").fadeOut(8000);
            }
            else {
                $('#PopDiv1').css('color', 'red');
                $("#PopDiv1").fadeIn();
                $("#PopDiv2").html(result);
                $("#PopDiv1").fadeOut(8000);
            }
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html(xhr.responseText);
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

//#### NOT IN USE
function ReloadReferenceNo() {
    var _url = $('#urlReloadReferenceNo').val()
    $.ajax({
        url: _url,
        type: "POST",
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (results) {
            cboSFM_Re_No.SetValue(results);
        },
        error: function (xhr) {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html(xhr.responseText);
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

//######### Print Data #########//
function PrintData() {
    //************ Hide unnecessary item before print ************//

    $('#inner-header').hide();
    $('#cssmenu').hide();
    $('#mnu').hide();
    $('#divButtons').hide();
    $('#btnSubmit').hide();
    $('#btnSaveOrigin').hide();
    $('#btnCancelOrigin').hide();
    $('#btnPostIncome').hide();
    $('#spStrategySubType').text(StrategySubType.GetText());
    $('#spStrategySubType').css('visibility', 'visible');
    $('#spStrategySubType').addClass("dxeTextBoxSys dxeTextBox_Moderno");
    StrategySubType.SetVisible(false);
    $('#spStrategyType').text(StrategyType.GetText());
    $('#spStrategyType').css('visibility', 'visible');
    $('#spStrategyType').addClass("dxeTextBoxSys dxeTextBox_Moderno");
    StrategyType.SetVisible(false);
    window.print();
    //********** Show all item after print **********//
    $('#inner-header').show();
    $('#cssmenu').show();
    $('#mnu').show();
    $('#divButtons').show();
    $('#btnSubmit').show();
    $('#btnSaveOrigin').show();
    $('#btnCancelOrigin').show();
    $('#btnPostIncome').show();
    $('#spStrategySubType').text('');
    $('#spStrategySubType').css('visibility', 'hidden');
    $('#spStrategySubType').removeClass("dxeTextBoxSys dxeTextBox_Moderno");
    StrategySubType.SetVisible(true);
    $('#spStrategyType').text('');
    $('#spStrategyType').css('visibility', 'hidden');
    $('#spStrategyType').removeClass("dxeTextBoxSys dxeTextBox_Moderno");
    StrategyType.SetVisible(true);
    e.preventDefault();
}
//######### Calculate Rate #########//

function CalculateRate() {
    var amount = Currency1_Amount.GetText().replace(/,/g, '');
    var fxRate = FxRate.GetText().replace(/,/g, '');

    var total = parseFloat(amount / fxRate).toFixed(2);

    Currency2Amount.SetText(total != 'Infinity' ? total : '0');
}

function UpdateFxRate() {
    var currency = Currency.GetValue();
    var tradeDate = TradeDate.GetText();
   
    $.ajax({
        type: 'POST',
        url: 'Trade/GetOriginationFxRate',
        data: { currencyID: currency, pDate: tradeDate },
        success: function (result) {
            if (result.message) alert(result.message);
            if (result.fxRate > 0) {
                FxRate.SetText(String(result.fxRate));
                CalculateRate();
            }
        },
        error: function () { alert('Error retrieving FX rate'); }
    });
}
//************ Get InActive Data and set it to ComboBox
function GetInActiveCP(s, e) {
    
    var cpid = s.GetValue();
    var cptext = s.GetText();
    var url = $('#urlGetInActiveCounterParty').val();
    
    if (cpid == cptext) {
        s.SetText('');
        s.SetValue(null);
    }

    if (cpid == "C6") {
        s.SetText("TGM");
    }
}
function ArrayFillter(a1, a2) {
    var array = [];
    var count = 1;
    if (a1.length == 0)
        return a1;
    $.each(a1, function () {
        if (a2.indexOf(this) == -1) {
            array.push(this);
        }
        if (a1.length == count) {
            return array;
        }
        count++;
    });
}

//function TradeFlowChange(s, e) {
//    debugger;
//    $('#goodsDetails').empty();
//    $('#goodsDetails').append("<thead><tr><th>Trade_Flow_No</th><th>Vessel</th><th>Goods</th><th>Quantity</th></tr></thead>");
//    var tfNow = TradeFlow.GetValue();
//    //TradeFlow.SetValue(null);
//    var _trade_flows_entered = tfNow == null ? [] : tfNow;
//    var added = _trade_flows_entered.filter(function (obj) { return _trade_flows.indexOf(obj) == -1; }).sort();
//    var removed = _trade_flows.filter(function (obj) { return _trade_flows_entered.indexOf(obj) == -1; }).sort();
//    _trade_flows_new = _trade_flows;
//    notremovedTradeFlow = "";
//    nogoodsTradeFlow = "";
//    var ind = 1;
//    $.each(removed, function () {
//        CheckInvoiceTradeFlow(String(this), removed.length == ind, added);
//        ind++;
//    });
//    if (removed.length == 0) {
//        var indadd = 1;
//        $.each(added, function () {
//            CheckTradeFlowShowGoods(String(this), added.length == indadd);
//            indadd++;
//        });
//        if (added.length == 0) {
//            setGLValue(TradeFlow, _trade_flows_new.sort(), btnSaveOrigin);
//            _trade_flows = _trade_flows_new.sort;
//        }

//    }
//}

function TradeFlowChange(s, e) {
    debugger;
    //var selectedValues = e.value;
    //document.getElementById('TradeFlow').value = selectedValues.join(',');
    // Prepare goods table
    $("#goodsDetails").html(`
        <thead>
            <tr>
                <th>Trade Flow No</th>
                <th>Vessel</th>
                <th>Goods</th>
                <th>Quantity</th>
            </tr>
        </thead>
        <tbody id="goodsDetailsBody">
        </tbody>
    `);

    // Show modal popup
    $("#pcModalMode").addClass("show");

    var tfNow = $("#TradeFlow").dxTagBox("instance").option("value");

    var _trade_flows_entered = tfNow == null ? [] : tfNow;

    var added = _trade_flows_entered.filter(function (obj) {
        return _trade_flows.indexOf(obj) == -1;
    }).sort();

    var removed = _trade_flows.filter(function (obj) {
        return _trade_flows_entered.indexOf(obj) == -1;
    }).sort();

    _trade_flows_new = _trade_flows;

    notremovedTradeFlow = "";
    nogoodsTradeFlow = "";

    var ind = 1;

    $.each(removed, function () {

        CheckInvoiceTradeFlow(
            String(this),
            removed.length == ind,
            added
        );

        ind++;
    });

    if (removed.length == 0) {

        var indadd = 1;

        $.each(added, function () {

            CheckTradeFlowShowGoods(
                String(this),
                added.length == indadd
            );

            indadd++;
        });

        if (added.length == 0) {

            setGLValue(
                $("#TradeFlow").dxTagBox("instance"),
                _trade_flows_new.sort(),
                btnSaveOrigin
            );

            _trade_flows = _trade_flows_new.sort();
        }
    }
}

function CheckTradeFlowShowGoods(tradeFlowNo, last) {
    debugger;
    var strategyTypeValue = StrategyType.GetValue();
    var data = {
        tradeFlowNo: String(tradeFlowNo),
        strategyTypeValue: parseInt(strategyTypeValue),
    }
    $.ajax({
        method: 'POST',
        url: $('#urlGetTradeFlowGoods').val(),
        dataType: 'json',
        data: { tradeFlowNo: tradeFlowNo, strategyTypeValue: strategyTypeValue },//JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {

            if (result.length == 0) {
                nogoodsTradeFlow += (nogoodsTradeFlow == "" ? "" : ", ") + String(tradeFlowNo);
            }
            else {
                _trade_flows_new.push(tradeFlowNo);

                $.each(result, function (index, value) {
                    $('#goodsDetails').append("<tr><td>" + value.Trade_Flow_No + "</td><td>" + value.Vessel + "</td><td>" + value.Goods_Name + "</td><td>" + value.Quantity + "</td></tr>");
                    //if (value.Quantity == 0) {
                    //    $('#noGoods').append("<tr><td>" + value.Goods_Name + "</td></tr>")
                    //}
                    $('#noGoods').append('')
                        pcModalMode.Show();
                    
                });

            }
            if (last) {
                if (nogoodsTradeFlow != "")
                    alert("No Goods added for this Trade Flow No " + nogoodsTradeFlow);
                setGLValue(TradeFlow, _trade_flows_new.sort(), btnSaveOrigin);
                _trade_flows = _trade_flows_new.sort();
            }

        },
        error: function () {
            alert('error!');
        }
    });
}
function CheckInvoiceTradeFlow(tradeFlowNo, last, added) {
    var tradeFlows = TradeFlow.GetValue();
    var data = {
        tradeFlowNo: String(tradeFlowNo),
        SFM_Ref_No: $('#cboSFM_Re_No_I').val()
    }
    $.ajax({
        method: 'POST',
        url: $('#urlCheckFinalizationForTradeFlow').val(),
        dataType: 'json',
        data: JSON.stringify(data),
        contentType: "application/json; charset=utf-8",
        cache: false,
        success: function (result) {

            if (result > 0) {
                notremovedTradeFlow += (notremovedTradeFlow == "" ? "" : ", ") + String(tradeFlowNo);

            }
            else {
                var index = _trade_flows_new.indexOf(tradeFlowNo);
                if (index > -1) {
                    _trade_flows_new.splice(index, 1);
                }
            }
            if (last) {
                if (notremovedTradeFlow != "")
                    alert("Invoice already finalized for tradflow No " + notremovedTradeFlow);
                var indadd = 1;
                $.each(added, function () {
                    CheckTradeFlowShowGoods(String(this), added.length, indadd);
                    indadd++;
                });
                if (added.length == 0) {
                    if (nogoodsTradeFlow != "")
                        alert("No Goods added for this Trade Flow No " + nogoodsTradeFlow);
                    setGLValue(TradeFlow, _trade_flows_new.sort(), btnSaveOrigin);
                    _trade_flows = _trade_flows_new.sort();
                }
            }
        },
        error: function () {
            alert('error!');
        }
    });
}

function FinalSet() {
    while (queue.length > 2) {
        queue.shift();
    }
    var i = queue.shift();
    i.Btn.SetEnabled(false);
    i.GL.SetValue(i.Value);

    setTimeout(function () {

        if (queue.length == 0) {
            i.Btn.SetEnabled(true);
            running = false;
        }
        else
            FinalSet();
    }, 2000);
}
function RunValue() {
    if (running != true) {
        running = true;
        FinalSet();
    }
}
function setGLValue(gl, value, btn) {
    queue.push({ GL: gl, Value: null, Btn: btn });
    RunValue();
    queue.push({ GL: gl, Value: value, Btn: btn });
    RunValue();

}
function isEqual(a, b) {
    if (a.length != b.length)
        return false;
    else {
        a = a.sort();
        b = b.sort();
        // comapring each element of array 
        for (var i = 0; i < a.length; i++)
            if (a[i] != b[i])
                return false;
        return true;
    }
}