
$(document).ready(function () {

    $('#Back_href').attr('href', '/Ipmanagement/ippatientdetails?Patient_Id=' + $('#IPPatient_Id').val() + '&IPVisitReport_Id=' + $('#IPVisitReportId').val() + '&IPDischarge_Id=' + $('#hdnIDischageid').val() + '&branch_id=' + $('#branch_id').val() + '');
    LoadDischargeDetails();

    if ($('#hdnIDischageid').val() == 1)
    {
        $('#btnDischarge').hide();
    }
    LoadIntraOperative();
    loadMedicineType();
    ShowPrescription();
    loadpharmacyid();
    templatelist();
    if (parseInt($('#hiddenRole_id').val()) == 1) {
        PrintDoctor();
    }
});

function PrintDoctor() {
    var DoctorData = {
        Dml_Indicator: "HLGD",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#Branch_id').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#ddRefDoctor').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var RefDoctor = '';

                    var default_opt = '<option value="0">--Select--</option>';

                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {

                            if (parseInt($('#hiddenRole_id').val()) == 1) {
                                $('#txtDoctorName').prop('readonly', true);
                                $('#txtDoctorName').val(data1[i].first_name);
                                $('#Hdndoctor_name').val(data1[i].first_name);
                            }
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function LoadDischargeDetails() {
    var Dischargedata = {
        Dml_Indicator: "DDL",
        IP_visit_report_id: $('#IPVisitReportId').val()       
    }

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

            }
            else {

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

                    if (data1[0].summary_prepared_by != null || data1[0].discharge_approved_by != null || data1[0].nursing_discharge_date != '') {
                        $('#txtSPreparedBy').val(data1[0].summary_prepared_by);
                        $('#txtApprovedBy').val(data1[0].discharge_approved_by);
                        $('#txtIDDate').val(data1[0].nursing_discharge_date);
                        $('#txtIDtime').val(data1[0].nursing_discharge_time);
                    }

                    $('#HLastTrans_Date').val(data1[0].TransferDate);
                    $('#HLastTrans_time').val(data1[0].TransferTime);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


$('#btnDischarge').click(function () {
    var Hiddate = $("#HLastTrans_Date").val()
    var Hidtime = $("#HLastTrans_time").val()
    if ($("#IPDischarge_Id").val() != "2")
    {
        debugger;
        if (confirm("Are You Sure You Want To Discharge ?")) {

            if ($.trim($('#txtIDDate').val()) == '') {
                $('#PtxtIDDate').show();
                $('#PtxtIDDate').fadeOut(8000);
                $('#PtxtIDDate').html('Select Initiate Discharge Date');
                $('#txtIDDate').focus();
                return false;
            }

            if ($.trim($('#txtSPreparedBy').val()) == '') {
                $('#PtxtSPreparedBy').show();
                $('#PtxtSPreparedBy').fadeOut(8000);
                $('#PtxtSPreparedBy').html('Enter Summary Prepared By');
                $('#txtSPreparedBy').focus();
                return false;
            }

            if ($.trim($('#txtApprovedBy').val()) == '') {
                $('#PtxtApprovedBy').show();
                $('#PtxtApprovedBy').fadeOut(8000);
                $('#PtxtApprovedBy').html('Enter Approved By');
                $('#txtApprovedBy').focus();
                return false;
            }

            var ADT = $('#txtIDDate').val();
            if (ADT == '') {
                ADT = '';
            }
            else {
                var a = ADT.split('/');
                ADT = a[2] + '-' + a[1] + '-' + a[0];
            }

            var time = $("#txtIDtime").val();
            var ATM = moment(time, 'hh:mm A').format('HH:mm');

            var seldatetime = ADT + ' ' + ATM;
            var Bedtransfertime = Hiddate + ' ' + Hidtime;
            if (seldatetime <= Bedtransfertime) {
                //alert("date time");
                //if ($.trim(ADT)&& $.trim(ATM)<= Hiddate && Hidtime ) {
            //if ($.trim(ADT) <= Hiddate) {  
                //if ($.trim(ATM) <= Hidtime) {
                    //$('#PtxtIDtime').show();
                    //$('#PtxtIDtime').fadeOut(8000);
                    //$('#PtxtIDtime').html('The date and time is not lesser than previous transfer date and time');
                    toastr.warning('The date and time is not lesser than previous transfer date and time');
                    $('#txtIDtime').focus();
                    return false;
                }
            //}

            var Dischargedata = {
                Dml_Indicator: "DP",
                patient_ID: $('#IPPatient_Id').val(),
                IP_visit_report_id: $('#IPVisitReportId').val(),
                summary_prepared_by: $('#txtSPreparedBy').val(),
                discharge_approved_by: $('#txtApprovedBy').val(),
                ip_patient_admitdate: ADT + " " + ATM
                //treatment_in_hospital: $('#txtTreatment').val()

            }

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

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

                        toastr.success('Patient Discharge Initiated Successfully');

                        if (data1.length > 0)
                        {
                            debugger;
                            $('#btnDischarge').hide();
                            $('#hdnIDischageid').val(data1[0].ip_nursing_discharge);
                        }
                        
                        SaveIntraOperativeFindings();
                        //alert('Patient Initiate Discharged Successfully');
                        //window.location = "/Ipmanagement/admissionmangement";
                    }
                    else {
                        console.log(data);
                    }
                }
            });
        }
    }

});

function dischargerprint(){
    var Hiddate = $("#HLastTrans_Date").val()
    var Hidtime = $("#HLastTrans_time").val()

    if ($.trim($('#txtIDDate').val()) == '') {
        $('#PtxtIDDate').show();
        $('#PtxtIDDate').fadeOut(8000);
        $('#PtxtIDDate').html('Select Initiate Discharge Date');
        $('#txtIDDate').focus();
        return false;
    }

    if ($.trim($('#txtSPreparedBy').val()) == '') {
        $('#PtxtSPreparedBy').show();
        $('#PtxtSPreparedBy').fadeOut(8000);
        $('#PtxtSPreparedBy').html('Enter Summary Prepared By');
        $('#txtSPreparedBy').focus();
        return false;
    }

    if ($.trim($('#txtApprovedBy').val()) == '') {
        $('#PtxtApprovedBy').show();
        $('#PtxtApprovedBy').fadeOut(8000);
        $('#PtxtApprovedBy').html('Enter Approved By');
        $('#txtApprovedBy').focus();
        return false;
    }

    var ADT = $('#txtIDDate').val();
    if (ADT == '') {
        ADT = '';
    }
    else {
        var a = ADT.split('/');
        ADT = a[2] + '-' + a[1] + '-' + a[0];
    }

    var time = $("#txtIDtime").val();
    var ATM = moment(time, 'hh:mm A').format('HH:mm');

    //if ($.trim(ADT) == $("#HLastTrans_Date").val()) {

    //    if ($.trim(ATM) <= $("#HLastTrans_time").val()) {
    //        //$('#PtxtIDtime').show();
    //        //$('#PtxtIDtime').fadeOut(8000);
    //        //$('#PtxtIDtime').html('The date and time is not lesser than previous transfer date and time');
    //        toastr.warning('The date and time is not lesser than previous transfer date and time');
    //        $('#txtIDtime').focus();
    //        return false;
    //    }
    //}

    var Dischargedata = {
        Dml_Indicator: "DP",
        patient_ID: $('#IPPatient_Id').val(),
        IP_visit_report_id: $('#IPVisitReportId').val(),
        summary_prepared_by: $('#txtSPreparedBy').val(),
        discharge_approved_by: $('#txtApprovedBy').val(),
        ip_patient_admitdate: ADT + " " + ATM

    }

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

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

                if ($('#hdnIDischageid').val() == 0) {
                    toastr.success('Patient Discharge Initiated Successfully');
                }

                if (data1.length > 0) {
                    debugger;
                    $('#btnDischarge').hide();
                    $('#hdnIDischageid').val(data1[0].ip_nursing_discharge);
                }
                SaveIntraOperativeFindings();
                debugger;
                $.each(data1, function (i, emp) {
                    debugger;
                    var load_data = {
                        formid: '83',
                        branchid: emp.branch_id,
                        hospitalid: emp.hospitalid,
                        patientid: emp.patientid,
                        visit_reportid: emp.visit_reportid
                    }
                    $.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');
                            iframe = document.createElement('iframe'); //load content in an iframe to print later
                            document.body.appendChild(iframe);

                            iframe.style.display = 'none';
                            iframe.src = link;
                            iframe.onload = function () {
                                setTimeout(function () {
                                    iframe.focus();
                                    iframe.contentWindow.print();
                                }, 1);
                            };
                        }
                    });

                });

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

$('#btnPrintDischargeSummary').click(function () {
    //window.open('/Ipmanagement/DischargeSummary?visit_report_id=' + $('#IPVisitReportId').val() + '&patient_id=' + $('#IPPatient_Id').val() + '&doctor_id=' + $('#HiddenDoctorID').val() + '&type=1');

    if ($('#hdnIDischageid').val() == 1)
    {
        dischargerprint();
    }
    else
    {
        if (confirm("Are You Sure You Want To Discharge ?")) {

            dischargerprint();

        }
    }
});


//Dynamic function Start //


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 objInvestigationHis = [

        {
            Dml_Indicator: "DOPC",
            screenid: "5",
            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 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: "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: $("#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();
    }

}


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

function SaveIntraOperativeFindings() {
    debugger;
    //if ($('#HRecordCount').val() == '' || $('#HRecordCount').val() == null) {
    //    return false;
    //}
    $('#Back_href').attr('href', '/Ipmanagement/ippatientdetails?Patient_Id=' + $('#IPPatient_Id').val() + '&IPVisitReport_Id=' + $('#IPVisitReportId').val() + '&IPDischarge_Id=' + $('#hdnIDischageid').val() + '&branch_id=' + $('#branch_id').val() + '');
    var count = $('#HRecordCount').val();

    if (count == "" || count==0)
    {
        //toastr.success('Patient Discharge Initiated Successfully.');
        return false;
    }
    else
    {
        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;

                    //alert("Investigation History Inserted Successfully");
                    //window.location = "/Ipmanagement/ippatientdetails?Patient_Id=" + $("#IPPatient_Id").val() + "&IPVisitReport_Id=" + $("#IPVisitReport_Id").val() + "";
                   
                    //window.location = "/Ipmanagement/admissionmangement";

                    //if ($('#hdnIDischageid').val() == 0) {
                    //    toastr.success('Patient Discharge Initiated Successfully');
                    //}
                }
                else {
                    console.log(data);
                }
            },
            error: function (data) {
                toastr.warning('some issue');
            }
        });
    }

    
}

//Dynamic function End //

// prescription start //

function templatelist() {
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'S',
        is_ip: 1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            var tr = '';
            if (jQuery.isEmptyObject((data2.data))) {
                // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
            }
            else {

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

                    if (data.length <= 0) {
                        // Type 2- diet, Type 1-lab , Type 3- prescription to make therespective tab active in template page
                        tr = tr + '<a href="/Template/Index?Type=3"><div class="pull-left">Click To Add Prescription Template</div><div class="clearfix"></div></a>';
                    }
                    else {
                        for (var i = 0; i < data.length; i++) {
                            tr = tr + '<a href="javascript:void(0)" class="Clscopytemplate" onclick=copytemplate(' + data[i].medicine_template_id + ');><div class="pull-left">' + data[i].template_name + '</div><div class="clearfix"></div><br></a>';
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('#templatelist').html(tr);

        }
    });
}

function ShowPrescription() {
    var Prescriptiondata = {

        Dml_Indicator: "PS",
        ip_Indicator: "IP",
        visit_report_id: $("#IPVisitReport_Id").val(),
        is_discharge_medicine: 1
    }

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

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

                tr = $('<table id="example1" class="table table-responsive table-bordered table-striped dataTable " />');

                tr.append("<thead><tr><th>Types</th><th>Medicine</th><th>When to take</th><th>Duration</th><th>Doctor Instruction</th><th>Frequency</th><th>Route</th><th>Doctor Name</th><th>Created Date/Time</th><th>Action</th></tr></thead><tbody>");

                $.each(data1, function (i, emp) {
                    //var PaseStart = "";

                    view = "<a href=# class='label label-success'onclick=loadPrescription('" + emp.medicine_prescription_id + "');>Edit</a>";

                    //if (emp.ip_medicine_status == 1) {
                    //    PaseStart = "<a id='Pause' href=# class='label label-success'onclick=Pause('" + emp.medicine_prescription_id + "');>pause</a>";
                    //}
                    //else {
                    //    PaseStart = "<a id='Start' href=# class='label label-success'onclick=Start('" + emp.medicine_prescription_id + "');>Start</a>";
                    //}

                    var generic_name = '';
                    if (emp.generic_name == '' || emp.generic_name == null) {
                        generic_name = '';
                    }
                    else {
                        generic_name = '<span style=font-size:11sssssspx;><i>(' + emp.generic_name + ')</i></span>';
                    }

                    var session = '', morning = '0', afternoon = '0', evening = '0', night = '0';
                    if (emp.morning != '' && emp.morning != null) {

                        morning = emp.morning.split('.');

                        if (morning.length > 1) {
                            if (morning[1] == 5 || morning[1] == 50 || morning[1] == 05) {
                                if (morning[0] == 0) {
                                    morning = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (morning[1] == 25) {
                                if (morning[0] == 0) {
                                    morning = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (morning[1] == 75) {
                                if (morning[0] == 0) {
                                    morning = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    morning = morning[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                morning = emp.morning;
                            }
                        }
                        else { morning = emp.morning; }
                    }
                    if (emp.afternoon != '' && emp.afternoon != null) {
                        afternoon = emp.afternoon;
                        afternoon = afternoon.split('.');
                        if (afternoon.length > 1) {
                            if (afternoon[1] == 5 || afternoon[1] == 50 || afternoon[1] == 05) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (afternoon[1] == 25) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (afternoon[1] == 75) {
                                if (afternoon[0] == 0) {
                                    afternoon = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    afternoon = afternoon[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                afternoon = emp.afternoon;
                            }
                        }
                        else { afternoon = emp.afternoon; }
                    }
                    if (emp.evening != '' && emp.evening != null) {
                        evening = emp.evening.split('.');
                        if (evening.length > 1) {
                            if (evening[1] == 5 || evening[1] == 50 || evening[1] == 05) {
                                if (evening[0] == 0) {
                                    evening = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (evening[1] == 25) {
                                if (evening[0] == 0) {
                                    evening = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (evening[1] == 75) {
                                if (evening[0] == 0) {
                                    evening = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    evening = evening[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                evening = emp.evening;
                            }
                        }
                        else { evening = emp.evening; }
                    }
                    if (emp.night != '' && emp.night != null) {
                        night = emp.night.split('.');

                        if (night.length > 1) {
                            if (night[1] == 5 || night[1] == 50 || night[1] == 05) {
                                if (night[0] == 0) {
                                    night = '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>1</sup>&frasl;<sub>2</sub>';
                                }
                            }
                            else if (night[1] == 25) {
                                if (night[0] == 0) {
                                    night = '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>1</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else if (night[1] == 75) {
                                if (night[0] == 0) {
                                    night = '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                                else {
                                    night = night[0] + '<sup>3</sup>&frasl;<sub>4</sub>';
                                }
                            }
                            else {
                                night = emp.night;
                            }
                        }
                        else { night = emp.night; }
                    }
                    if (emp.evening == '' || emp.evening == null || emp.evening == 0) {
                        session = morning + ' - ' + afternoon + ' - ' + night;
                    }
                    else {
                        session = morning + ' - ' + afternoon + ' - ' + evening + ' - ' + night;
                    }

                    var color = '';
                    if (emp.priority == 1) {
                        color = '<i class=" fa fa-circle" style="color:green"></i>&nbsp;';
                    }
                    else if (emp.priority == 2) {
                        color = '<i class=" fa fa-play" style="color:orange"></i>&nbsp;';
                    }
                    else if (emp.priority == 3) {
                        color = '<i class=" fa fa-square" style="color:#418bfe"></i>&nbsp;';
                    }
                    else {
                        color = '<i class=" fa fa-circle" style="color:#ffffff"></i>&nbsp;';
                    }

                    row_data = "<tr><td>" + emp.medicine_type + "</td><td style='text-transform: capitalize;'>" + color + emp.medicine_name + generic_name + "</td><td>" + emp.when_to_eat_value + "</td><td>" + emp.days_to_take + "</td><td>" + emp.instructions + "</td><td>" + session + "</td><td>" + ((emp.iproute != null && emp.iproute != "") ? emp.iproute : "-") + "</td><td>" + ((emp.ipdoctor_name != null && emp.ipdoctor_name != "") ? emp.ipdoctor_name : "-") + "</td><td>" + emp.created_on + "</td><td>" + view + "</td></tr>";
                    tr.append(row_data);
                });
                tr.append("</tbody></table>");
                $('#tbl-medicine').html(tr);
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

function copytemplate(medicineTemplateId) {
    $('.Clscopytemplate').hide();
    $('#loaderimg').show();

    var VisitreportId = {
        medicine_template_id: medicineTemplateId,
        patient_id: $("#IPPatient_Id").val(),
        visit_report_id: $('#IPVisitReport_Id').val(),
        Dml_Indicator: 'DPTI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Medicine_template',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(VisitreportId),
        success: function (data) {

            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject((data2.data))) {
                $('#Ptbl-medicine').show();
                $('#Ptbl-medicine').fadeOut(8000);
                $('#Ptbl-medicine').html('No medicine prescribed during previous data found');
                $('#Ptbl-medicine').focus();
                $('#Ptbl-medicine').val('');
                return false;
            }
            else {

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

                    ShowPrescription();
                }
                else {
                    console.log(data);
                }
            }
            $('.Clscopytemplate').show();
            $('#loaderimg').hide();
        }
    });
}

function loadMedicineType() {

    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#HiddenDoctorID').val()
    }

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

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var medicine;
                    $('#SelMedicineType').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        medicine = medicine + '<option value="' + emp.medicine_type_id + '">' + emp.medicine_type + '</option>';
                    });
                    $('#SelMedicineType').append(default_opt + medicine);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    //PatientNeuropathyLoad();
    loadwhentoeat();
}

function loadwhentoeat() {

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

            }
            else {

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

                    $('#hndwenttoeat').empty();
                    trs = '';
                    for (var i = 0; i < data1.length; i++) {
                        trs = trs + '<option value="' + data1[i].when_to_eat_id + '">' + data1[i].when_to_eat_value + '</option>';
                    }
                    $('#hndwenttoeat').append(trs);
                }
                else {
                    console.log(data);
                }
            }
        }

    });
}

$('#txtDoctorName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, branch_id: $('#branch_id').val() },
            success: function (data) {
                debugger;
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#Hdndoctor_name').val(ui.item.value);
    }
});

//$('#ADD_Medicine').on("click", function () {
$(document).on('click', '#ADD_Medicine', function () {
    debugger;

    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
        $('#PSelMedicineType').show();
        $('#PSelMedicineType').fadeOut(8000);
        $('#PSelMedicineType').html('Select Types');
        $('#SelMedicineType').focus();
        $('#SelMedicineType :selected').val('0');
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    if ($.trim($('#medicine_name').val()) == "") {
        $('#Pmedicine_name').show();
        $('#Pmedicine_name').fadeOut(8000);
        $('#Pmedicine_name').html('Enter Medicine Name');
        $('#medicine_name').focus();
        $('#medicine_name').val('');
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    var priority = $("input[name='optradio']:checked").val();
    var mor = $('#mor').val();
    var aft = $('#aft').val();
    var nit = $('#nit').val();
    if ($('#days').val().length == 0 || $('#days').val() == '') {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter Duration');
        $('#days').focus();
        return false;
    }
    if (mor > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#mor').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (aft > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#aft').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }
    if (nit > 999) {
        $('#Pmor').show();
        $('#Pmor').fadeOut(8000);
        $('#Pmor').html('This seems to be high');
        $('#nit').focus();
        $('#ADD_Medicine').attr('disabled', false);
        return false;
    }

    if ($.trim($('#txtDoctorName').val()) != "") {

        if ($.trim($('#Hdndoctor_name').val()) == "") {
            $('#PtxtDoctorName').show();
            $('#PtxtDoctorName').fadeOut(8000);
            $('#PtxtDoctorName').html('Enter Valid Doctor Name');
            $('#txtDoctorName').focus();
            $('#txtDoctorName').val('');

            return false;
        }
    }

    var Durations = $('#hndduration').val();

    var WhenEat = $('#hndwenttoeat').val();
    var day = $('#days').val();
    if (day == '' || day == null) {
    }
    else {
        var days = 0;
        if (Durations == 1) {
            days = day;
        }
        else if (Durations == 2) {
            days = ((day) * (7));
        }
        else if (Durations == 3) {
            days = ((day) * (30));
        }
        else {

        }
    }
    var days1 = days;




    var medicineType = $('#dosage').val();
    var max_quantity = parseFloat(mor) + parseFloat(aft) + parseFloat(nit);
    max_quantity = parseFloat(max_quantity) * parseFloat($('#days').val());



    var mdPescription = {
        Dml_Indicator: 'IPI',
        ip_Indicator: "IP",
        patient_id: $("#IPPatient_Id").val(),
        visit_report_id: $("#IPVisitReport_Id").val(),
        medicine_type_id: $('#SelMedicineType').val(),
        medicine_name: $('#medicine_name').val(),
        how_to_take: $('#hndwenttoeat').val(),
        morning: mor,
        afternoon: aft,
        evening: $('#eve').val(),
        night: nit,
        days_to_take: days,
        pmedicine_dosage: $('#dosage').val(),
        medicine_dosage: $('#dosage').val(),
        medicine_type: $('#SelUnit').val(),
        doctor_id: $('#doctorId').val(),
        slot_start_time: $('#Hdnappointment_date').val(),
        instructions: $('#prescriptionNotes').val(),
        medicine_unit: $('#SelUnit').val(),
        generic_name: $('#txtGenericName').val(),
        max_quantity: max_quantity,
        pharmacy_id: $('#txtPharmacyID').val(),
        medicine_id: $('#txtMedicineID').val(),
        iproute: $("#ddRoute").val(),
        ipdoctor_name: $("#txtDoctorName").val(),
        medicine_prescription_id: $("#HPrescriptionID").val(),
        is_discharge_medicine: 1,
        priority: priority
    }

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

                if (data1.msg == "Success") {
                    debugger;
                    var data1 = data1.data;
                    if (data1.length > 0) {
                        if ($("#HPrescriptionID").val() == "") {
                            toastr.success('Prescription Added Successfully',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        }
                        else {

                            toastr.success('Prescription Updated Successfully',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });

                        }

                        ShowPrescription();
                        clearPrescription();
                    }
                    else {
                        toastr.warning('Unable to add the Prescription',
                            {
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                    }

                }
                else {
                    console.log(data);
                }

            }
        }
    });
});

function clearPrescription() {

    if (parseInt($('#hiddenRole_id').val()) == 2) {

        $('#txtDoctorName').val('');
        $('#Hdndoctor_name').val('');
    }

    $('#SelMedicineType').val(0),
    $("#medicine_name").val(""),
    $("#hndwenttoeat").val(""),
    $("#days").val(""),
    $("#mor").val(""),
    $('#aft').val(""),
    $('#nit').val("");
    $("#ddRoute").val(""),
    //$("#txtDoctorName").val(""),
    $("#prescriptionNotes").val(""),
    $("#HPrescriptionID").val(""),
    $('#txtGenericName').val('');
    $("#high").prop("checked", false);
    $("#medium").prop("checked", false);
    $("#low").prop("checked", false);

    //duration reset
    $('#duration_days').prop('checked', true);
    $('#duration_week').prop('checked', false);
    $('#duration_month').prop('checked', false);
    $('p.duration_days').addClass('text_before_btn');
    $('p.duration_week').removeClass('text_before_btn');
    $('p.duration_month').removeClass('text_before_btn');
    $('.duration_disp').html('Days');
    $('#hndduration').val(1);
    $('#setDurationUnit').text('Days');
    $("input[name='optradio']").prop('checked', false);

}

function loadPrescription(val) {
    if ($("#IPDischarge_Id").val() != "2") {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPID',
            ip_Indicator: "IP",
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Prescriptiondata),
            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) {
                            $('#SelMedicineType').val(emp.medicine_type_id),
                            $("#medicine_name").val(emp.medicine_name),
                            $("#hndwenttoeat").val(emp.how_to_take),
                            $("#days").val(emp.days_to_take),
                            $("#mor").val(emp.morning),
                            $('#aft').val(emp.afternoon),
                            $('#nit').val(emp.night);
                            $('#eve').val(emp.evening);
                            $("#ddRoute").val(emp.iproute),
                            $("#txtDoctorName").val(emp.ipdoctor_name),
                            $('#Hdndoctor_name').val(emp.ipdoctor_name),
                            $("#prescriptionNotes").val(emp.instructions),
                            $("#HPrescriptionID").val(emp.medicine_prescription_id)
                            $('#txtGenericName').val(emp.generic_name);
                            $("#high").prop("checked", false);
                            $("#medium").prop("checked", false);
                            $("#low").prop("checked", false);

                            $('#days').val(emp.days_to_take);
                            $('#duration_days').prop('checked', true);
                            $('#duration_week').prop('checked', false);
                            $('#duration_month').prop('checked', false);
                            $('p.duration_days').addClass('text_before_btn');
                            $('p.duration_week').removeClass('text_before_btn');
                            $('p.duration_month').removeClass('text_before_btn');
                            $('.duration_disp').html('Days');
                            $('#hndduration').val(1);
                            $('#setDurationUnit').text('Days');

                            if (emp.priority == 3) {
                                $("#high").prop("checked", true);
                            }
                            else if (emp.priority == 2) {
                                $("#medium").prop("checked", true);
                            }
                            else if (emp.priority == 1) {
                                $("#low").prop("checked", true);
                            }
                            else { }

                            if (emp.how_to_take == 9 || emp.how_to_take == 10) {
                                $('#eveningSession').show();
                                $('.alltime').removeClass('col-lg-3');
                                $('.alltime').addClass('col-lg-4');
                                $('.alltimeinner').removeClass('col-md-4');
                                $('.alltimeinner').addClass('col-md-3');
                                $('.whentoeatcls').removeClass('col-lg-2');
                                $('.whentoeatcls').addClass('col-lg-1');
                            }
                            else {
                                $('#eveningSession').hide();
                                //$('#eve').val(0);
                            }
                        });
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }

}

function Pause(val) {

    if ($("#IPDischarge_Id").val() != "2") {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPPS',
            ip_Indicator: "IP",
            ip_medicine_status: "0"
        }

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

                }
                else {

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

                        toastr.success('Medicine Paused');
                        ShowPrescription();
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
}

function Start(val) {

    if ($("#IPDischarge_Id").val() != "2") {
        var Prescriptiondata = {
            medicine_prescription_id: val,
            Dml_Indicator: 'IPPS',
            ip_Indicator: "IP",
            ip_medicine_status: "1"
        }

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

                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        toastr.success('Medicine Started');
                        ShowPrescription();
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }

}

function dosage() {
    var medicine_name = $('#medicine_name').val();

    if (medicine_name.length > 0) {
        var medicine = {
            medicine_name: medicine_name,
            doctor_id: $('#HiddenDoctorID').val(),
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientDashboard/select_Medicine',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(medicine),
            success: function (data) {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;

                    if (data1.Table1.length > 0) {
                        if (data1.Table1[0].generic_name == '' || data1.Table1[0].generic_name == null) {
                            //$('#SelMedicineType').val(data1.Table[0].medicine_type_id);
                            $('#txtGenericName').val(data1.Table[0].generic_name);
                            $('#lblGenericName').html('Select Generic');
                        }
                        else {
                            //$('#SelMedicineType').val(data1.Table1[0].medicine_type_id);
                            $('#txtGenericName').val(data1.Table1[0].generic_name);
                            //$('#lblGenericName').html(data1.Table1[0].generic_name);
                        }
                        $('#hndwenttoeat').val(data1.Table1[0].how_to_take);
                        //  $('#days').val(data1.Table1[0].days_to_take);
                        $('#mor').val(data1.Table1[0].morning);
                        $('#aft').val(data1.Table1[0].afternoon);
                        //$('#priority').val(data1.Table1[0].priority);
                        if (data1.Table1[0].priority == 3) {
                            $("#high").prop("checked", true);
                        }
                        else if (data1.Table1[0].priority == 2) {
                            $("#medium").prop("checked", true);
                        }
                        else if (data1.Table1[0].priority == 1) {
                            $("#low").prop("checked", true);
                        }
                        else { }
                        if (data1.Table1[0].how_to_take == 9 || data1.Table1[0].how_to_take == 10) {
                            $('#eveningSession').show();
                            $('.alltime').removeClass('col-lg-3');
                            $('.alltime').addClass('col-lg-4');
                            $('.alltimeinner').removeClass('col-md-4');
                            $('.alltimeinner').addClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-2');
                            $('.whentoeatcls').addClass('col-lg-1');
                        }
                        else {
                            $('#eveningSession').hide();
                            $('.alltime').addClass('col-lg-3');
                            $('.alltime').removeClass('col-lg-4');
                            $('.alltimeinner').addClass('col-md-4');
                            $('.alltimeinner').removeClass('col-md-3');
                            $('.whentoeatcls').removeClass('col-lg-1');
                            $('.whentoeatcls').addClass('col-lg-2');
                            $('#eve').val(0);
                        }
                        $('#nit').val(data1.Table1[0].night);
                        $('#prescriptionNotes').val(data1.Table1[0].instructions);
                    }
                    else if (data1.Table.length > 0) {
                        // $('#SelMedicineType').val(data1.Table[0].medicine_type_id);
                        $('#txtGenericName').val(data1.Table[0].generic_name);
                    }
                    else {
                        $('#txtGenericName').val('');
                        //$('#txtGenericName').prop('readonly', false);
                    }

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

$('#SelMedicineType').change(function () {

    if ($('#medicine_name').val() != null && $('#medicine_name').val() != "" && $('#txtMedicineID').val() != null && $('#txtMedicineID').val() != "") {
        $('#txtMedicineID').val('');
        $('#medicine_name').val('');
        $('#days').val('');
        $('#dosage').val('');
        $('input:checkbox').prop('checked', false);
        $('#mor').val(0);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(0);
        $('#prescriptionNotes').val('');
        $('#txtGenericName').val('');
        //$('#txtGenericName').prop('readonly', true);
        $('#lblGenericName').html('Select Generic');
        $('#txtGenericName').show();
        //when_to eat reset
        $('#before_food').prop('checked', true);
        $('#with_food').prop('checked', false);
        $('#after_food').prop('checked', false);
        $('.when_to_eat_disp').text('Before Food');
        $('p.before_food').addClass('text_before_btn');
        $('p.with_food').removeClass('text_before_btn');
        $('p.after_food').removeClass('text_before_btn');
        $('#hndwenttoeat').val(0);
        //duration reset
        $('#duration_days').prop('checked', true);
        $('#duration_week').prop('checked', false);
        $('#duration_month').prop('checked', false);
        $('p.duration_days').addClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('.duration_disp').html('Days');
        $('#hndduration').val(1);
        $('#prescriptionNotesToggle').hide();
        $("input[name='optradio']").prop('checked', false);
    }

})

function Daily() {
    $('#days').val('9999');
}


$('.radio_wrapper_2').click(function () {
    debugger;
    var value = $('input[name=duration_switch]:checked').val();
    if (value == 1) {
        $('.duration_disp').text('Days');
        $('p.duration_days').addClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(1);
        $("#hndduration").change();
    } else if (value == 2) {
        $('.duration_disp').text('Week');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').addClass('text_before_btn');
        $('p.duration_month').removeClass('text_before_btn');
        $('#hndduration').val(2);
        $("#hndduration").change();
    } else if (value == 3) {
        $('.duration_disp').text('Month');
        $('p.duration_days').removeClass('text_before_btn');
        $('p.duration_week').removeClass('text_before_btn');
        $('p.duration_month').addClass('text_before_btn');
        $('#hndduration').val(3);
        $("#hndduration").change();
    }
});

$("#hndduration").change(function () {
    debugger;
    var dur = $(this).val();
    var durTxt;
    if (dur == 1) {
        durTxt = "Days";
    } else if (dur == 2) {
        durTxt = "Week";
    } else if (dur == 3) {
        durTxt = "Month";
    }
    $('#setDurationUnit').text(durTxt);
    $('#setDurationUnit').show();
    $('#DurationUnitToggle').hide();
});

function medicine() {
    if ($('#medicine').val('').length == 0) {
        $('#dosage').val('');
    }

}

function prescriptionNotes_change() {

    var mdescription = {
        Dml_Indicator: 'I',
        doctor_id: $('#doctorId').val(),
        notes: $('#prescriptionNotes').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/prescription_notes_ins',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(mdescription),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

            }

        }
    });
}

function loadpharmacyid() {
    var screen = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/Dashboard_count',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(screen),
        success: function (datas) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.datas))) {

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

                    if (data.Table9.length > 0) {
                        var pharmacyID = data.Table9[0].pharmacy_id;
                        $('#txtPharmacyID').val(pharmacyID);
                        $('#phy_data_flag').val(data.Table9[0].data_flag);

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

$('#hndwenttoeat').change(function () {
    var hndwenttoeat = $('#hndwenttoeat').val();
    if (hndwenttoeat == 9 || hndwenttoeat == 10) {
        $('#eveningSession').show();
        $('.alltime').removeClass('col-lg-3');
        $('.alltime').addClass('col-lg-4');
        $('.alltimeinner').removeClass('col-md-4');
        $('.alltimeinner').addClass('col-md-3');
        $('.whentoeatcls').removeClass('col-lg-2');
        $('.whentoeatcls').addClass('col-lg-1');
    }
    else {
        $('#eveningSession').hide();
        $('#eve').val(0);
    }
    if ($('#hndwenttoeat').val() == 4) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(0);
    }
    else if ($('#hndwenttoeat').val() == 5) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 6) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 7) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 8) {
        $('#mor').val(1);
        $('#aft').val(0);
        $('#eve').val(0);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 9) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(1);
        $('#nit').val(1);
    }
    else if ($('#hndwenttoeat').val() == 10) {
        $('#mor').val(1);
        $('#aft').val(1);
        $('#eve').val(1);
        $('#nit').val(1);
    }
});

$('#medicine_name').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompletelist?dataflags=" + $('#phy_data_flag').val() + "&MedicineName=" + $('#medicine_name').val() + "&PharmacyID=" + $('#txtPharmacyID').val() + "&typeid=" + $('#SelMedicineType').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                //$('#txtMedicineID').val('');
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.medicine_status + "   ", value: item.medicine_name, medicine_type_id: item.medicine_type_id, id: item.medicine_id };
                    // return { label: item.medicine_name + "     Stock: " + item.medicine_status + "    MRP:  " + item.last_updated_on, value: item.medicine_name, medicine_type_id: item.medicine_type_id, id: item.medicine_id };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#txtMedicineID').val(ui.item.id);
        $('#SelMedicineType').val(ui.item.medicine_type_id);
    }
});

$('#txtGenericName').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/CaseStudy/AutoCompletelist_genericName?generic_name=" + $('#txtGenericName').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                response($.map(data, function (item) {
                    return { label: item.generic_name, value: item.generic_name, id: item.generic_id };
                }));
            }
        })
    }
});

// prescription end //