$(document).ready(function () {
    //LoadIntraOperative();
    IPLapTbl('PLS');
});


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 loadpatientdetail() {
    debugger;
    var Fetchdata = {
        Dml_Indicator: "PD",
        patient_ID: $("#IPPatient_Id").val(),
        IP_visit_report_id: $("#IPVisitReport_Id").val()
    }

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

            }
            else {

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

                    $.each(data1, function (i, emp) {
                        $("#IPpatientid").html(emp.ip_patient_id + " | " + emp.ip_doctor_id),
                            $("#IPpatiendname").html(emp.PatientName),
                            $("#IPpatiendage").html(emp.age + " years | " + emp.gender),
                            $("#IPpatblood").html(emp.patient_blood_group),
                            $("#IPdate").html(emp.created_on),
                            $("#IPward").html(emp.Bed_ID),
                            $("#IPReportId").val(emp.ip_visit_report_id),
                            $('#HOperationID').val(emp.ip_surgery_type)
                    });

                    LoadIntraOperative();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


function LoadIntraOperative() {

    var objInvestigationHis = [

        {
            Dml_Indicator: "OPC",
            screenid: "2",
            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 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">');
                        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 header-line-center"> <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 //
                                    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-4" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group form-field-height"><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-4 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-4" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group form-field-height mt30"><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>');
                                        
                                    }
                                    else if (data.Table1[s].Column_Type == "DT") {
                                        tr.append('<div class="col-xs-12 col-md-4" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group form-field-height"><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-4" id="Text_id_' + data.Table1[s].ip_intra_operative_findings_id + '"><div class="form-group form-field-height"><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 form-field-height"><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>');
                                    }
                                    else {
                                        tr.append('');
                                    }

                                    SubParaID = data.Table1[s].SubParameter_ID;
                                }
                            }
                            tr.append("</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: "2"
                        },
                    ]


                    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: "2",
        ip_visit_report_id: $("#IPReportId").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();
    }

}


$('#btnInHistory').click(function () {
    if ($("#IPDischarge_Id").val() != "2") {
        SaveIntraOperativeFindings();
    }
});

function SaveIntraOperativeFindings() {
    debugger;
    if ($('#HRecordCount').val() == '' || $('#HRecordCount').val() == null) {
        return false;
    }
    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: "2",
            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("Investigation History Added Successfully");
                window.location = "/Ipmanagement/ippatientdetails?Patient_Id=" + $("#IPPatient_Id").val() + "&IPVisitReport_Id=" + $("#IPVisitReport_Id").val() + "";

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

$('#ResultPending_tab').click(function () {
    IPLapTbl('PLS');
})

$('#ResultCompleted_tab').click(function () {
    IPLapTbl('CLS');
})

function IPLapTbl(DML)
{
    //var request_data = {
    //    Dml_Indicator: DML,
    //    ip_visit_report_id: $("#IPVisitReport_Id").val()
    //}


    var objInvestigationHis = [

        {
            Dml_Indicator: DML,
            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;
            $('#req_service_list tbody').empty();
            $('#Completed_service_list tbody').empty();
            console.log(data);
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1))) {
            }
            else {

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

                    debugger;
                    
                    var tr = "";
                    $.each(data.Table, function (i, emp) {
                        var action = "-";

                        action = (emp.flag == 4) ? '<button type="button" class="btn btn-primaryuse btn-xs mr-5" onclick=jobprint("' + emp.work_order_id + '","' + emp.hospitalid + '","' + emp.patientid + '","' + emp.branch_id + '","' + emp.master_service_id + '","' + emp.barcodeid + '")><i class="fa fa fa-print" aria-hidden="true"></i></button>' : "Result Pending";


                        if (emp.base_amount_type == 4) {
                            var date_time = emp.service_date + " " + emp.service_time + " - " + emp.service_end_date + " " + emp.service_end_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + action + '</td></tr>'
                        }
                        else {
                            var date_time = emp.service_date + " " + emp.service_time;
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + emp.service_name + '</td><td>' + emp.service_code + '</td><td>' + emp.quantity + '</td><td>' + date_time + '</td><td>' + action + '</td></tr>'
                        }
                    })

                    if (DML == 'PLS')
                    {
                        $('#req_service_list tbody').append(tr);
                    }
                    else
                    {
                        $('#Completed_service_list tbody').append(tr);
                    }
                    
                }
                else {
                    console.log(data);
                }
            }
        }
    })
}

//print lab result
//function jobprint(work_order_id, hospitalid, patientid, branchid) {

//    var load_data = {
//        formid: "73",
//        branchid: branchid,
//        hospitalid: hospitalid,
//        work_order_id: work_order_id,
//        patientid: patientid

//    }

//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/reports/PrintCrystalReport',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(load_data),
//        success: function (data) {
//            var byteArray = new Uint8Array(data);
//            var blob = new Blob([byteArray], { type: "application/pdf" });
//            var link = window.URL.createObjectURL(blob);
//            window.open(link, '_blank');

//        }
//    });

//}

function jobprint(work_order_id, hospitalid, patientid, branchid, master_service_id, barcodeid) {

    var load_data = {
        formid: "73",
        branchid: branchid,
        hospitalid: hospitalid,
        work_order_id: work_order_id,
        patientid: patientid,
        barcodeid: barcodeid,
        masterserviceid: master_service_id

    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/reports/PrintCrystalReport',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(load_data),
        success: function (data) {
            var byteArray = new Uint8Array(data);
            var blob = new Blob([byteArray], { type: "application/pdf" });
            var link = window.URL.createObjectURL(blob);
            window.open(link, '_blank');

        }
    });

}