
function getQueryStringValue(key) {
    return unescape(window.location.search.replace(new RegExp("^(?:.*[&\\?]" + escape(key).replace(/[\.\+\*]/g, "\\$&") + "(?:\\=([^&]*))?)?.*$", "i"), "$1"));
}
//######### Function to Search Trade Data  #########//

function GetTradeData(RefNo, flag) {
    var canUpdate = enableControl.GetText();
    var url = $('#urlGetOrigination').val() + "?SFMRefNo=" + RefNo;
    $.ajax({
        type: "POST",
        contentType: 'application/json',
        url: url,
        data: null,
        cache: 'false',
        success: function (data) {
            SFM_Ref_Number.SetValue(data.SFM_Ref_No);
            $('#spSFM_Ref_No').text(data.SFM_Ref_No != null ? data.SFM_Ref_No : '');
            $('#spParent_SFM_Ref_No').text(data.Parent_SFM_Ref_No != null ? data.Parent_SFM_Ref_No : '');
            $("#spParent_SFM_Ref_No").attr("href", data.Parent_SFM_Ref_No != null ? 'Trade?SFMRefNo=' + data.urlParentRef : ''); // Make parent number as link
            if (data.CanAccessParent == false) {
                $('#spParent_SFM_Ref_No').css("cursor", "not-allowed");
                $("#spParent_SFM_Ref_No").attr("disabled", true);
                $("#spParent_SFM_Ref_No").removeAttr("href");
            }
            else {
                $('#spParent_SFM_Ref_No').css("cursor", "pointer");
                $("#spParent_SFM_Ref_No").attr("disabled", false);
            }
            //$('#spParent_SFM_Ref_No').text(data.Parent_SFM_Ref_No != null ? data.Parent_SFM_Ref_No : '');
            $('#spTrade_Status_Name').text(data.Trade_Status_Name != null ? data.Trade_Status_Name : '');
            $('#spCreated_By').text(data.Created_By != null ? data.Created_By : '');
            $('#spCreated_On').text(data.Created_On != null ? data.Created_On : '');
            $('#hdnGlobalRef').val(data.SFM_Ref_No);
            //TradeDate.Focus();
            TradeDate.SetText(data.Trade_Date);
            //FxRate.Focus();
            FxRate.SetValue(data.Fx_Rate);
            //CPId.Focus();
            //CPId.SetValue(data.CP_Id);
            $('#TransactionalCPID').val(data.CP_Id);
            
            //Currency2Amount.Focus();
            Currency2Amount.SetValue(data.Fx_Rate != undefined ? data.Currency1_Amount / data.Fx_Rate : 0); // Getting value by dividing Currency amount to FxRate
            //RiskIssuerID.Focus();
            Bloomberg_Trade.SetText(data.Bloomberg_Trade);
            RiskIssuerID.SetValue(data.Risk_Issuer_Id);
            $('#RiskISId').val(data.Risk_Issuer_Id);
            //RiskCountry.Focus();
            RiskCountry.SetValue(data.Country_Id);
            //TransactionType_Id.Focus();
            TransactionType_Id.SetValue(data.Transaction_Type_Id);
            CPId.PerformCallback();

            //Estimated_Execution_Month.Focus();
            //Estimated_Execution_Month.SetValue(data.Estimated_Execution_Month);
            //Currency.Focus();
            Currency.SetValue(data.Currency1_Id);
            //InstrumentType.Focus();
            InstrumentType.SetValue(data.InstrumentType_Id);
            TradeFlow.SetEnabled(true);

            var tradeflownos = [];
            if (data.Trade_Flow_No != null && data.Trade_Flow_No != "") {
                //TradeFlow.SetValue(data.Trade_Flow_No);
                tradeflownos = data.Trade_Flow_No.split(',');
            }
            setGLValue(TradeFlow, tradeflownos.sort(), btnSaveOrigin);
            _trade_flows = tradeflownos.sort();
            $('#TradeFID').val(data.Trade_Flow_No);
            //StrategyType.Focus();
            StrategyType.SetValue(data.Strategy_Id);
            //StrategySubType.Focus();
            StrategySubType.PerformCallback();                      //Perform Callback for bind sub value.
            StrategySubType.SetValue(data.StrategySub_Id);
            $('#Strategy_SubTypeID').val(data.StrategySub_Id);
            //Estimated_Execution_Year.Focus();
            //Estimated_Execution_Year.SetValue(data.Estimated_Execution_Year);
            //Currency1_Amount.Focus();
            Currency1_Amount.SetValue(data.Currency1_Amount);
            //Tenure_Days.Focus();
            Tenure_Days.SetText(data.Tenure_Days);
            Comments.SetText(data.Comment);

            //******** Disable/ Enable Buttons ********//
            btnOPSSignOffGlobal.SetEnabled(data.CanSignOff);
            btnCopyGlobal.SetEnabled(data.CanCopy);
            btnCloneGlobal.SetEnabled(data.CanClone);
            btnVoidGlobal.SetEnabled(data.CanVoid);
            btnActivateAccount.SetEnabled(data.CanActivate);
            btnSaveOrigin.SetEnabled(data.CanOriginationEdit);
            btnFinalizeAccount.SetEnabled(data.CanFinalize);

            btnPostIncome.SetEnabled(data.CanAccountAdd);
            // btnPostCost.SetEnabled(data.CanAccountAdd);
            //btnAddNewIncome.SetVisible(data.CanAccountAdd);
            //btnAddNewCost.SetVisible(data.CanAccountAdd);

            //make field disable based on Access control
            if (canUpdate == "False") {
                TradeDate.SetEnabled(false);
                RiskCountry.SetEnabled(false);
                RiskIssuerID.SetEnabled(false);
                Comments.SetEnabled(false);
                Currency1_Amount.SetEnabled(false);
                Currency2Amount.SetEnabled(false);
                FxRate.SetEnabled(false);
                Currency.SetEnabled(false);
                InstrumentType.SetEnabled(false);
                Bloomberg_Trade.SetEnabled(false);
                StrategyType.SetEnabled(false);
                StrategySubType.SetEnabled(false);
                Tenure_Days.SetEnabled(false);
                TransactionType_Id.SetEnabled(false);
                CPId.SetEnabled(false);
                TradeFlow.SetEnabled(false);
            }
            //btnAddIncomeBalance.SetEnabled(data.CanAccountAdd);
            //btnAddCostBalance.SetEnabled(data.CanAccountAdd);

            //********* Disable/Enable Document, Distribution & Shipment buttons ******//
            btnAddDoc.SetEnabled(data.CanDocumentAdd);
            $('#canAddDistribution').val(data.CanDistributionAdd);
            $('#canAddShipment').val(data.CanBLAdd);
            $('#canAddString').val(data.CanStringAdd);

            if (data.CanSignOff == false)
                $('#btnOPSSignOffGlobal').css("cursor", "not-allowed");
            else
                $('#btnOPSSignOffGlobal').css("cursor", "pointer");

            //if (data.CanOriginationEdit == false)
            //    $('#btnSaveOrigin').css("cursor", "not-allowed");
            //else
            //    $('#btnSaveOrigin').css("cursor", "pointer");
            if (data.CanCopy == false)
                $('#btnCopyGlobal').css("cursor", "not-allowed");
            else
                $('#btnCopyGlobal').css("cursor", "pointer");
            if (data.CanClone == false)
                $('#btnCloneGlobal').css("cursor", "not-allowed");
            else
                $('#btnCloneGlobal').css("cursor", "pointer");
            if (data.CanVoid == false)
                $('#btnVoidGlobal').css("cursor", "not-allowed");
            else
                $('#btnVoidGlobal').css("cursor", "pointer");
            if (data.CanActivate == false)
                $('#btnActivateAccount').css("cursor", "not-allowed");
            else
                $('#btnActivateAccount').css("cursor", "pointer");

            if (data.CanFinalize == false)
                $('#btnFinalizeAccount').css("cursor", "not-allowed");
            else
                $('#btnFinalizeAccount').css("cursor", "pointer");

            //if (data.CanAccountAdd == false) {
            //    $('#btnAddNewIncome').css("cursor", "not-allowed");
            //    $('#btnAddNewCost').css("cursor", "not-allowed");

            //    $('#btnAddIncomeBalance').css("cursor", "not-allowed");
            //    $('#btnAddCostBalance').css("cursor", "not-allowed");

            //    $('#btnPostIncome').css("cursor", "not-allowed");
            //    $('#btnReversePost').css("cursor", "not-allowed");
            //    //   $('#btnPostCost').css("cursor", "not-allowed");
            //}
            //else {
            //    $('#btnAddNewIncome').css("cursor", "pointer");
            //    $('#btnAddNewCost').css("cursor", "pointer");

            //    $('#btnAddIncomeBalance').css("cursor", "pointer");
            //    $('#btnAddCostBalance').css("cursor", "pointer");

            //    $('#btnPostIncome').css("cursor", "pointer");
            //    $('#btnReversePost').css("cursor", "pointer");
            //    // $('#btnPostCost').css("cursor", "pointer");
            //}
            if (data.CanDocumentAdd == false) {
                $('#btnAddDoc').css("cursor", "not-allowed");
            }
            else
                $('#btnAddDoc').css("cursor", "pointer");


            //********** If Click on Search and Data not found  ***********//
            if (flag == "search") {
                if (data.SFM_Ref_No == null) {
                    $('#spSFMPartialError').text("Sorry, No Record found with Ref No: " + RefNo);
                    $('#spSFM_Ref_No').text("");
                    $('#spParent_SFM_Ref_No').text("");
                    $('#spTrade_Status_Name').text("");
                    $('#spCreated_By').text("");
                    $('#spCreated_On').text("");

                    // Clear Origination 
                    FxRate.SetValue('1');
                    TradeDate.SetValue(null);
                    CPId.SetValue('');
                    Currency2Amount.SetValue('');
                    RiskIssuerID.SetValue('');
                    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('');
                    setGLValue(TradeFlow, [], btnSaveOrigin);
                    _trade_flows = [];
                    //TradeFlow.SetEnabled(true);
                    StrategyType.SetValue('');
                    StrategySubType.SetValue('');
                    //Estimated_Execution_Year.SetValue(new Date().getFullYear()); //Get Year By default
                    Currency1_Amount.SetValue('0');
                    Tenure_Days.SetText('270');
                    //Estimated_Execution_PNL.SetValue('');
                    Comments.SetText('');
                }
                else {
                    $('#spSFMPartialError').text("");
                }
            }

            //********* IF Loading for New Entry *********//
            if (RefNo == null) {
                FxRate.SetText('1');
                TradeDate.SetValue(null);
                CPId.SetValue('');
                Currency2Amount.SetValue('');
                RiskIssuerID.SetValue('');
                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('');
                setGLValue(TradeFlow, [], btnSaveOrigin);
                _trade_flows = [];
                //TradeFlow.SetEnabled(true);
                StrategyType.SetValue('');
                StrategySubType.SetValue('');
                //Estimated_Execution_Year.SetValue(new Date().getFullYear()); //Get Year By default
                Currency1_Amount.SetValue('0');
                Tenure_Days.SetText('270');
                //Estimated_Execution_PNL.SetValue('');
                Comments.SetText('');
            }
        },
        error: function () {
            $('#PopDiv1').css('color', 'red');
            $("#PopDiv1").fadeIn();
            $("#PopDiv2").html('Error finding data!');
            $("#PopDiv1").fadeOut(8000);
        }
    });
}

//######### ON PAGE LOAD IF QUERY STRING IS NOT NULL #########//
$(window).load(function () {
    var Ref = getQueryStringValue("SFMRefNo");
    SFM_Ref_Number.SetValue(Ref);
    GetTradeData(SFM_Ref_Number.GetValue(), '');
    $('#TradeFlow_I').attr('readonly', true); 
    //######### ON CLICK OF SEARCH BUTTON #########//
    //$("#btnSubmit").click(function () {
    //    FilterEntity.SetValue("");
    //    TransactionDateFilter.SetText("Select");

    //    var RefNo = SFM_Ref_Number.GetValue();
    //    if (RefNo == null || RefNo == "Enter SFM Ref No.") {
    //        $('#spSFMPartialError').text("Please Select Reference number");
    //        return false;
    //    }
    //    else {
    //        GetTradeData(RefNo, 'search');
    //        RearrangeSectionOnSearch();
    //    }
    //});
});
function TradeSFMChange() {
    FilterEntity.SetValue("");
    TransactionDateFilter.SetText("Select");

    var RefNo = SFM_Ref_Number.GetValue();
    if (RefNo == null || RefNo == "Enter SFM Ref No.") {
        $('#spSFMPartialError').text("Please Select Reference number");
        return false;
    }
    else {
        GetTradeData(RefNo, 'search');
        RearrangeSectionOnSearch();
    }
}
/* REARRANGE ALL SECTION AND SHOW ONLY ORIGINATION SECTION ON SEARCH BUTTON CLICK*/
function RearrangeSectionOnSearch() {
    //### Reset all flag
    var flag1 = 1;
    var flag2 = 0;
    var flag3 = 0;
    var flag4 = 0;
    var flag5 = 0;
    //### Collapse all Section and expand only Origination section
    $('.distribution-child').slideUp();
    $('.shipment-child').slideUp();
    $('.accounting-child').slideUp();
    $('.documentation-child').slideUp();
    $('.origination-child').slideDown();

    //### Change Icon of each section to '+' and Origination to '-'
    $("#distribution").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
    $("#imgdistribution").attr("src", "Content/Images/plus.png");

    $("#shipment").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
    $("#imgshipment").attr("src", "Content/Images/plus.png");

    $("#accounting").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
    $("#imgaccounting").attr("src", "Content/Images/plus.png");

    $("#documentation").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
    $("#imgdocumentation").attr("src", "Content/Images/plus.png");

    $("#origination").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
    $("#imgorigination").attr("src", "Content/Images/minus.png");

    //### Set Toggle icon of each section
    $("#origination").click(function () {
        flag1 = flag1 == 0 ? 1 : 0;

        if (flag1 == 0) {
            $("#origination").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
            $("#imgorigination").attr("src", "Content/Images/plus.png");

        }
        else {
            $("#origination").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
            $("#imgorigination").attr("src", "Content/Images/minus.png");
        }

    });
    $("#distribution").click(function () {
        flag2 = flag2 == 0 ? 1 : 0;

        if (flag2 == 0) {
            $("#distribution").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
            $("#imgdistribution").attr("src", "Content/Images/plus.png");

        }
        else {
            $("#distribution").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
            $("#imgdistribution").attr("src", "Content/Images/minus.png");
        }
    });
    $("#shipment").click(function () {
        flag3 = flag3 == 0 ? 1 : 0;

        if (flag3 == 0) {
            $("#shipment").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
            $("#imgshipment").attr("src", "Content/Images/plus.png");
        }
        else {
            $("#shipment").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
            $("#imgshipment").attr("src", "Content/Images/minus.png");
        }
    });

    $("#accounting").click(function () {
        flag4 = flag4 == 0 ? 1 : 0;
        if (flag4 == 0) {
            $("#accounting").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
            $("#imgaccounting").attr("src", "Content/Images/plus.png");
        }
        else {
            $("#accounting").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
            $("#imgaccounting").attr("src", "Content/Images/minus.png");
        }
    });
    $("#documentation").click(function () {
        flag5 = flag5 == 0 ? 1 : 0;

        if (flag5 == 0) {
            $("#documentation").parent().css("border-color", "#fff").find("legend").css("background-color", "#0a67a8").css("color", "#fff");
            $("#imgdocumentation").attr("src", "Content/Images/plus.png");
        }
        else {
            $("#documentation").parent().css("border-color", "#0072C6").find("legend").css("background-color", "#DEEAFF").css("color", "#111");
            $("#imgdocumentation").attr("src", "Content/Images/minus.png");
        }
    });
}