$(document).ready(function () {
    loadExaminationHistory();
});

function loadExaminationHistory() {
    var Patientdata = {
        Dml_Indicator: "EXS",
        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) {
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                $.each(data1, function (i, emp) {

                    var hieghtdb = parseInt(emp.patient_height * 12) + parseInt(emp.patient_height_metric);
                    var hieghtout = Math.round(hieghtdb * 2.54);

                    if (parseInt(hieghtout) <= 0)
                    {
                        hieghtout = '';
                    }

                    $('#txtSYS').val(emp.patient_bp_max),
                    $('#txtDIA').val(emp.patient_bp_min),
                    $('#txtHeight').val(hieghtout),
                    $('#txtPulse').val(emp.pulse_rate),
                    $('#txtRespiratory').val(emp.ip_respiratory_rate),
                    $('#txtWeight').val(emp.patient_weight),
                    $('#txtOthers').val(emp.ip_Others),
                    $('#CBLAD').prop("checked", emp.ip_cervical_supraclavicular_LAD),
                    $('#CBIcterus').prop("checked", emp.ip_icterus),
                    $('#CBPallor').prop("checked", emp.ip_pallor),
                    $('#CBPedalEdema').prop("checked", emp.ip_pedal_edema),
                    $('#HOperationID').val(emp.ip_surgery_type),
                    $('#HdIPtype').val(emp.type_of_admition);

                });

                if ($('#HdIPtype').val() != 1)
                {
                    LoadIntraOperative();
                }

                PrintBMI();
            }
            else {
                console.log(data2);
            }

        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}


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 LoadIntraOperative() {
    //var Dml_Indicator = $('#HOperationID').val();

    var objInvestigationHis = [

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


    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 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);
                        }
                    }

                    var objInvestigationHis = [

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


                    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);
                                                        }
                                                        //$('#check_' + (j + 1)).prop("checked", data1.Table[i].intra_operative_findings_check_values);
                                                        //$('input[name=codecheck_1' + (j + 1) + ']').val((data1.Table[i].intra_operative_findings_check_values) ? "1" : "0");
                                                        $("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: "4",
        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();
    }

}

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

        if ($.trim($('#txtSYS').val()) == "") {
            $('#PtxtSYS').show();
            $('#PtxtSYS').fadeOut(8000);
            $('#PtxtSYS').html('Enter SYS');
            $('#txtSYS').focus();
            $('#txtSYS').val('');
            return false;
        }

        if ($.trim($('#txtDIA').val()) == "") {
            $('#PtxtDIA').show();
            $('#PtxtDIA').fadeOut(8000);
            $('#PtxtDIA').html('Enter DIA');
            $('#txtDIA').focus();
            $('#txtDIA').val('');
            return false;
        }

        var LAD = ($('#CBLAD').prop('checked') == true) ? "1" : "0";
        var Icterus = ($('#CBIcterus').prop('checked') == true) ? "1" : "0";
        var Pallor = ($('#CBPallor').prop('checked') == true) ? "1" : "0";
        var PedalEdema = ($('#CBPedalEdema').prop('checked') == true) ? "1" : "0";

        var heightFT = '', heightIn = '', heightcent = '';

        var height = $('#txtHeight').val();
        heightcent = height;
        var heightdb = height / 2.54;
        heightFT = heightdb / 12;
        heightFT = parseInt(heightFT);
        heightIn = heightdb % 12;
        heightIn = heightIn.toFixed(1);
        heightIn = Math.round(heightIn);

        var patientData = {
            patient_id: $("#IPPatient_Id").val(),
            Dml_Indicator: 'EXI',
            ip_visit_report_id: $("#IPVisitReport_Id").val(),
            BMI: $('#txtBMI').val(),
            SYS: $('#txtSYS').val(),
            DIA: $('#txtDIA').val(),
            height: heightFT,
            patient_height_metric: heightIn,
            Pulse: $('#txtPulse').val(),
            respiratory_rate: $('#txtRespiratory').val(),
            Weight: $('#txtWeight').val(),
            ip_Others: $('#txtOthers').val(),
            cervical_supraclavicular_LAD: LAD,
            icterus: Icterus,
            pallor: Pallor,
            pedal_edema: PedalEdema

        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Ipmanagement/PatientHistory_Ins_Upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(patientData),
            success: function (data) {

                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

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

                }
               
            }
        });
        
    }

});

function SaveIntraOperativeFindings() {
    debugger;
    if ($('#HRecordCount').val() == '' || $('#HRecordCount').val() == null) {
        toastr.success('Examination 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>');
       
    }
    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: "4",
            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) {
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                toastr.success('Examination 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>');
               
            }
            else {
                console.log(data);
            }
            
        },
        error: function (data) {
        }
    });
}

$(document).on('input', '#Total', function () {

    PrintBMI();
});

function PrintBMI() {
    debugger;
    var heightFT = '', heightIn = '', heightcent = '';

    var height = $('#txtHeight').val();
    heightcent = height;
    var heightdb = height / 2.54;
    heightFT = heightdb / 12;
    heightFT = parseInt(heightFT);
    heightIn = heightdb % 12;
    heightIn = heightIn.toFixed(1);
    heightIn = Math.round(heightIn);

    height = parseFloat(heightFT * 12) + parseFloat(heightIn);
    var weight = $('#txtWeight').val();
    weight = (weight * 2.20462)
    BMI = calculateBMI(height, weight);

    if (parseInt(BMI)>0)
    {
        BMI = BMI;
    }
    else
    {
        BMI = '';
    }
    $('#txtBMI').val(BMI);

    
}

function calculateBMI(height, weight) {
    var BMI = (weight / (height * height)) * 703

    return Math.round(BMI * Math.pow(10, 2)) / Math.pow(10, 2);
}