$(document).ready(function () {
    LoadTemplateDetails();
    loadMedicineType();

})

function loadMedicineType() {

    var params = {
        Dml_Indicator: '',
        medicine_type_id: 0,
        medicine_type: $('#hdn_IPDoctorID').val(),
        is_pharmacy: $('#His_pharmacy').val(),
        hospital_id: $('#HdnHospitalid').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);
                }
            }
        }
    });
    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);
                }
            }
        }

    });
    templatelist();
}

function templatelist() {
    var Template = {
        doctor_id: $('#hdn_IPDoctorID').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))) {
                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) {                        
                        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 LoadTemplateDetails() {
    $('#SelSummaryTemplate').empty();

    var subdepartment = {
        Dml_Indicator: "S",
        doctor_id: $('#hdn_IPDoctorID').val(),
        branch_id: $('#branch_id').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/Discharge_summary_template_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table.length > 0) {
                        var default_opt = '<option value="0">--Select--</option>';
                        var templatelist;
                        $.each(data1.Table, function (i, emp) {
                            templatelist = templatelist + '<option value="' + emp.template_id + '">' + emp.template_name + '</option>';
                        });

                        $('#SelSummaryTemplate').append(default_opt + templatelist);
                    }
                }
            }
        }
    });
}


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

    if ($.trim($('#SelSummaryTemplate :selected').val()) == "" || $('#SelSummaryTemplate :selected').val() == "0") {
        $('#PSelSummaryTemplate').show();
        $('#PSelSummaryTemplate').fadeOut(8000);
        $('#PSelSummaryTemplate').html('Choose Template');
        $('#SelSummaryTemplate').focus();
        $('#SelSummaryTemplate').val('');
        return false;
    }

    $('#Hdn_patientsummarydetailsid').val('');
    LoadTemplateParameters();

});


function LoadTemplateParameters() {
    var subdepartment = {
        Dml_Indicator: "TS",
        template_id: $('#SelSummaryTemplate').val()        
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/Discharge_summary_template_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    if (data1.Table.length > 0) {
                       
                        $('#Reporttitle').html(data1.Table[0].template_title);
                        $('#template_header').val(data1.Table[0].template_header);
                        $('#template_footer').val(data1.Table[0].template_footer);
                        $('#page_top').val(data1.Table[0].page_top);
                        $('#page_bottom').val(data1.Table[0].page_bottom);
                        $('#font_size').val(data1.Table[0].font_size);
                        $('#font_style').val(data1.Table[0].font_style);
                        $('#sign').val(data1.Table[0].sign);
                        $('#header_logo').val(data1.Table[0].header_logo);
                        

                        $('#totalparameterscount').val(data1.Table1.length);

                        if (data1.Table1.length > 0) {
                            $('#divReportParameters').empty();
                            var row = '';
                            for (i = 0; i < data1.Table1.length; i++) {

                                if (data1.Table1[i].is_head == "1") {
                                    row = row + '<div class="col-md-12 mt20 mb-10" id="divParam_' + i + '"><div class="col-md-2 mt10" style="display:none;"><label id="lblParam_' + i + '">' + data1.Table1[i].parameter_label + '</label></div>'
                                    + '<div class="col-md-8" style="display:none;"><textarea id="txtParameter_' + i + '" class="form-control clsparamname_' + data1.Table1[i].summary_template_parameters_id + '">' + ((data1.Table1[i].is_default_text == 1 || data1.Table1[i].is_default_text == "1") ? data1.Table1[i].default_text : "") + '</textarea></div>'
                                    + '<input type="hidden" id="ishead_' + i + '" value="' + data1.Table1[i].is_head + '" /><input type="hidden" id="paramname_' + i + '" value="' + data1.Table1[i].parameter_name + '" /><input type="hidden" id="displayorder_' + i + '" value="' + data1.Table1[i].display_order + '" /><input type="hidden" id="summarytempparamid_' + i + '" value="' + data1.Table1[i].summary_template_parameters_id + '" /><div>' + data1.Table1[i].parameter_label + '</div></div>'
                                }
                                else if (data1.Table1[i].parameter_name.toLowerCase() == "prescription") {
                                    row = row + '<div class="col-md-12 mt20 mb-10" id="divParam_' + i + '" style="display:none;"><div class="col-md-2 mt10" style="display:none;"><label id="lblParam_' + i + '">' + data1.Table1[i].parameter_label + '</label></div>'
                                    + '<div class="col-md-8" style="display:none;"><textarea id="txtParameter_' + i + '" class="form-control clsparamname_' + data1.Table1[i].summary_template_parameters_id + '">' + ((data1.Table1[i].is_default_text == 1 || data1.Table1[i].is_default_text == "1") ? data1.Table1[i].default_text : "") + '</textarea></div>'
                                    + '<input type="hidden" id="ishead_' + i + '" value="' + data1.Table1[i].is_head + '" /><input type="hidden" id="paramname_' + i + '" value="' + data1.Table1[i].parameter_name + '" /><input type="hidden" id="displayorder_' + i + '" value="' + data1.Table1[i].display_order + '" /><input type="hidden" id="summarytempparamid_' + i + '" value="' + data1.Table1[i].summary_template_parameters_id + '" /></div>'
                                    $('#lblPrescriptionsection').html(data1.Table1[i].parameter_label);
                                    $('#divDischargeMedicine').show();
                                }
                                else {
                                    row = row + '<div class="col-md-12 mt20 mb-10" id="divParam_' + i + '"><div class="col-md-2 mt10"><label id="lblParam_' + i + '">' + data1.Table1[i].parameter_label + '</label></div>'
                                    + '<div class="col-md-8"><textarea id="txtParameter_' + i + '" class="form-control summernote clsparamname_' + data1.Table1[i].summary_template_parameters_id + '">' + ((data1.Table1[i].is_default_text == 1 || data1.Table1[i].is_default_text == "1") ? data1.Table1[i].default_text : "") + '</textarea></div>'
                                    + '<input type="hidden" id="ishead_' + i + '" value="' + data1.Table1[i].is_head + '" /><input type="hidden" id="paramname_' + i + '" value="' + data1.Table1[i].parameter_name + '" /><input type="hidden" id="displayorder_' + i + '" value="' + data1.Table1[i].display_order + '" /><input type="hidden" id="summarytempparamid_' + i + '" value="' + data1.Table1[i].summary_template_parameters_id + '" /></div>'
                                }

                                
                            }

                            $('#divReportParameters').append(row);

                            $('.summernote').summernote({
                                toolbar: [
                                  // [groupName, [list of button]]
                                  ['style', ['bold', 'italic', 'underline']],
                                  ['fontname', ['fontname']],
                                  ['fontsize', ['fontsize']],
                                  ['para', ['ul', 'ol', 'paragraph']],
                                  //['height', ['height']]
                                ]
                            });
                        }

                        $('#reportParameters_Section').show();
                    }

                }
            }

            GetPatientDischargeSummaryDetails();
        }
    });



}

//Load already saved data for this template for this patient
function GetPatientDischargeSummaryDetails() {

    if ($('#totalparameterscount').val() == 0) {        
        return false;
    }

    var subdepartment = {
        Dml_Indicator: "PDS",        
        patient_id: $('#IPPatient_Id').val(),
        visit_report_id: $('#IPVisitReportId').val(),
        template_id : $('#SelSummaryTemplate').val()        
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/Discharge_summary_template_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.Table.length > 0) {                       
                        var summarydatajson = data1.Table[0].summary;
                        if (jQuery.isEmptyObject((summarydatajson))) {
                        }
                        else {
                            var summarydata = JSON.parse(summarydatajson);

                            var paramdata = summarydata.parameters_data;

                            $('#Hdn_patientsummarydetailsid').val(data1.Table[0].patient_discharge_summary_id);
                            $('#Hdn_patientIntId').val(data1.Table[0].patientid)
                            $('#Hdn_visitreportIntId').val(data1.Table[0].visit_reportid);
                            $('#btnPrintSummary').show();

                            if (paramdata.length > 0) {

                                for (l = 0; l < paramdata.length; l++) {
                                    $('.clsparamname_' + paramdata[l].summary_template_parameter_id).summernote('code', paramdata[l].textvalue);
                                }
                            }
                        }                          
                                                   
                        
                    }
                }
            }
        }        
    })

    ShowPrescription();
}

$('#btnSaveandPrintSummary').click(function () {

    if ($('#totalparameterscount').val() == 0) {
        alert('Kindly add parameters');
        return false;
    }

    var parameterArray = new Array();  
    var totalparameters = $('#totalparameterscount').val()
    if (totalparameters > 0) {
        for (var i = 0; i < totalparameters; i++) {
            var parameter_data = {}
            parameter_data.parameter_name = $('#paramname_' + i).val(),
            parameter_data.parameter_label = $('#lblParam_' + i).html(),
            parameter_data.textvalue = $('#txtParameter_' + i).summernote('code'),
            parameter_data.is_head = $('#ishead_' + i).val(),
            parameter_data.display_order = $('#displayorder_' + i).val(),
            parameter_data.summary_template_parameter_id = $('#summarytempparamid_' + i).val();
            parameterArray.push(parameter_data);
        }
    }

    var dischargemedicineArray = new Array();
    var totalPrescription = $('#tbl-medicine tbody tr').length;
    if(totalPrescription>0){
        $("#tbl-medicine tbody tr").each(function () {
            var medicinearray = {}
            medicinearray.medicine_type = $(this).find("td").eq(0).html();
            medicinearray.medicine_name = $(this).find("td").eq(1).text();
            medicinearray.how_to_take = $(this).find("td").eq(2).html();
            medicinearray.duration = $(this).find("td").eq(3).html();
            medicinearray.instructions = $(this).find("td").eq(4).html();
            medicinearray.frequency = $(this).find("td").eq(5).html();
            medicinearray.ip_route = $(this).find("td").eq(6).html();
            medicinearray.ip_doctor_name = $(this).find("td").eq(7).html();
            medicinearray.createddatetime = $(this).find("td").eq(8).html();
            dischargemedicineArray.push(medicinearray);
        })
        
    }

    var subdepartment = {
        Dml_Indicator: "PDI",
        doctor_id: $('#hdn_IPDoctorID').val(),
        branch_id: $('#branch_id').val(),
        patient_id: $('#IPPatient_Id').val(),
        visit_report_id: $('#IPVisitReportId').val(),
        template_id : $('#SelSummaryTemplate').val(),        
        template_tile: $('#Reporttitle').html(),
        template_header: $('#template_header').val(),
        template_footer: $('#template_footer').val(),
        page_top: $('#page_top').val(),
        page_bottom: $('#page_bottom').val(),
        sign: $('#sign').val(),
        font_size: $('#font_size').val(),
        font_style: $('#font_style').val(),
        header_logo: $('#header_logo').val(),
        parameters_data: parameterArray,
        prescription_data:dischargemedicineArray
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/Patient_discharge_summary_details_ins',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    alert('Saved Successfully');
                   
                    var patientid = data1.Table[0].patientid;
                    var visit_reportid = data1.Table[0].visit_reportid;

                    var load_data = {
                        formid: "164",                       
                        patientid: patientid,
                        visit_reportid: 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);                           
                            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);
                            };
                        }
                    });

                    
                }
            }
        }
    });
     

})

$('#btnPrintSummary').click(function () {

    
    var load_data = {
        formid: "164",
        patientid: $('#Hdn_patientIntId').val(),
        visit_reportid: $('#Hdn_visitreportIntId').val()

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


})


//------------------Prescription start --------------------------------------------------


$('#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=" + 0 + "&BranchId=" + $('#branch_id').val() + "&is_pharmacy=" + $('#His_pharmacy').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {                
                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 };                   
                }))
            }
        })
    },
    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 };
                }));
            }
        })
    }
});

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 {

            }

        }
    });
}

$('#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.doctor_id };
                }))
            }
        })
    },
    select: function (event, ui) {
        $('#doctorId').val(ui.item.value);
    }
});

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 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 Delete = '';
                    
                    Delete = '<button type="button" class="btn btn-delete btn-xs" data-id="CD_D1" data-toggle="tooltip" data-placement="bottom" title="Delete" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_Prescription" onclick=DeletePrescription(' + emp.medicine_prescription_id + ');><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                                       
                    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>" + Delete + "</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 DeletePrescription(id) {

    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'Are You Sure, You Want to Delete?',
          {

              closeButton: true,
              progressBar: true,
              allowHtml: true,
              timeOut: 20000000,

              onShown: function (toast) {
                  $("#confirmationRevertYes").click(function () {

                      var Prescriptiondata = {

                          Dml_Indicator: "IPD",
                          ip_Indicator: "IP",
                          medicine_prescription_id: id,
                          ip_prescription_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 (data2.msg == "Success") {

                                  toastr.success('Deleted Successfully.');

                                  ShowPrescription();

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

$(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($('#txtDoctorName').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 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 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 {

            }

        }
    });
}


$('#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);
    }
});

//------------------Prescription end --------------------------------------------------