$(document).ready(function () {
    
    StepChart();
    FeatureDate();
    loadMedicineType();
    loadSugarTrend();
    loadBPTrend();
    loadProfile();
   
});

$('#btnStep').click(function () {
    
    StepChart();
});
$('#btnBP').click(function () {
    
    BPChart();
});
$('#btnSugar').click(function () {
    
    BloodSugarChart();
});
$('#btnHBA1C').click(function () {
    
    HBA1CChart();
});



function BloodSugarChart() {
    var BPTrend = {
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'B'
    }

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

            }
            else {
                var sugarMin = [], sugarMax = [], label = [];
                var BPTrend = {
                    doctor_id: $('#HiddenDoctorID').val(),
                    patient_id: $('#Hdnpatient_id').val(),
                    Dml_Indicator: 'A'
                }

                var data1 = JSON.parse(datas);

                for (var i = 0; i < data1.length; i++) {
                    sugarMin.push(data1[i].patient_blood_sugar_Pre_fasting);
                    label.push(data1[i].Pdate);
                }

                $.ajax({
                    async: true,
                    type: 'POST',
                    url: '/PatientDashboard/BloodSugarChart',
                    contentType: 'application/json; charset=UTF-8',
                    data: JSON.stringify(BPTrend),
                    success: function (datass) {
                        
                        var data22 = JSON.parse(datass);
                        for (var i = 0; i < data22.length; i++) {
                            sugarMax.push(data22[i].patient_blood_sugar_Post_fasting);
                        }

                        var ctx = document.getElementById('chartJSContainer').getContext('2d');
                        var chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                datasets: [{
                                    label: 'Sugar Pre Fasting',
                                    data: sugarMin,
                                    borderWidth: 1,
                                }, {
                                    label: 'Sugar Post Fasting',
                                    data: sugarMax,
                                    borderWidth: 1,
                                }],
                                labels: label
                            },
                            options: {
                                scales: {
                                    yAxes: [{
                                        ticks: {
                                            reverse: false
                                        }
                                    }]
                                }
                            }
                        });
                        
                    }
                });
                
            }
        }
    
    });
}

function BPChart() {
    var BPTrend = {
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'B'
    }

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

            }
            else {
                var BPMin = [], BPMax = [], label = [];
                var BPTrend = {
                    patient_id: $('#Hdnpatient_id').val(),
                    Dml_Indicator: 'A'
                }

                var data1 = JSON.parse(datas);

                for (var i = 0; i < data1.length; i++) {
                    BPMin.push(data1[i].patient_bp_mix);
                    label.push(data1[i].Pdate);
                }

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

                        var data22 = JSON.parse(datass);
                        for (var i = 0; i < data22.length; i++) {
                            BPMax.push(data22[i].patient_bp_max);
                        }

                        var ctx = document.getElementById('chartJSContainer').getContext('2d');
                        var chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                datasets: [{
                                    label: 'BP Min',
                                    data: BPMin,
                                    borderWidth: 1,
                                }, {
                                    label: 'BP Max',
                                    data: BPMax,
                                    borderWidth: 1,
                                }],
                                labels: label
                            },
                            options: {
                                scales: {
                                    yAxes: [{
                                        ticks: {
                                            reverse: false
                                        }
                                    }]
                                }
                            }
                        });

                    }
                });

            }
        }

    });
}


function StepChart() {
    var BPTrend = {
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: ''
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/StepChart',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(BPTrend),
        success: function (datas) {
            if (jQuery.isEmptyObject(datas)) {
            }
            else {
                var StepCount = [], label = [];
                var data1 = JSON.parse(datas);

                for (var i = 0; i < data1.length; i++) {
                    StepCount.push(data1[i].patient_step_record_achieved);
                    label.push(data1[i].Pdate);
                }
                
                        var ctx = document.getElementById('chartJSContainer').getContext('2d');
                        var chart = new Chart(ctx, {
                            type: 'line',
                            data: {
                                datasets: [{
                                    label: 'Step Count',
                                    data: StepCount,
                                    borderWidth: 1,
                                }],
                                labels: label
                            },
                            options: {
                                scales: {
                                    yAxes: [{
                                        ticks: {
                                            reverse: false
                                        }
                                    }]
                                }
                            }
                        });

                    }
        }

    });
}

function HBA1C() {
    var BPTrend = {
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: ''
    }

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

            }
            else {
                var HBA1C = [], label = [];
                var ctx = document.getElementById('chartJSContainer').getContext('2d');
                var chart = new Chart(ctx, {
                    type: 'line',
                    data: {
                        datasets: [{
                            label: 'HBA1C',
                            data: HBA1C,
                            borderWidth: 1,
                        }],
                        labels: label
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    reverse: false
                                }
                            }]
                        }
                    }
                });

            }
        }

    });
}


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


            if (jQuery.isEmptyObject((data))) {

            }
            else {
                var data1 = JSON.parse(data);
                var medicine;
                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);
            }
        }

    });
}


function loadSugarTrend() {
    var BPTrend = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'Sugar'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/BPSugarTrend',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(BPTrend),
        success: function (datas) {
            var data1 = JSON.parse(datas);
            var sugarMin = [], sugarMax = [],label=[];
            for (var i = 0; i < data1.length; i++) {
                sugarMin.push(data1[i].patient_blood_sugar_pre_fasting);
                sugarMax.push(data1[i].patient_blood_sugar_post_fasting);
                label.push(data1[i].lateday);
            }
            var ctx = document.getElementById('SugarTrend').getContext('2d');
            var chart = new Chart(ctx, {
                type: 'line',
                data: {
                    datasets: [{
                        label: 'Sugar Pre Fasting',
                        data: sugarMin,
                        borderColor: 'rgb(114, 99, 212)',
                        backgroundColor: 'rgba(114, 99, 217, 0.5)',
                        fill: false,
                        pointHoverRadius: 10
                    }, {
                        label: 'Sugar Post Fasting',
                        data: sugarMax,
                        borderColor: 'rgb(130, 195, 98)',
                        backgroundColor: 'rgba(130, 195, 98, 0.5)',
                        fill: false,
                        pointHoverRadius: 10
                    }],
                    labels: label
                },
                options: {
                    hover: {
                        mode: 'nearest',
                        intersect: false
                    },
                    tooltips: {
                        mode: 'nearest',
                        intersect: false
                    }
                }
            });
        }
    });
}

function loadBPTrend() {
    var BPTrend = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        Dml_Indicator: 'BP'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/BPSugarTrend',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(BPTrend),
        success: function (datass) {
            var data1 = JSON.parse(datass);
            var BPMin = [], BPMax = [], label = [];
            for (var i = 0; i < data1.length; i++) {
                BPMin.push(data1[i].patient_bp_min);
                BPMax.push(data1[i].patient_bp_max);
                label.push(data1[i].lateday);
            }
            var ctx = document.getElementById('BPTrend').getContext('2d');
            var chart = new Chart(ctx, {
                type: 'line',
                data: {
                    datasets: [{
                        label: 'BP Min',
                        data: BPMin,
                        borderColor: 'rgb(114, 99, 212)',
                        backgroundColor: 'rgba(114, 99, 217, 0.5)',
                        fill: false,
                        pointHoverRadius: 10
                    }, {
                        label: 'BP Max',
                        data: BPMax,
                        borderColor: 'rgb(130, 195, 98)',
                        backgroundColor: 'rgba(130, 195, 98, 0.5)',
                        fill: false,
                        pointHoverRadius: 10
                    }],
                    labels: label
                },
                options: {
                    hover: {
                        mode: 'nearest',
                        intersect: false
                    },
                    tooltips: {
                        mode: 'nearest',
                        intersect: false
                    }
                }
            });

        }
    });

}


function loadProfile() {
    var patient_id;
    var pid = $('#Hdnpatient_id').val();
    var patient_id;
        patient_id = pid;


    $('#patientid').val(patient_id);

    var Url = "/PatientVisitHistory?Patient_id=" + patient_id;

    $('#visit_history_patient_id').attr("href", Url);

    var view_profile = {
        patient_id: patient_id
    }


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

            }
            else {
                var data1 = JSON.parse(data);

                $.each(data1, function (i, emp) {

                    //alert(emp.patient_id);
                    var photoSrc;
                    var PatientPhoto = $('#hdnPatientPhoto').val();
                    if (emp["patient_photo"] == null || emp["patient_photo"]=="") {
                        photoSrc = "/Content/img/profile_icon.png";
                    }
                    else
                    {
                        photoSrc = PatientPhoto + emp["patient_photo"];

                    }
                    $('#patientPhoto,#DpatientPhoto').attr('src', photoSrc);

                    if (emp["patient_id"] == null || emp["patient_id"] == "") {
                        $('#cpatient_id').html('-');

                        $('#vpatientid').html('-');
                    }
                    else {
                        $('#cpatient_id').html(emp.patient_id);

                        $('#vpatientid').html(emp.patient_id);
                    }



                    if (emp["patient_first_name"] == null || emp["patient_first_name"] == "") {
                        $('#patientname').html('-');
                        $('#name').html('-');
                    }
                    else {
                        $('#patientname').html(emp.patient_first_name);
                        $('#name').html(emp.patient_first_name);
                    }


                    if (emp["patient_dob"] == null || emp["patient_dob"] == "") {
                        $('#dob').html('-');
                    }
                    else {

                        var date1 = emp.patient_dob.split('-');
                        //alert(date[0]);
                        var day = date1[2] + "-" + date1[1] + "-" + date1[0];
                        //alert(day);
                        $('#dob').html(day);
                    }
                    if (emp["patient_phone_number"] == null || emp["patient_phone_number"] == "") {
                        $('#contact_number').html('-');
                        $('#patientphone').html('-');
                    }
                    else {
                        $('#contact_number').html(emp.patient_phone_number);
                        $('#patientphone').html(emp.patient_phone_number);
                    }

                    if (emp["patient_email_id"] == null || emp["patient_email_id"] == "") {
                        $('#email_id').html('-');
                    }
                    else {
                        $('#email_id').html(emp.patient_email_id);
                    }
                    if (emp["patient_gender"] == null || emp["patient_gender"] == "") {
                        $('#gender').html('-');
                    }
                    else {
                        $('#gender').html(emp.patient_gender);
                    }
                    if (emp["patient_blood_group"] == null || emp["patient_blood_group"] == "") {
                        $('#blood_group').html('-');
                    }
                    else {
                        $('#blood_group').html(emp.patient_blood_group);
                    }
                    if (emp["patient_marital_status"] == null || emp["patient_marital_status"] == "") {
                        $('#marital_status').html('-');
                    }
                    else {
                        $('#marital_status').html(emp.patient_marital_status);
                    }
                    if (emp["patient_height"] == null || emp["patient_height"] == "" || emp["patient_height"] == "0") {
                        $('#height').html('-');
                    }
                    else {
                        $('#height').html(emp.patient_height);
                    }
                    if (emp["patient_weight"] == null || emp["patient_weight"] == "") {
                        $('#weight').html('-');
                    }
                    else {
                        $('#weight').html(emp.patient_weight);
                    }




                    $('#Allergies_note').html(emp.patient_allergy_note);

                    //alert(emp.patient_allergy_note);

                    var smoking_id = emp.patient_smoking_habit;
                    var alcohol_id = emp.patient_alcohol_consumption;
                    var activity_id = emp.patient_activity_level;
                    var food_id = emp.patient_food_perference;

                    if (emp["patient_smoking_habit"] == "" || emp["patient_smoking_habit"] == null) {
                        $('#smoking').html('-');
                    }
                    else {
                        var smoking = {
                            lifestyle_smoking_value_id: smoking_id
                        }

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

                                }
                                else {
                                    var data1 = JSON.parse(data);

                                    $.each(data1, function (i, emp) {
                                        $('#smoking').html(emp.lifestyle_smoking_value);
                                    });
                                }
                            }
                        });
                    }


                    if (emp["patient_alcohol_consumption"] == "" || emp["patient_alcohol_consumption"] == null) {
                        $('#alcohol').html('-');
                    }
                    else {

                        var alcohol = {
                            lifestyle_alcohol_consumption_id: alcohol_id
                        }

                        //alert(JSON.stringify(alcohol));

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

                                }
                                else {
                                    var data1 = JSON.parse(data);

                                    $.each(data1, function (i, emp) {
                                        $('#alcohol').html(emp.lifestyle_alcohol_consumptionl);
                                    });
                                }
                            }
                        });
                    }


                    if (emp["patient_activity_level"] == "" || emp["patient_activity_level"] == null) {
                        $('#activity').html('-');
                    }
                    else {

                        var activity = {
                            lifestyle_activity_level_id: activity_id
                        }


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

                                }
                                else {
                                    var data1 = JSON.parse(data);

                                    $.each(data1, function (i, emp) {
                                        $('#activity').html(emp.lifestyle_activity_level);
                                    });
                                }
                            }
                        });
                    }


                    if (emp["patient_food_perference"] == "" || emp["patient_food_perference"] == null) {
                        $('#food_preference').html('-');
                    }
                    else {
                        var food = {
                            lifestyle_food_preference_id: food_id
                        }


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

                                }
                                else {
                                    var data1 = JSON.parse(data);

                                    $.each(data1, function (i, emp) {
                                        $('#food_preference').html(emp.lifestyle_food_preference);
                                    });
                                }
                            }
                        });
                    }




                });

            }

        }
    });

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

            }
            else {
                var data1 = JSON.parse(data);

                $.each(data1, function (i, emp) {
                    tr = $('<span class="btn btn-default" />');
                    tr.append(emp.patient_allergy);
                    $('#Allergies').append(tr);
                });
                //tr.append('<td>' + emp.medicine_name + '<input type="hidden" value="' + emp.medicine_name + '" id="medicine_name_' + emp.medicine_prescription_id + '"/></td><td>' + food + '<input type="hidden" value="' + emp.how_to_take + '" id="food_' + emp.medicine_prescription_id + '"/></td><td>' + emp.days_to_take + '<input type="hidden" value="' + emp.days_to_take + '" id="day_' + emp.medicine_prescription_id + '"/></td><td>' + morning + '<input value="' + emp.morning + '" type="hidden" id="morning_' + emp.medicine_prescription_id + '"/></td><td>' + afternoon + '<input value="' + emp.afternoon + '" type="hidden"  id="afternoon_' + emp.medicine_prescription_id + '"/></td><td>' + night + '<input value="' + emp.night + '" type="hidden"  id="night_' + emp.medicine_prescription_id + '"/></td><td><button onclick="medicineedit(\'' + emp.medicine_prescription_id + '\')">Edit</button></td>');
                //$('#tbl-medicine').append(tr);

            }
        }
    });

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

            }
            else {
                var data1 = JSON.parse(data);

                if (data.length > 2) {

                    $.each(data1, function (i, emp) {
                        if (emp["patient_companion_contact_no"] == null || emp["patient_companion_contact_no"] == "") {
                            $('#ccontact').html('-');
                        }
                        else {
                            $('#ccontact').html(emp.patient_companion_contact_no);
                        }

                        if (emp["patient_companion_relationship"] == null || emp["patient_companion_relationship"] == "") {
                            $('#relationship').html('-');
                        }
                        else {
                            $('#relationship').html(emp.patient_companion_relationship);
                        }
                    });
                }
                else {
                    $('#ccontact').html('-');
                    $('#relationship').html('-');
                }
            }

        }
    });

}


function FeatureDate() {
    var appointment_date = $('#Hdnappointment_date').val();
    var str = appointment_date;
    var appdate = str.split("T");
    console.log('splitdate----' + appdate[0]);

    var d = new Date();
    var strDate = d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
    console.log(strDate);
    var month = d.getMonth() + 1;
    var todaydate = (d.getFullYear() < 10 ? "0" + d.getFullYear() : d.getFullYear()) + '-' + (month < 10 ? "0" + month : month) + "-" + (d.getDate() < 10 ? "0" + d.getDate() : d.getDate());
    if (appdate[0] > todaydate) {
        window.location.href = '/PatientCalender';
    }
}

$('#create_visitreport').click(function (event) {
    
    event.preventDefault();
    
    if ($.trim($('#datepickern').val()) == "") {
        $('#Pdatepickern').show();
        $('#Pdatepickern').fadeOut(8000);
        $('#Pdatepickern').html('Suggestion Date');
        $('#datepickern').focus();
        $('#datepickern').val('');
        return false;
    }

    var DoctorId = $('#myHiddenVar').val();


    var patient_id;
    var pid = $('#Hdnpatient_id').val();
    var patient_id;
    if (pid == null || pid == "") {
        patient_id = '0';
    }
    else {
        patient_id = pid;
    }

    if ($('#datepickern').val().length > 0) {

        var appointment_date = $('#Hdnappointment_date').val();

        var today_date = new Date(appointment_date);
        var now = new Date();
        console.log(today_date);
        console.log(now);

        //if (today_date <= now) {

            var date = today_date.getFullYear() + "-" + (today_date.getMonth() + 1) + "-" + today_date.getDate();


            var check_appointment_date = {
                patient_id: patient_id,
                slot_start_time: appointment_date
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/PatientDashboard/select_check_appointment_date',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(check_appointment_date),
                success: function (data) {
                    if (jQuery.isEmptyObject((data))) {
                        $('#Pdatepickern').show();
                        $('#Pdatepickern').fadeOut(8000);
                        $('#Pdatepickern').html('Sorry, The values you entered are invalid.\n Please try again.');
                        $('#datepickern').focus();
                    }
                    else {

                        if (data.length > 2) {

                            var data1 = JSON.parse(data);

                            $.each(data1, function (i, emp) {

                                var appointment_id = emp.appointment_id;

                                var sdate = $('#datepickern').val().split('/');
                                var cdate = sdate[2] + "-" + sdate[1] + "-" + sdate[0];



                                var check_suggest = {
                                    schedule_date: cdate,
                                    doctor_id: DoctorId
                                }

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

                                        if (data.length > 2) {

                                            $('#create_visitreport').prop('disabled', true);

                                            var Dml_Indicator = "I";
                                            var prescription_note = "";

                                            var visit_report_id = "";
                                            var next_appointment_date = cdate;

                                            var medicine_prescription_id = "";
                                            var prescription_scan_id = "";


                                            var create_visit_report = {
                                                Dml_Indicator: Dml_Indicator,
                                                prescription_note: prescription_note,
                                                patient_id: patient_id,
                                                visit_report_id: visit_report_id,
                                                next_appointment_date: next_appointment_date,
                                                appointment_id: appointment_id,
                                                created_on: date,
                                                doctor_id: DoctorId
                                            }

                                            //alert(JSON.stringify(create_visit_report));

                                            $.ajax({
                                                async: true,
                                                type: 'POST',
                                                url: '/PatientDashboard/VisitReport_Ins_Upd',
                                                contentType: 'application/json; charset=UTF-8',
                                                data: JSON.stringify(create_visit_report),
                                                success: function (data) {
                                                    if (jQuery.isEmptyObject((data))) {
                                                        
                                                    }
                                                    else {
                                                        //alert(data);
                                                        $('.edit').hide();
                                                        $('#ADD_Medicine').hide();
                                                        $('#Add_Lab_record').hide();

                                                        var data1 = JSON.parse(data);
                                                        var visitreportid;
                                                        $.each(data1, function (i, emp) {
                                                            //$('#hdnvisit_id').val(emp.visit_report_id);

                                                            visitreportid = emp.visit_report_id;

                                                            var tot_row = $.trim($('#TableRowCountM').val());
                                                            var i, j;
                                                            for (i = 1; i <= tot_row; i++) {
                                                                console.log(i);
                                                                // alert('fdg');
                                                                var gkey = 'rowM' + i;
                                                                console.log(sessionStorage.getItem(gkey));
                                                                var row_data = sessionStorage.getItem(gkey);
                                                                if (row_data == "") {
                                                                    console.log(gkey + '--------->' + row_data);
                                                                }
                                                                if (row_data != "") {
                                                                    console.log(gkey + '-------' + row_data);
                                                                    row_data = row_data.split(',');
                                                                    var medicine_dosage_value = row_data[3].split('-');
                                                                    var medicine_dosage = medicine_dosage_value[0];
                                                                    var medicine_type;
                                                                    console.log('value1----'+medicine_dosage_value[1]);
                                                                    console.log('value2----' + medicine_dosage_value[0]);
                                                                    
                                                                    if (medicine_dosage_value[1] == 'mg') {
                                                                        medicine_type = "1";
                                                                    }
                                                                    else if (medicine_dosage_value[1] == 'mcg') {
                                                                        medicine_type = "2";
                                                                    }
                                                                    else if (medicine_dosage_value[1] == 'gram') {
                                                                        medicine_type = "3";
                                                                    }
                                                                    else if (medicine_dosage_value[1] == 'ml') {
                                                                        medicine_type = "4";
                                                                    }

                                                                    var mdescription = {
                                                                        Dml_Indicator: Dml_Indicator,
                                                                        medicine_prescription_id: medicine_prescription_id,
                                                                        patient_id: patient_id,
                                                                        visit_report_id: visitreportid,
                                                                        medicine_type_id: row_data[0],
                                                                        medicine_name: row_data[1],
                                                                        how_to_take: row_data[2],
                                                                        morning: row_data[5],
                                                                        afternoon: row_data[6],
                                                                        night: row_data[7],
                                                                        days_to_take: row_data[4],
                                                                        pmedicine_dosage: row_data[3],
                                                                        medicine_dosage: medicine_dosage,
                                                                        medicine_type: medicine_type,
                                                                        doctor_id: DoctorId
                                                                    }
                                                                    //alert(JSON.stringify(mdescription));
                                                                    $.ajax({
                                                                        async: true,
                                                                        type: 'POST',
                                                                        url: '/PatientDashboard/Medicine_Prescription_Ins_Upd',
                                                                        contentType: 'application/json; charset=UTF-8',
                                                                        data: JSON.stringify(mdescription),
                                                                        success: function (data) {

                                                                        }
                                                                    });
                                                                }



                                                            }


                                                            var tot_rowM = $.trim($('#TableRowCount').val());
                                                            for (j = 1; j <= tot_rowM; j++) {
                                                                console.log(i);
                                                                // alert('fdg');
                                                                var gkey = 'row' + j;
                                                                console.log(sessionStorage.getItem(gkey));
                                                                var row_data = sessionStorage.getItem(gkey);
                                                                if (row_data == "") {
                                                                    console.log(gkey + '--------->' + row_data);
                                                                }
                                                                if (row_data != "") {
                                                                    console.log(gkey + '-------' + row_data);
                                                                    row_data = row_data.split(',');

                                                                    var sldate = row_data[2].split('/');
                                                                    var s_lab_date = sldate[2] + "-" + sldate[1] + "-" + sldate[0];

                                                                    var sms = {
                                                                        Dml_Indicator: Dml_Indicator,
                                                                        prescription_scan_id: prescription_scan_id,
                                                                        patient_id: patient_id,
                                                                        visit_report_id: visitreportid,
                                                                        lab_prescription: row_data[0],
                                                                        lab_type: row_data[1],
                                                                        suggested_date: s_lab_date
                                                                    }
                                                                    //alert(JSON.stringify(sms));
                                                                    $.ajax({
                                                                        async: true,
                                                                        type: 'POST',
                                                                        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
                                                                        contentType: 'application/json; charset=UTF-8',
                                                                        data: JSON.stringify(sms),
                                                                        success: function (data) {
                                                                            $('.pdmclose').click();
                                                                            alert("Visit Report ID : " + visitreportid);
                                                                            $('#visitreport').attr("data-target", " ");
                                                                            window.open('/PatientDashboard/PPDF?visitreportid=' + visitreportid, "_blank");

                                                                        }
                                                                    });
                                                                }
                                                            }


                                                        });

                                                        //$('.pdmclose').click();
                                                        //alert("Visit Report ID : " + visitreportid);
                                                        //$('#visitreport').attr("data-target"," ");
                                                        //window.open('/PatientDashboard/PPDF?visitreportid=' + visitreportid, "_blank");
                                                    }
                                                }
                                                });
                                        
                                        
                                        }
                                        else {
                                            
                                            $('#Pdatepickern').show();
                                            $('#Pdatepickern').fadeOut(8000);
                                            $('#Pdatepickern').html('Slot is not available');
                                            $('#datepickern').focus();
                                            //alert('Your Suggest date is not schedule date');
                                        }
                                    
                                    }

                                });
                            
                            });
                        //1234
                        }

                    
                        else {
                            //$('#Pdatepickern').show();
                            //$('#Pdatepickern').fadeOut(8000);
                            //$('#Pdatepickern').html('Slot is not available');
                            //$('#datepickern').focus();

                            alerttoastr.warning('Incorrect Patient ID or Appointment Date');
                        }
                    

                    }
                }
            });
        //} 
    //else {
        //alert('Your selected future appointment date')
    //}
    }
    else {
        //alert('Select Suggest date');
    }
});

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

    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
        $('#PSelMedicineType').show();
        $('#PSelMedicineType').fadeOut(8000);
        $('#PSelMedicineType').html('Select Types');
        $('#SelMedicineType').focus();
        $('#SelMedicineType :selected').val('0');
        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('');
        return false;
    }
    if ($.trim($('#dosage').val()) == "") {
        $('#Pdosage').show();
        $('#Pdosage').fadeOut(8000);
        $('#Pdosage').html('Enter Dosage');
        $('#dosage').focus();
        $('#dosage').val('');
        return false;
    }
    if ($.trim($('#days').val()) == "") {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter days');
        $('#days').focus();
        $('#days').val('');
        return false;
    }
    if ($.trim($('#days').val()) == "") {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter days');
        $('#days').focus();
        $('#days').val('');
        return false;
    }
    var medicineType = $('#dosage').val();
    console.log(medicineType);
    medicineType = medicineType.split('-');
  var  medicineType1 = medicineType[1];
  if (medicineType1 != 'mg' && medicineType1 != 'mcg' && medicineType1 != 'gram' && medicineType1 != 'ml') {
        $('#Pdosage').show();
        $('#Pdosage').fadeOut(8000);
        $('#Pdosage').html('Dosage value give like 100-mg / 100-mcg /100-ml/100-gram');
        $('#dosage').focus();
        $('#dosage').val('');
        return false;
    }
   
    var SelMedicineType = $('#SelMedicineType :selected').text();
    var SelMedicineTypeId = $('#SelMedicineType :selected').val();
    var medicine_name_dosage = $('#medicine_name').val().split('/');
    var medicine_name = medicine_name_dosage[0];
    var dosage = $('#dosage').val();
    //var how_to_take = $('#food').val();
    var how_to_take = $("input[name='food']:checked").val();
    var days_to_take = $('#days').val();
    var morning, morningt;

    var len1 = $('#morning[type=checkbox]:checked').length;
    if (len1 > 0) {
        morning = "1";
        morningt = '<i class="fa fa-circle text-primary"></i>';
    } else {
        morning = "0";
        morningt = '<i class="fa fa-circle"></i>';
    }


    var afternoon, afternoont;

    var len2 = $('#afternoon[type=checkbox]:checked').length;
    if (len2 > 0) {
        afternoon = "1";
        afternoont = '<i class="fa fa-circle text-primary"></i>';
    } else {
        afternoon = "0";
        afternoont = '<i class="fa fa-circle"></i>';
    }

    var night, nightt;

    var len3 = $('#night[type=checkbox]:checked').length;
    if (len3 > 0) {
        night = "1";
        nightt = '<i class="fa fa-circle text-primary"></i>';
    } else {
        night = "0";
        nightt = '<i class="fa fa-circle"></i>';
    }
    if (len1 == 0 && len2 == 0 && len3 == 0) {
        $('#PMorning').show();
        $('#PMorning').fadeOut(8000);
        $('#PMorning').html('Select the Frequency');
        //$('#PMorning').focus();
        //$('#days').val('');
        return false;

    }


    if (medicine_name_dosage.length > 0 && dosage.length > 0 && how_to_take.length > 0 && days_to_take.length > 0 && (len1 > 0 || len2 > 0 || len3 > 0)) {

        //alert(dosage);
        var format = /-/;
        if (format.test(dosage)) {

            //alert(dosage);
            var sess_key;


            var rowcount = $.trim($('#TableRowCountM').val());
            var tot_row = (Number(rowcount) + 1);
            var sess_data = SelMedicineTypeId + "," + medicine_name + "," + how_to_take + "," + dosage + "," + days_to_take + "," + morning + "," + afternoon + "," + night;

            //alert(tot_row);

            var ikey = 'rowM' + tot_row;

            //alert(ikey);

            sessionStorage.setItem(ikey, sess_data);
            console.log(ikey + '------>' + sess_data);

            var a;

            if (how_to_take == "1") {
                a = "Post Food";
            }
            else {
                a = "Pre Food";
            }


            var value = "<tr><td>" + SelMedicineType + "</td><td style='text-transform: capitalize;'>" + medicine_name + "</td><td>" + a + "</td><td>" + dosage + "</td><td>" + days_to_take + "</td><td>" + morningt + "</td><td>" + afternoont + "</td><td>" + nightt + "</td><td><button class='edit' onclick='medicineedit(\"" + ikey + "\")'>Edit</button></td></tr>"

            $('#tbl-medicine > tbody:last').append(value);
            $('#TableRowCountM').val(tot_row);


            $('#SelMedicineType').val('0');
            $('#food').val('1');
            $('#medicine_name').val('');
            $('#days').val('');
            $('#dosage').val('');
            $('input:checkbox').prop('checked', false);

            $("#dosage").attr("readonly", true);
        }
        else {
                $('#Pdosage').show();
                $('#Pdosage').fadeOut(8000);
                $('#Pdosage').html('Dosage value give like 100-mg / 100-mcg /100-ml/100-gram');
                $('#dosage').focus();
                $('#dosage').val('');
                return false;

        }

    }
    else {

       // alert("Required field in Medicine,When to eat,Dosage,Days and session(morning,afternoon,night)");

    }

});


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

    if (dosage.length > 0) {

        var dosage_split = dosage.split('/');

        var medicine = {
            medicine_name: dosage_split[0],
            medicine_dosage: dosage_split[1]
        }

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

                if (data.length > 2) {
                    $("#dosage").attr("readonly", true);

                    var data1 = JSON.parse(data);

                    $.each(data1, function (i, emp) {
                        var dosage = emp.medicine_dosage + "-" + emp.medicine_type;
                        //alert(dosage);
                        $('#dosage').val(dosage);
                    });
                }
                else {
                }


            }
        });


    }
}

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

}


$('#Update_Medicine').click(function () {
    
    if ($.trim($('#SelMedicineType :selected').val()) == "" || $('#SelMedicineType :selected').val() == "0") {
        $('#PSelMedicineType').show();
        $('#PSelMedicineType').fadeOut(8000);
        $('#PSelMedicineType').html('Select Types');
        $('#SelMedicineType').focus();
        $('#SelMedicineType :selected').val('0');
        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('');
        return false;
    }
    if ($.trim($('#dosage').val()) == "") {
        $('#Pdosage').show();
        $('#Pdosage').fadeOut(8000);
        $('#Pdosage').html('Enter Dosage');
        $('#dosage').focus();
        $('#dosage').val('');
        return false;
    }
    if ($.trim($('#days').val()) == "") {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter days');
        $('#days').focus();
        $('#days').val('');
        return false;
    }
    if ($.trim($('#days').val()) == "") {
        $('#Pdays').show();
        $('#Pdays').fadeOut(8000);
        $('#Pdays').html('Enter days');
        $('#days').focus();
        $('#days').val('');
        return false;
    }


    $('#ADD_Medicine').show();
    $('#Update_Medicine').hide();

    var table_id = $('#hddn_medicine_prescription_id').val();

    var SelMedicineType = $('#SelMedicineType :selected').text();
    var SelMedicineTypeId = $('#SelMedicineType :selected').val();
    var medicine_name_dosage = $('#medicine_name').val().split('/');
    var medicine_name = medicine_name_dosage[0];
    var how_to_take = $('#food').val();
    var days_to_take = $('#days').val();
    var dosage = $('#dosage').val();

    var morning, morningt;

    var len1 = $('#morning[type=checkbox]:checked').length;
    if (len1 > 0) {
        morning = "1";

    } else {
        morning = "0";

    }


    var afternoon, afternoont;

    var len2 = $('#afternoon[type=checkbox]:checked').length;
    if (len2 > 0) {
        afternoon = "1";

    } else {
        afternoon = "0";

    }

    var night, nightt;

    var len3 = $('#night[type=checkbox]:checked').length;
    if (len3 > 0) {
        night = "1";

    } else {
        night = "0";

    }
    if (len1 == 0 && len2 == 0 && len3 == 0) {
        $('#PMorning').show();
        $('#PMorning').fadeOut(8000);
        $('#PMorning').html('Select the Frequency');
        return false;

    }
    if (medicine_name.length > 0 && how_to_take.length > 0 && dosage.length > 0 && days_to_take.length > 0 && (len1 > 0 || len2 > 0 || len3 > 0)) {

        var sess_data = SelMedicineTypeId+","+medicine_name + "," + how_to_take + "," + dosage + "," + days_to_take + "," + morning + "," + afternoon + "," + night;
        var ikey = table_id;
        sessionStorage.setItem(ikey, sess_data);

        $('#tbl-medicine > tbody:last').empty();


        var tot_row = $.trim($('#TableRowCountM').val());
        var i, j;


        for (i = 1; i <= tot_row; i++) {
            console.log(i);
            var gkey = 'rowM' + i;
            console.log(sessionStorage.getItem(gkey));
            var row_data = sessionStorage.getItem(gkey);
            if (row_data == "") {
                console.log(gkey + '--------->' + row_data);
            }
            if (row_data != "") {
                row_data = row_data.split(',');
                if (row_data[4] == 1) {
                    morningt = '<i class="fa fa-circle text-primary"></i>';
                }
                else {
                    morningt = '<i class="fa fa-circle"></i>';
                }

                if (row_data[5] == 1) {
                    afternoont = '<i class="fa fa-circle text-primary"></i>';
                }
                else {
                    afternoont = '<i class="fa fa-circle"></i>';
                }

                if (row_data[6] == 1) {
                    nightt = '<i class="fa fa-circle text-primary"></i>';
                }
                else {
                    nightt = '<i class="fa fa-circle"></i>';
                }

                var a;

                if (row_data[1] == "1") {
                    a = "Post Food";
                }
                else {
                    a = "Pre Food";
                }

                var value = "<tr><td>" + SelMedicineType + "</td><td>" + row_data[1] + "</td><td>" + a + "</td><td>" + row_data[2] + "</td><td>" + row_data[3] + "</td><td>" + morningt + "</td><td>" + afternoont + "</td><td>" + nightt + "</td><td><button class='edit' onclick='medicineedit(\"" + gkey + "\")'>Edit</button></td></tr>"

                $('#tbl-medicine > tbody:last').append(value);
            }
        }

        $('input:checkbox').prop('checked', false);
        $('#food').val('1');
        $('#medicine_name').val('');
        $('#days').val('');
        $('#dosage').val('');

    }
    else {
        alert("Required field in Medicine,When to eat,Dosage,Days and session(morning,afternoon,night)");
    }

});


function medicineedit(medicine_id) {
    $('#ADD_Medicine').hide();
    $('#Update_Medicine').show();
    $('#hddn_medicine_prescription_id').val(medicine_id)

    var gkey = medicine_id;
    var row_data = sessionStorage.getItem(gkey);
    //alert(row_data);
    var row_data_split = row_data.split(',');

    var a = row_data_split[3].split('-');

    var medicine_name_ = row_data_split[1] + "/" + a[0];
    var medicine_type_ = row_data_split[0];
    var food_ = row_data_split[2];
    var dosage_ = row_data_split[3];
    var days_ = row_data_split[4];
    var morning_ = row_data_split[5];
    var afternoon_ = row_data_split[6];
    var night_ = row_data_split[7];

    //$('#SelMedicineType').text(medicine_type_);
    $('#SelMedicineType').val(medicine_type_);
    $('#food').val(food_);
    $('#medicine_name').val(medicine_name_);
    $('#days').val(days_);
    $('#dosage').val(dosage_);

    if (morning_ == "1") {
        $('#morning').prop('checked', true);
    }
    else {
        $('#morning').prop('checked', false);
    }

    if (afternoon_ == "1") {
        $('#afternoon').prop('checked', true);
    }
    else {
        $('#afternoon').prop('checked', false);
    }

    if (night_ == "1") {
        $('#night').prop('checked', true);
    }
    else {
        $('#night').prop('checked', false);
    }

}


$('#Add_Lab_record').click(function () {
    var SelFacility = $("#report").val();
    var SelFacilityId = $("input[name='scan']:checked").val();
    var Registration = $("#datepickerscan").val();


    if ($.trim((SelFacilityId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((SelFacility)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    if ($.trim((Registration)) == "") {
        $('#Pdatepickerscan').show();
        $('#Pdatepickerscan').fadeOut(8000);
        $('#Pdatepickerscan').html('Select Suggested Date');
        $('#datepickerscan').focus();
        $('#Pdatepickerscan').val('');
        return false;
    }


    if (SelFacility.length > 0 && SelFacilityId.length > 0) {

        var sess_key;
        var rowcount = $.trim($('#TableRowCount').val());
        var tot_row = (Number(rowcount) + 1);
        var sess_data = SelFacility + "," + SelFacilityId + "," + Registration;
        var ikey = 'row' + tot_row;



        sessionStorage.setItem(ikey, sess_data);
        console.log(ikey + '------>' + sess_data);

        var a;

        if (SelFacilityId == "1") {
            a = "Lab";
        }
        else if (SelFacilityId == "2") {
            a = "Scan";
        }
        else {
            a = "X-Ray";
        }

        var value = "<tr><td>" + SelFacility + "</td><td>" + a + "</td><td>" + Registration + "</td><td><button class='edit' onclick='scanedit(\"" + ikey + "\")'>Edit</button></td></tr>"

        $('#tbl-scan > tbody:last').append(value);
        $('#TableRowCount').val(tot_row);

        $("#report").val('');
        $("input[name='scan']").prop("checked", false);
        $("#datepickerscan").val('');
    }

    else {
        alert("Required field in lab test type, report name and suggested date");
    }


});


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

   

    var table_id = $('#hdn_scan_id').val();


    var SelFacility = $("#report").val();
    var SelFacilityId = $("input[name='scan']:checked").val();
    var Registration = $("#datepickerscan").val();

    if ($.trim((SelFacilityId)) == "") {
        $('#PSelFacilityId').show();
        $('#PSelFacilityId').fadeOut(8000);
        $('#PSelFacilityId').html('Select Type ');
        return false;
    }
    if ($.trim((SelFacility)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Report');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    if ($.trim((Registration)) == "") {
        $('#Pdatepickerscan').show();
        $('#Pdatepickerscan').fadeOut(8000);
        $('#Pdatepickerscan').html('Select Suggested Date');
        $('#datepickerscan').focus();
        $('#Pdatepickerscan').val('');
        return false;
    }

    $('#Add_Lab_record').show();
    $('#Update_Lab_record').hide();


    if (SelFacility.length > 0 && SelFacilityId.length > 0) {


        var sess_data = SelFacility + "," + SelFacilityId + "," + Registration;
        var ikey = table_id;
        sessionStorage.setItem(ikey, sess_data);

        $('#tbl-scan > tbody:last').empty();


        var tot_row = $.trim($('#TableRowCount').val());
        var i, j;


        for (i = 1; i <= tot_row; i++) {
            console.log(i);
            // alert('fdg');
            var gkey = 'row' + i;
            console.log(sessionStorage.getItem(gkey));
            var row_data = sessionStorage.getItem(gkey);
            if (row_data == "") {
                console.log(gkey + '--------->' + row_data);
            }
            if (row_data != "") {
                row_data = row_data.split(',');


                var a;

                if (row_data[1] == "1") {
                    a = "Lab";
                }
                else if (row_data[1] == "2") {
                    a = "Scan";
                }
                else {
                    a = "X-Ray";
                }

                var value = "<tr><td>" + row_data[0] + "</td><td>" + a + "</td><td>" + row_data[2] + "</td><td><button class='edit' onclick='scanedit(\"" + gkey + "\")'>Edit</button></td></tr>"

                $('#tbl-scan > tbody:last').append(value);


            }
        }

        $("#report").val('');
        $("input[name='scan']").prop("checked", false);
        $("#datepickerscan").val('');
    }
    else {
        alert("Required field in lab test type, report name and suggested date");
    }

});


function scanedit(scan_id) {



    $('#Add_Lab_record').hide();
    $('#Update_Lab_record').show();
    $('#hdn_scan_id').val(scan_id);

    var gkey = scan_id;
    var row_data = sessionStorage.getItem(gkey);
    //alert(row_data);
    var row_data_split = row_data.split(',');

    var report_ = row_data_split[0];
    var lab_type_ = row_data_split[1];


    if (lab_type_ == "1") {
        $("input[value='1']").prop('checked', true);
    }
    if (lab_type_ == "2") {
        $("input[value='2']").prop('checked', true);
    }
    if (lab_type_ == "3") {
        $("input[value='3']").prop('checked', true);
    }

    $('#report').val(report_);
    $('#datepickerscan').val(row_data_split[2]);

}






