
$(document).ready(function () {
    loadPatientHistory();
    loadFamilyHistory();
});

function MaxMin_Condition(evt, id, min, maxval, errormessage) {
    debugger;
    var MaxLength = maxval.length;
    var ErrorMessage = errormessage;
    var Message = "";
    if (ErrorMessage != "") {
        Message = errormessage;
    }
    else {
        Message = "Min Value " + min + " Max value " + maxval;
    }

    var value = $("#" + id).val();
    var preg_check = /[^0-9.]/ig;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode >= 65 && charCode <= 90) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('Numerics only allowed');
        $("#" + id).val(value.replace(/[^0-9.]/ig, ''));
        $("#" + id).focus();
    }

    else if (preg_check.test(value)) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('Numerics only allowed');
        $("#" + id).val(value.replace(/[^0-9.]/ig, ''));
        $("#" + id).focus();
    }
    else {
        if ($("#" + id).val().indexOf('.') > -1) {
            var numbers = $("#" + id).val().split('.');
            var preDecimal = numbers[0];
            var postDecimal = numbers[1];

            if (preDecimal.length > MaxLength || postDecimal.length > 2) {
                if (preDecimal.length > MaxLength) {
                    $('#P' + id).show();
                    $('#P' + id).fadeOut(8000);
                    $('#P' + id).html('Max value ' + maxval);
                    var newval = preDecimal.substring(0, maxval);
                    if ($.trim(postDecimal) == "" || $.trim(postDecimal) == null) {
                        postDecimal = "00";
                        newval = newval + '.' + postDecimal;
                    }
                    else {
                        newval = newval + '.' + postDecimal;
                    }
                    console.log(newval);
                    $("#" + id).val(newval);
                }
                else {
                    $('#P' + id).show();
                    $('#P' + id).fadeOut(8000);
                    $('#P' + id).html('2 digits after decimal.');
                    var newval = postDecimal.substring(0, 2);
                    console.log(newval);
                    if ($.trim(preDecimal) == "" || $.trim(preDecimal) == null) {
                        preDecimal = "0";
                        newval = preDecimal + '.' + newval;
                    }
                    else {
                        newval = preDecimal + '.' + newval;
                    }
                    console.log(newval);
                    $("#" + id).val(newval);
                }
                $("#" + id).focus();
            }
        }
        else {
            var txtval = $("#" + id).val();
            if (txtval.length > MaxLength) {
                $('#P' + id).show();
                $('#P' + id).fadeOut(8000);
                $('#P' + id).html('Max value ' + maxval);
                var newval = txtval.substring(0, MaxLength);

                $("#" + id).val(newval);
                $("#" + id).focus();
            }
        }
    }

    if (parseInt(value) < parseInt(min) || parseInt(value) > parseInt(maxval)) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html(Message);
        $("#" + id).val("");
    }
}

function Numericcomotwo_wot(evt, id) {
    debugger;
    var value = $("#" + id).val();
    var preg_check = /[^0-9.]/ig;
    var charCode = (evt.which) ? evt.which : event.keyCode
    if (charCode >= 65 && charCode <= 90) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('Numerics only allowed');
        $("#" + id).val(value.replace(/[^0-9.]/ig, ''));
        $("#" + id).focus();
    }

    else if (preg_check.test(value)) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('Numerics only allowed');
        $("#" + id).val(value.replace(/[^0-9.]/ig, ''));
        $("#" + id).focus();
    }
    else {
        if ($("#" + id).val().indexOf('.') > -1) {
            var numbers = $("#" + id).val().split('.');
            var preDecimal = numbers[0];
            var postDecimal = numbers[1];

            if (preDecimal.length > 3 || postDecimal.length > 2) {
                if (preDecimal.length > 3) {
                    $('#P' + id).show();
                    $('#P' + id).fadeOut(8000);
                    $('#P' + id).html('Max value 999.99.');
                    var newval = preDecimal.substring(0, 3);
                    if ($.trim(postDecimal) == "" || $.trim(postDecimal) == null) {
                        postDecimal = "00";
                        newval = newval + '.' + postDecimal;
                    }
                    else {
                        newval = newval + '.' + postDecimal;
                    }
                    console.log(newval);
                    $("#" + id).val(newval);
                }
                else {
                    $('#P' + id).show();
                    $('#P' + id).fadeOut(8000);
                    $('#P' + id).html('2 digits after decimal.');
                    var newval = postDecimal.substring(0, 2);
                    console.log(newval);
                    if ($.trim(preDecimal) == "" || $.trim(preDecimal) == null) {
                        preDecimal = "0";
                        newval = preDecimal + '.' + newval;
                    }
                    else {
                        newval = preDecimal + '.' + newval;
                    }
                    console.log(newval);
                    $("#" + id).val(newval);
                }
                $("#" + id).focus();
            }
        }
        else {
            var txtval = $("#" + id).val();
            if (txtval.length > 3) {
                $('#P' + id).show();
                $('#P' + id).fadeOut(8000);
                $('#P' + id).html('Max value 999.99.');
                var newval = txtval.substring(0, 3);

                $("#" + id).val(newval);
                $("#" + id).focus();
            }
        }
    }
}

function MaxLength_Validation(evt, id, length, errormessage) {
    debugger;
    var value = $("#" + id).val();

    var ErrorMessage = errormessage;
    var Message = "";
    if (ErrorMessage != "") {
        Message = errormessage;
    }
    else {
        Message = "Do not Enter Next Values..Max Value is " + length;
    }

    if (length != "") {
        var ColLength = length;
        if (value.length >= ColLength) {
            $('#P' + id).show();
            $('#P' + id).fadeOut(8000);
            $('#P' + id).html(Message);
        }
    }
}

function loadPatientHistory() {
    var Patientdata = {
        Dml_Indicator: "US",
        patient_id: $("#IPPatient_Id").val(),
        ip_visit_report_id: $("#IPVisitReport_Id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/PatientHistory_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Patientdata),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                $.each(data1, function (i, emp) {
                    $('#txtComplaints').val(emp.ip_complaints),
                        $('#txtIllness').val(emp.ip_history_of_present_illness),
                        $('#txtFRelevence').val(emp.ip_past_history_of_relevence_family),
                        $('#txtPRelevence').val(emp.ip_past_history_of_relevence_personal),
                        $('#txtmorbidities').val(emp.ip_co_morbidities),
                        $('#txtExamination').val(emp.ip_clinical_examination),
                        $('#txtdiagnosis').val(emp.ip_clinical_diagnosis),
                        $('#txtDrugHistory').val(emp.ip_drug_history_notes),
                        $('#txtTreatment').val(emp.treatment_history_notes),
                        $('#txtSurgery').val(emp.surgery_history_notes),
                        $('#txtPersonal').val(emp.personal_history)
                    if (emp.patient_alcohol_consumption != "" || emp.patient_alcohol_consumption != null) {
                        $('#ChkAlcohol').val(emp.patient_alcohol_consumption);
                        $('a[data-toggle=ChkAlcohol][data-title="' + emp.patient_alcohol_consumption + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkAlcohol][data-title="' + emp.patient_alcohol_consumption + '"]').addClass('active');
                        $("#ChkAlcohol").change();
                    }
                    if (emp.patient_smoking_habit != "" || emp.patient_smoking_habit != null) {
                        $('#ChkSmoking').val(emp.patient_smoking_habit);
                        $('a[data-toggle=ChkSmoking][data-title="' + emp.patient_smoking_habit + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkSmoking][data-title="' + emp.patient_smoking_habit + '"]').addClass('active');
                        $("#ChkSmoking").change();
                    }
                    if (emp.patient_activity_level != "" || emp.patient_activity_level != null) {
                        $('#ChkActivity').val(emp.patient_alcohol_consumption);
                        $('a[data-toggle=ChkActivity][data-title="' + emp.patient_activity_level + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkActivity][data-title="' + emp.patient_activity_level + '"]').addClass('active');
                        $("#ChkActivity").change();
                    }
                    if (emp.patient_food_perference != "" || emp.patient_food_perference != null) {
                        $('#ChkFood').val(emp.patient_alcohol_consumption);
                        $('a[data-toggle=ChkFood][data-title="' + emp.patient_food_perference + '"]').removeClass('not-active');
                        $('a[data-toggle=ChkFood][data-title="' + emp.patient_food_perference + '"]').addClass('active');
                        $("#ChkFood").change();
                    }
                    $('#HOperationID').val(emp.ip_surgery_type),
                        $('#HBriefCount').val(emp.BriefCount),
                        $("#ChkAlcohol").val(emp.patient_alcohol_consumption),
                        $("#txtRadiation").val(emp.ip_radiation),
                        $("#txtChemotherapy").val(emp.ip_chemotherapy)
                    $('#HdIPtype').val(emp.type_of_admition);

                });
                if ($('#HdIPtype').val() == 2) {
                    LoadIntraOperative();
                }
                
            }
            else {
                console.log(data2);
            }

        },
        error: function (data) {
            toastr.warning('Some Issue');
        }
    });
}


//BreifHistory Start //

function LoadIntraOperative() {

    var objInvestigationHis = [

        {
            Dml_Indicator: "OPC",
            screenid: "3",
            ip_visit_report_id: $("#IPVisitReport_Id").val()
        },
    ]


    objInvestigationHis = JSON.stringify({ 'objInvestigationHis': objInvestigationHis });

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/InvestigationHis_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: objInvestigationHis,
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;

                    var ShowHideCount = 0;
                    var j = 0, DySectionCount = 0, DyRowCount = 0;
                    var Radio = 0, Rcount = 0, r = 0;
                    var RadioID = "", SubParaID = "", ParameterID = "";

                    if (data.Table.length > 0) {
                        // Dynamic Section //
                        tr = $('<div class="row ml-15 mr-15">');
                        for (var DS = 0; DS < data.Table.length; DS++) {
                            DySectionCount++;
                            tr.append('<div class="section-box"><div class="section-heading"><div class="row"> <div class="col-sm-12"> <p>' + data.Table[DS].Parameters + '</p></div></div><div id="' + DySectionCount + '-section" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="headingOne"><div class="panel-body"><div id="" class="' + DySectionCount + '" role="tabpanel" aria-labelledby="headingOne">');
                            tr.append('</div></div></div></div>');
                        }
                        tr.append("</div>");
                        $('#DynamicSection').html(tr);
                    }

                    debugger;
                    if (data.Table1.length > 0) {
                        for (var p = 0; p < data.Table.length; p++) {
                            DyRowCount++;
                            SubParaID = "";
                            tr = $('<div class="panel-body">');
                            tr = $('<div class="row">');

                            for (var s = 0; s < data.Table1.length; s++) {

                                if (data.Table[p].Parameters_ID == data.Table1[s].Parameters_ID) {

                                    // Record Count Start //

                                    if (SubParaID != data.Table1[s].SubParameter_ID) {
                                        j++
                                    }
                                    else { j = j; }

                                    // RowCount End //

                                    //Dynamic Text Box //
                                    //Dynamic Text Box //
                                    if (data.Table1[s].Column_Type == "T") {

                                        var valonkeyup = "";

                                        if (parseInt(data.Table1[s].Field_Value) == 1) {
                                            if (data.Table1[s].Max_Value != "" || data.Table1[s].Min_Value != "") {
                                                var valonkeyup = "return MaxMin_Condition(event, this.id,'" + data.Table1[s].Min_Value + "','" + data.Table1[s].Max_Value + "','" + data.Table1[s].Error_Message + "')";
                                            }
                                            else {
                                                var valonkeyup = "return Numericcomotwo_wot(event, this.id)";
                                            }
                                        }
                                        else if (parseInt(data.Table1[s].Field_Value) == 2) {
                                            var valonkeyup = "return MaxLength_Validation(event, this.id,'" + data.Table1[s].Field_Length + "','" + data.Table1[s].Error_Message + "')";
                                        }
                                        else {
                                            var valonkeyup = "";
                                        }
                                        tr.append('<div class="col-xs-12 col-md-6" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group"><label>' + data.Table1[s].SubParameter + '</label><input type="text" onblur="' + valonkeyup + '" maxlength="' + data.Table1[s].Field_Length + '"  data-placement="bottom" title="' + data.Table1[s].tooltip + '" data-toggle="tooltip" class="form-control textbxwidth disable" id="GeneralInformation_' + (j) + '"><span class="unitmute unitstyle" >' + data.Table1[s].unit_values + '</span></div><p id="PGeneralInformation_' + (j) + '" style="color:red;"></p><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>');

                                    }

                                        // Dynamic Radio button //
                                    else if (data.Table1[s].Column_Type == "R") {
                                        RadioID = data.Table1[s].SubParameter_ID;
                                        if (SubParaID != data.Table1[s].SubParameter_ID) {
                                            var radio = '';

                                            radio = radio + '<div class="col-sm-6 col-xs-12"><label>' + data.Table1[s].SubParameter + '</label><div class="form-group">';

                                            for (var rb = 0; rb < data.Table1.length; rb++) {
                                                if (data.Table[p].Parameters_ID == data.Table1[rb].Parameters_ID) {
                                                    if (data.Table1[rb].Column_Type == "R" && RadioID == data.Table1[rb].SubParameter_ID) {

                                                        var condition = "";
                                                        if (data.Table1[s].CheckBox_condition_Value != "") {
                                                            if (data.Table1[s].CheckBox_condition_Value == data.Table1[rb].Column_Type_values) {
                                                                condition = "ShowHideFunction(this)";
                                                                ShowHideCount++;
                                                            }
                                                            else {
                                                                condition = "ShowHideRadio(this)";
                                                                ShowHideCount++;
                                                            }

                                                        }
                                                        else {
                                                            condition = " ";
                                                        }
                                                        radio = radio + '<label class="form-check-label"><input type="radio" style="margin-right: 4px;" data ="' + data.Table1[s].relational_column_id + '" id="optradio_' + data.Table1[s].ip_intra_operative_findings_id + '" class="form-check-input radio-inline" name="optradio' + (j) + '" value="' + data.Table1[rb].Column_Type_values + '" onclick="' + condition + '">' + data.Table1[rb].Column_Type_values + '</label>';
                                                        RadioID = data.Table1[rb].SubParameter_ID;
                                                    }
                                                }
                                            }
                                            radio = radio + '</div><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>';
                                            tr.append(radio);
                                        }
                                    }
                                        //Dynamic CheckBox //
                                    else if (data.Table1[s].Column_Type == "YN") {
                                        var condition = "";
                                        if (data.Table1[s].CheckBox_condition_Value != "") {
                                            condition = "ShowHideFunction(this)";
                                            ShowHideCount++;
                                        }
                                        else {
                                            condition = " ";
                                        }
                                        tr.append('<div class="col-xs-12 col-md-6 mt30" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group"><input type="checkbox" class="disable" style="margin-right:12px;" data ="' + data.Table1[s].relational_column_id + '" id="check_' + (j) + '" class="check_' + data.Table1[s].ip_intra_operative_findings_id + '" name="check_1" value="1" onclick="' + condition + '"><label for="check_1">' + data.Table1[s].SubParameter + '</label></div><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>');
                                        //<div class="col-md-3 m15"><input type="checkbox" id="CBIcterus" name="" value="1" /><label>Icterus</label></div>
                                    }
                                    else if (data.Table1[s].Column_Type == "DT") {
                                        tr.append('<div class="col-xs-12 col-md-6" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group"><label for="check_1">' + data.Table1[s].SubParameter + '</label><div class="input-group date"><div class="input-group-addon"><i class="fa fa-calendar"></i></div><input type="text" class="form-control Date disable" id="GeneralInformation_' + (j) + '"></div></div><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>');
                                    }
                                    else if (data.Table1[s].Column_Type == "TC") {

                                        var valonkeyup = "";

                                        if (parseInt(data.Table1[s].Field_Value) == 1) {
                                            if (data.Table1[s].Max_Value != "" || data.Table1[s].Min_Value != "") {
                                                var valonkeyup = "return MaxMin_Condition(event, this.id,'" + data.Table1[s].Min_Value + "','" + data.Table1[s].Max_Value + "','" + data.Table1[s].Error_Message + "')";
                                            }
                                            else {
                                                var valonkeyup = "return Numericcomotwo_wot(event, this.id)";
                                            }
                                        }
                                        else if (parseInt(data.Table1[s].Field_Value) == 2) {
                                            var valonkeyup = "return MaxLength_Validation(event, this.id,'" + data.Table1[s].Field_Length + "','" + data.Table1[s].Error_Message + "')";
                                        }
                                        else {
                                            var valonkeyup = "";
                                        }

                                        tr.append('<div class="col-xs-12 col-md-6" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group"><label for="check_1">' + data.Table1[s].SubParameter + '</label><input type="checkbox" style="float:right;" id="check_' + (j) + '" name="check_1" value="1"><input type="text" onkeyup="' + valonkeyup + '" maxlength="' + data.Table1[s].Field_Length + '"  data-placement="bottom" title="' + data.Table1[s].tooltip + '" data-toggle="tooltip" class="form-control disable" id="GeneralInformation_' + (j) + '"></div><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>');
                                    }
                                    else if (data.Table1[s].Column_Type == "TCT") {
                                        var valonkeyup = "";

                                        if (parseInt(data.Table1[s].Field_Value) == 1) {
                                            if (data.Table1[s].Max_Value != "" || data.Table1[s].Min_Value != "") {
                                                var valonkeyup = "return MaxMin_Condition(event, this.id,'" + data.Table1[s].Min_Value + "','" + data.Table1[s].Max_Value + "','" + data.Table1[s].Error_Message + "')";
                                            }
                                            else {
                                                var valonkeyup = "return Numericcomotwo_wot(event, this.id)";
                                            }
                                        }
                                        else if (parseInt(data.Table1[s].Field_Value) == 2) {
                                            var valonkeyup = "return MaxLength_Validation(event, this.id,'" + data.Table1[s].Field_Length + "','" + data.Table1[s].Error_Message + "')";
                                        }
                                        else {
                                            var valonkeyup = "";
                                        }
                                        tr.append('<div class="col-xs-12 col-md-6" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="col-xs-12 col-md-6"><div class="form-group"><label for="check_1">' + data.Table1[s].SubParameter + '</label><input type="checkbox" class="disable" style="float:right;" id="check_' + (j) + '" name="check_1" value="1"><input type="text" onkeyup="' + valonkeyup + '" maxlength="' + data.Table1[s].Field_Length + '" data-placement="bottom" title="' + data.Table1[s].tooltip + '" data-toggle="tooltip" class="form-control disable" id="GeneralInformation_' + (j) + '"></div><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div><div class="col-xs-12 col-md-6"><div class="form-group form-field-height"><label for="check_1">' + "Duration" + '</label><input type="text" class="form-control disable" id="Duration_' + (j) + '"></div></div></div>');
                                    }
                                        //Dynamic Textarea //
                                    else if (data.Table1[s].Column_Type == "TA") {

                                        var valonkeyup = "";

                                        if (parseInt(data.Table1[s].Field_Value) == 1) {
                                            if (data.Table1[s].Max_Value != "" || data.Table1[s].Min_Value != "") {
                                                var valonkeyup = "return MaxMin_Condition(event, this.id,'" + data.Table1[s].Min_Value + "','" + data.Table1[s].Max_Value + "','" + data.Table1[s].Error_Message + "')";
                                            }
                                            else {
                                                var valonkeyup = "return Numericcomotwo_wot(event, this.id)";
                                            }
                                        }
                                        else if (parseInt(data.Table1[s].Field_Value) == 2) {
                                            var valonkeyup = "return MaxLength_Validation(event, this.id,'" + data.Table1[s].Field_Length + "','" + data.Table1[s].Error_Message + "')";
                                        }
                                        else {
                                            var valonkeyup = "";
                                        }
                                        tr.append('<div class="col-xs-12 col-md-12" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group"><label>' + data.Table1[s].SubParameter + '</label><textarea onblur="' + valonkeyup + '" maxlength="' + data.Table1[s].Field_Length + '" rows="3"  data-placement="bottom" title="' + data.Table1[s].tooltip + '" data-toggle="tooltip"  class="textarea-height textbxwidth disable" id="GeneralInformation_' + (j) + '"></textarea></div><p id="PGeneralInformation_' + (j) + '" style="color:red;"></p><div><input type="hidden" id="HBSUB_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].SubParameter_ID + '><input type="hidden" id="HBPara_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].Parameters_ID + '><input type="hidden" id="HBMaster_Id_' + (j) + '" name="codecheck_1" value=' + data.Table1[s].ip_intra_operative_findings_id + '><input type="hidden" id="Record_Id_' + (j) + '" value=' + (j) + '></div></div>');

                                    }
                                    else {
                                        tr.append('');
                                    }

                                    SubParaID = data.Table1[s].SubParameter_ID;
                                }
                            }
                            tr.append("</div></div></div>");
                            $("." + DyRowCount).html(tr);
                            $('[data-toggle="tooltip"]').tooltip();
                        }
                        $('#HRecordCount').val(j);
                        $('.Date').datepicker({
                            autoclose: true,
                            todayHighlight: true,
                            format: "dd/mm/yyyy",
                            //endDate: new Date()
                        });

                        if ($("#IPDischarge_Id").val() == "2") {
                            $('.disable').prop('readonly', true);
                            $(':input[type="checkbox"]').prop('disabled', true);
                        }
                    }

                    if (parseInt($('#HBriefCount').val()) > 0) {
                        var objInvestigationHis = [

                            {
                                Dml_Indicator: "IFD",
                                patient_id: $("#IPPatient_Id").val(),
                                ip_visit_report_id: $("#IPVisitReport_Id").val(),
                                screenid: "3"
                            },
                        ]


                        objInvestigationHis = JSON.stringify({ 'objInvestigationHis': objInvestigationHis });

                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Ipmanagement/InvestigationHis_Ins_Upd_Sel',
                            contentType: 'application/json; charset=UTF-8',
                            data: objInvestigationHis,
                            success: function (data) {
                                var data2 = JSON.parse(data);
                                if (jQuery.isEmptyObject((data2.data))) {

                                }
                                else {
                                    if (data2.msg == "Success") {
                                        var data1 = data2.data;
                                        var count = $('#HRecordCount').val();
                                        debugger;
                                        if (data1.Table.length > 0) {
                                            if (count > 0) {

                                                for (var i = 0; i < data1.Table.length; i++) {
                                                    for (var j = 0; j < data1.Table.length; j++) {
                                                        if ($('#HBMaster_Id_' + (j + 1)).val() == data1.Table[i].master_intra_operative_findings_id) {

                                                            if (data1.Table[i].intra_operative_findings_check_values == 1) {
                                                                $('#check_' + (j + 1)).prop('checked', true);
                                                            }
                                                            else {
                                                                $('#check_' + (j + 1)).prop('checked', false);
                                                            }
                                                            $("input[name='optradio" + (j + 1) + "'][value='" + data1.Table[i].intra_operative_findings_values + "']").prop('checked', true);
                                                            $('#GeneralInformation_' + (j + 1)).val(data1.Table[i].intra_operative_findings_values);
                                                            $('#Duration_' + (j + 1)).val(data1.Table[i].ip_duration_value)
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else {
                                        console.log(data);
                                    } 
                                }
                                if (ShowHideCount > 0) {
                                    LoadCheckHideFunction();
                                }
                            }
                        });
                    }
                }
                else {
                    console.log(data);
                }
            }

        },
        error: function (data) {
            toastr.warning('Some Issue...');
        }
    });

};

function LoadCheckHideFunction() {

    var objInvestigationHis = [];

    objInvestigationHis.push({
        Dml_Indicator: 'CHIDE',
        screenid: "3",
        ip_visit_report_id: $("#IPVisitReport_Id").val()
    })

    objInvestigationHis = JSON.stringify({ 'objInvestigationHis': objInvestigationHis });
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/InvestigationHis_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: objInvestigationHis,
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if (data1.Table.length > 0) {

                        for (var i = 0; i < data1.Table.length; i++) {
                            debugger;

                            var data2 = data1.Table[i].relational_column_id;
                            var data3 = data2.split(',');
                            if (data1.Table[i].Column_Type == "YN") {
                                if (parseInt(data1.Table[i].intra_operative_findings_check_values) > 0) {

                                    for (var j = 0; j < data3.length; j++) {
                                        $('#Text_id_' + data3[j]).show();
                                    }
                                }
                                else {
                                    for (var j = 0; j < data3.length; j++) {
                                        $('#Text_id_' + data3[j]).hide();
                                    }
                                }
                            }
                            else {
                                if (data1.Table[i].intra_operative_findings_values == data1.Table[i].CheckBox_condition_Value) {

                                    for (var j = 0; j < data3.length; j++) {
                                        $('#Text_id_' + data3[j]).show();
                                    }
                                }
                                else {
                                    for (var j = 0; j < data3.length; j++) {
                                        $('#Text_id_' + data3[j]).hide();
                                    }
                                }
                            }

                        }
                    }
                }
                else {
                    console.log(data);
                }               
            }
        },
        error: function (data) {
        }
    });
}

function ShowHideFunction(e) {
    var data = $(e).attr('data');
    var data1 = data.split(',');

    if ($(e).prop('checked')) {

        for (var i = 0; i < data1.length; i++) {
            $('#Text_id_' + data1[i]).show();
        }
    }
    else {
        for (var i = 0; i < data1.length; i++) {
            $('#Text_id_' + data1[i]).hide();
        }
    }
}

function ShowHideRadio(e) {
    var data = $(e).attr('data');
    var data1 = data.split(',');

    for (var i = 0; i < data1.length; i++) {
        $('#Text_id_' + data1[i]).hide();
    }

}

$('#btnPhistory').click(function () {
    debugger;
    if ($("#IPDischarge_Id").val() != "2") {

        if ($.trim($("#txtdiagnosis").val()) == "") {
            $('#Ptxtdiagnosis').show();
            $('#Ptxtdiagnosis').fadeOut(8000);
            $('#Ptxtdiagnosis').html('Enter Clinical diagnosis');
            $('#txtdiagnosis').val('');
            $('#txtdiagnosis').focus();
            return false;
        }

        if ($.trim($("#ChkAlcohol").val()) == "") {
            $('#PChkAlcohol').show();
            $('#PChkAlcohol').fadeOut(8000);
            $('#PChkAlcohol').html('Select Alcohol consumption');
            $('#ChkAlcohol').val('');
            $('#ChkAlcohol').focus();
            return false;
        }

        if ($.trim($("#ChkSmoking").val()) == "") {
            $('#PChkSmoking').show();
            $('#PChkSmoking').fadeOut(8000);
            $('#PChkSmoking').html('Select Smoking Habits');
            $('#ChkSmoking').val('');
            $('#ChkSmoking').focus();
            return false;
        }

        if ($.trim($("#ChkActivity").val()) == "") {
            $('#PChkActivity').show();
            $('#PChkActivity').fadeOut(8000);
            $('#PChkActivity').html('Select Activity');
            $('#ChkActivity').val('');
            $('#ChkActivity').focus();
            return false;
        }

        if ($.trim($("#ChkFood").val()) == "") {
            $('#PChkFood').show();
            $('#PChkFood').fadeOut(8000);
            $('#PChkFood').html('Select Food Preference');
            $('#ChkFood').val('');
            $('#ChkFood').focus();
            return false;
        }

        if ($.trim($("#txtTreatment").val()) == "") {
            $('#PtxtTreatment').show();
            $('#PtxtTreatment').fadeOut(8000);
            $('#PtxtTreatment').html('Enter Treatment History');
            $('#txtTreatment').val('');
            $('#txtTreatment').focus();
            return false;
        }
        if ($.trim($("#txtSurgery").val()) == "") {
            $('#PtxtSurgery').show();
            $('#PtxtSurgery').fadeOut(8000);
            $('#PtxtSurgery').html('Enter Surgery');
            $('#txtSurgery').val('');
            $('#txtSurgery').focus();
            return false;
        }

        var patientData = {
            patient_id: $("#IPPatient_Id").val(),
            Dml_Indicator: 'PHI',
            ip_visit_report_id: $("#IPVisitReport_Id").val(),
            complaints: $('#txtComplaints').val(),
            history_of_present_illness: $('#txtIllness').val(),
            Past_history_of_relevence_family: $('#txtFRelevence').val(),
            Past_history_of_relevence_personal: $('#txtPRelevence').val(),
            co_morbidities: $('#txtmorbidities').val(),
            clinical_examination: $('#txtExamination').val(),
            clinical_diagnosis: $('#txtdiagnosis').val(),
            drug_history: $('#txtDrugHistory').val(),
            treatment_history: $('#txtTreatment').val(),
            surgery_history: $('#txtSurgery').val(),
            personal_history: $('#txtPersonal').val(),
            alcohol_consumption: $('#ChkAlcohol').val(),
            smoking_habits: $('#ChkSmoking').val(),
            Activity: $('#ChkActivity').val(),
            food_preference: $('#ChkFood').val(),
            ip_radiation: $("#txtRadiation").val(),
            ip_chemotherapy: $("#txtChemotherapy").val()

        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Ipmanagement/PatientHistory_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(patientData),
            success: function (data) {
                //SaveIntraOperativeFindings();
                console.log(data);
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    SubmitArr = data
                    var ChkForm = CheckFormRights($("#IPPatient_Id").val(), 95, 3, 2);
                    $.when(ChkForm)
              .then(function (data3) {
                  var data2 = JSON.parse(data3);
             
                  if (jQuery.isEmptyObject((data2.data))) {
                      patientHistory_Submit()
                  }
                  else {
                      debugger;
                      if (data2.data.Table[0].StringMsg != "Rights") {
                          patientHistory_Submit()
                      }
                  }
              });
                }
            }
        });
    }
});

function patientHistory_Submit() {
    toastr.success('Patient History Added Successfully <br/>  <br/> <a type="button" href="/Ipmanagement/ippatientdetails?Patient_Id=' + $("#IPPatient_Id").val() + '&IPVisitReport_Id=' + $("#IPVisitReport_Id").val() + '&IPDischarge_Id=' + $("#IPDischarge_Id").val() + '&branch_id=' + $("#branch_id").val() + '" class="btn btn-xs btn-success">ok</a>');
 
}



//Form Close Funtion
$('#formClose').click(function () {
    debugger;
    patientHistory_Submit()

})


function SaveIntraOperativeFindings() {
    debugger;
    if ($('#HRecordCount').val() == '' || $('#HRecordCount').val() == null) {
        toastr.success('Patient History Added Successfully <br/>  <br/> <a type="button" href="/Ipmanagement/ippatientdetails?Patient_Id=' + $("#IPPatient_Id").val() + '&IPVisitReport_Id=' + $("#IPVisitReport_Id").val() + '&IPDischarge_Id=' + $("#IPDischarge_Id").val() + '&branch_id=' + $("#branch_id").val() + '" class="btn btn-xs btn-success">ok</a>');
        //toastr.success("Patient History Inserted Successfully");
        //window.location = "/Ipmanagement/ippatientdetails?Patient_Id=" + $("#IPPatient_Id").val() + "&IPVisitReport_Id=" + $("#IPReportId").val() + "&IPDischarge_Id=" + $("#IPDischarge_Id").val() + "&branch_id=" + $("#branch_id").val() + "";
    }
    var count = $('#HRecordCount').val();

    var objInvestigationHis = [];
    for (var i = 0; i < count; i++) {

        if ($('#GeneralInformation_' + (i + 1)).val() != null && $('#GeneralInformation_' + (i + 1)).val() != "") {
            var OperativeFindingsValue = $('#GeneralInformation_' + (i + 1)).val();
        }
        else if ($("input[name='optradio" + (i + 1) + "']:checked").val() != null && $("input[name='optradio" + (i + 1) + "']:checked").val() != "") {
            var OperativeFindingsValue = $("input[name='optradio" + (i + 1) + "']:checked").val();
        }
        else {
            var OperativeFindingsValue = "";
        }

        var IPDuration_Value = $('#Duration_' + (i + 1)).val();



        var OFcheck_values = ($('#check_' + (i + 1)).prop('checked') == true) ? "1" : "0";
        var OFMasHistoryId = $('#HBMaster_Id_' + (i + 1)).val();
        var OFParameterId = $('#HBPara_Id_' + (i + 1)).val();
        var OFSubParameterId = $('#HBSUB_Id_' + (i + 1)).val();
        var OFRecordID = $('#Record_Id_' + (i + 1)).val();

        objInvestigationHis.push({
            patient_id: $("#IPPatient_Id").val(),
            master_intra_operative_findings_id: OFMasHistoryId,
            ip_operations_id: $("#HOperationID").val(),
            Dml_Indicator: 'IFI',
            intra_operative_findings_values: OperativeFindingsValue,
            parameters_Id: OFParameterId,
            sub_Parameter_Id: OFSubParameterId,
            ip_visit_report_id: $("#IPVisitReport_Id").val(),
            screenid: "3",
            intra_operative_findings_check_values: OFcheck_values,
            record_id: OFRecordID,
            total_record: $('#HRecordCount').val(),
            ip_duration_value: IPDuration_Value
        })
    }


    objInvestigationHis = JSON.stringify({ 'objInvestigationHis': objInvestigationHis });
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Ipmanagement/InvestigationHis_Ins_Upd_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: objInvestigationHis,
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                toastr.success('Patient History Added Successfully <br/>  <br/> <a type="button" href="/Ipmanagement/ippatientdetails?Patient_Id=' + $("#IPPatient_Id").val() + '&IPVisitReport_Id=' + $("#IPVisitReport_Id").val() + '&IPDischarge_Id=' + $("#IPDischarge_Id").val() + '&branch_id=' + $("#branch_id").val() + '" class="btn btn-xs btn-success">ok</a>');
                //toastr.success("Patient History Inserted Successfully");
                //window.location = "/Ipmanagement/ippatientdetails?Patient_Id=" + $("#IPPatient_Id").val() + "&IPVisitReport_Id=" + $("#IPReportId").val() + "&IPDischarge_Id=" + $("#IPDischarge_Id").val() + "&branch_id=" + $("#branch_id").val() + "";
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('Some Issue');
        }
    });
}

//BriefHistory End//

// Personal History Template strat //
$('#AlcText').on('click', function () {
    if ($("#IPDischarge_Id").val() != "2") {
        $('.ChkAlcoholOptions').show();
        $(this).hide();
    }

});

$("#ChkAlcohol").change(function () {
    var ls = $(this).val();
    var lsTxt;
    if (ls == 1) {
        lsTxt = "Non Drinker";
    } else if (ls == 2) {
        lsTxt = "Rare";
    } else if (ls == 3) {
        lsTxt = "Social";
    } else if (ls == 4) {
        lsTxt = "Regular";
    } else if (ls == 5) {
        lsTxt = "Heavy";
    }
    $('#AlcText>span').text(lsTxt);
    $('#AlcText').show();
    $('.ChkAlcoholOptions').hide();
});

$('#smkText').on('click', function () {
    if ($("#IPDischarge_Id").val() != "2") {
        $('.smkChkOptions').show();
        $(this).hide();
    }

});

$("#ChkSmoking").change(function () {
    var ls = $(this).val();
    var lsTxt;
    if (ls == 8517006) {
        lsTxt = "Iv'e quit";
    } else if (ls == 266919005) {
        lsTxt = "Don't Smoke";
    } else if (ls == 4.28061E+14) {
        lsTxt = "1-2/day";
    } else if (ls == 4.28041E+14) {
        lsTxt = "3-5/day";
    } else if (ls == 4.28071E+14) {
        lsTxt = "5-10/day";
    } else if (ls == 449868002) {
        lsTxt = "10/day";
    }
    $('#smkText>span').text(lsTxt);
    $('#smkText').show();
    $('.smkChkOptions').hide();
});

$('#ChkActText').on('click', function () {
    if ($("#IPDischarge_Id").val() != "2") {
        $('.ChkActOptions').show();
        $(this).hide();
    }

});

$("#ChkActivity").change(function () {
    var ls = $(this).val();
    var lsTxt;
    if (ls == 1) {
        lsTxt = "Sedentary(low)";
    } else if (ls == 2) {
        lsTxt = "Moderately(normal)";
    } else if (ls == 3) {
        lsTxt = "Active(high)";
    } else if (ls == 4) {
        lsTxt = "Athletic(Very high)";
    }
    $('#ChkActText>span').text(lsTxt);
    $('#ChkActText').show();
    $('.ChkActOptions').hide();
});

$('#ChkFoodText').on('click', function () {
    if ($("#IPDischarge_Id").val() != "2") {
        $('.ChkFoodOptions').show();
        $(this).hide();
    }

});

$("#ChkFood").change(function () {
    var ls = $(this).val();
    var lsTxt;
    if (ls == 1) {
        lsTxt = "Vegetarian";
    } else if (ls == 2) {
        lsTxt = "Non-Vegetarian";
    } else if (ls == 3) {
        lsTxt = "Eggetarian";
    } else if (ls == 4) {
        lsTxt = "Vegan";
    }
    $('#ChkFoodText>span').text(lsTxt);
    $('#ChkFoodText').show();
    $('.ChkFoodOptions').hide();
});

// Personal History End //

//Family History start//
$('#add_family').click(function () {
    if ($('#add_family').length > 0) {
        if ($.trim($("#FSelrelationship").val()) == 0) {
            $('#PFSelrelationship').show();
            $('#PFSelrelationship').fadeOut(8000);
            $('#PFSelrelationship').html('Select the relationship');
            $('#PFSelrelationship').focus();
            return false;
        }
        if ($.trim($("#FSeldisease").val()) == 0) {
            $('#PFSeldisease').show();
            $('#PFSeldisease').fadeOut(8000);
            $('#PFSeldisease').html('Select the Condition');
            $('#PFSeldisease').focus();
            return false;
        }

        var Family_DML = "";

        if ($('#Hfamilyedit').val() == "") {
            Family_DML = 'I';
        }
        else {
            Family_DML = 'U';
        }

        var familydetails = {
            patient_id: $("#IPPatient_Id").val(),
            name: $('#Ftxtname').val(),
            relationship: $('#FSelrelationship').val(),
            disease: $('#FSeldisease').val(),
            no_of_years: $('#Ftxtyears').val(),
            patient_family_history_id: $('#Hfamilyedit').val(),
            Dml_Indicator: Family_DML
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/patient_family_history',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(familydetails),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data = data2.data;

                        var tr = ''
                        for (var i = 0; i < data.length; i++) {
                            var relationship = '';
                            var disease = '', noofyear, notesfamily;
                            if (data[i].relationship == 1) {
                                relationship = 'Father';
                            }
                            else if (data[i].relationship == 2) {
                                relationship = 'Mother';
                            }
                            else if (data[i].relationship == 3) {
                                relationship = 'Brother';
                            }
                            else if (data[i].relationship == 4) {
                                relationship = 'Sister';
                            }
                            else if (data[i].relationship == 5) {
                                relationship = 'Paternal GrandFather';
                            }
                            else if (data[i].relationship == 6) {
                                relationship = 'Paternal GrandMother';
                            }
                            else if (data[i].relationship == 7) {
                                relationship = 'Maternal GrandFather';
                            }
                            else if (data[i].relationship == 8) {
                                relationship = 'Maternal GrandMother';
                            }
                            else if (data[i].relationship == 9) {
                                relationship = 'Both Parents';
                            }
                            else if (data[i].relationship == 10) {
                                relationship = 'All Family number';
                            }
                            else if (data[i].relationship == 11) {
                                relationship = 'Others';
                            }
                            else {
                                relationship = '';
                            }
                            if (data[i].disease == 1) {
                                disease = 'CVA';
                            }
                            else if (data[i].disease == 2) {
                                disease = 'Thyroid';
                            }
                            else if (data[i].disease == 3) {
                                disease = 'Hypertension';
                            }
                            else if (data[i].disease == 4) {
                                disease = 'Diabetes';
                            }
                            else if (data[i].disease == 5) {
                                disease = 'Cardiac Diseases';
                            }
                            else if (data[i].disease == 6) {
                                disease = 'Cancer';
                            }
                            else if (data[i].disease == 7) {
                                disease = 'Renal Diseases';
                            }
                            else if (data[i].disease == 8) {
                                disease = 'Others';
                            }
                            else {
                                disease = '';
                            }
                            if (data[i].no_of_years == null || data[i].no_of_years == "") noofyear = "-";
                            else noofyear = data[i].no_of_years;
                            if (data[i].name == null || data[i].name == "") notesfamily = '-';
                            else notesfamily = data[i].name;
                            tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn btn-edit btn-xs" onclick="familyedit(' + data[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn btn-delete btn-xs" onclick="familydelete(' + data[i].patient_family_history_id + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></button></td></tr>';
                        }
                        $('#tbl_family_body').html(tr);
                        $('#Hfamilyedit').val('');
                        $('#Ftxtname').val('');
                        $('#FSelrelationship').val(0);
                        $('#FSeldisease').val(0);
                        $('#Ftxtyears').val('');
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
});
//Family History End//

function loadFamilyHistory() {
    var familydetails = {
        patient_id: $("#IPPatient_Id").val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/patient_family_history',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    var tr = ''
                    for (var i = 0; i < data.length; i++) {
                        var relationship = '';
                        var disease = '', noofyear, notesfamily;
                        if (data[i].relationship == 1) {
                            relationship = 'Father';
                        }
                        else if (data[i].relationship == 2) {
                            relationship = 'Mother';
                        }
                        else if (data[i].relationship == 3) {
                            relationship = 'Brother';
                        }
                        else if (data[i].relationship == 4) {
                            relationship = 'Sister';
                        }
                        else if (data[i].relationship == 5) {
                            relationship = 'Paternal GrandFather';
                        }
                        else if (data[i].relationship == 6) {
                            relationship = 'Paternal GrandMother';
                        }
                        else if (data[i].relationship == 7) {
                            relationship = 'Maternal GrandFather';
                        }
                        else if (data[i].relationship == 8) {
                            relationship = 'Maternal GrandMother';
                        }
                        else if (data[i].relationship == 9) {
                            relationship = 'Both Parents';
                        }
                        else if (data[i].relationship == 10) {
                            relationship = 'All Family number';
                        }
                        else if (data[i].relationship == 11) {
                            relationship = 'Others';
                        }
                        else {
                            relationship = '';
                        }
                        if (data[i].disease == 1) {
                            disease = 'CVA';
                        }
                        else if (data[i].disease == 2) {
                            disease = 'Thyroid';
                        }
                        else if (data[i].disease == 3) {
                            disease = 'Hypertension';
                        }
                        else if (data[i].disease == 4) {
                            disease = 'Diabetes';
                        }
                        else if (data[i].disease == 5) {
                            disease = 'Cardiac Diseases';
                        }
                        else if (data[i].disease == 6) {
                            disease = 'Cancer';
                        }
                        else if (data[i].disease == 7) {
                            disease = 'Renal Diseases';
                        }
                        else if (data[i].disease == 8) {
                            disease = 'Others';
                        }
                        else {
                            disease = '';
                        }
                        if (data[i].no_of_years == null || data[i].no_of_years == "") noofyear = "-";
                        else noofyear = data[i].no_of_years;
                        if (data[i].name == null || data[i].name == "") notesfamily = '-';
                        else notesfamily = data[i].name;
                        tr = tr + '<tr><td>' + relationship + '</td><td>' + disease + '</td><td>' + noofyear + '</td><td>' + notesfamily + '</td><td><button class="btn btn-edit btn-xs" onclick="familyedit(' + data[i].patient_family_history_id + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn btn-delete btn-xs" onclick="familydelete(' + data[i].patient_family_history_id + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></button></td></tr>';
                    }
                    $('#tbl_family_body').html(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function familyedit(val) {
    if ($("#IPDischarge_Id").val() != "2") {
        $('#Hfamilyedit').val(val);
        var familydetails = {
            Dml_Indicator: 'SS',
            patient_family_history_id: val,
            patient_id: $('#IPPatient_Id').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/patient_family_history',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(familydetails),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data = data2.data;

                        if (data.length > 0) {
                            //$('#add_family').hide();
                            //$('#Update_family').show();
                            for (var i = 0; i < data.length; i++) {
                                $('#Ftxtname').val(data[i].name);
                                $('#FSelrelationship').val(data[i].relationship);
                                $('#FSeldisease').val(data[i].disease);
                                $('#Ftxtyears').val(data[i].no_of_years);
                            }
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }

}

function familydelete(val) {

    if ($("#IPDischarge_Id").val() != "2") {
        var familydetails = {
            Dml_Indicator: 'D',
            patient_family_history_id: val,
            patient_id: $('#IPPatient_Id').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/patient_family_history',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(familydetails),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                    $('#tbl_family_body').html('')
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        loadFamilyHistory();
                    }
                    else {
                        console.log(data);
                    }

                }
            }
        });
    }

}