var Norecord = '<div class="img-center"><img src="/Content/img/no_record.png" class="img-resposive no_record_img" style="height:65px; width:72px; border-radius:0px;"><br><div class="no_data_content">No data found.</div></div>';

$(document).ready(function () {
    loadlab_id();
    $("#tbl").find("input,button,textarea,select").attr("disabled", "disabled");  
    $("#viewTab>li").click(function () {
        var hrefActive = $(this).find('a').attr("href");
        ('#viewTab a[href="' + hrefActive + '"]').tab('show');
    });
});

function functionclick(v) {
}

function changedefault(e) {
    var photoSrc = "/Content/img/profile_icon.png";
    $(e).attr("src", photoSrc)
}

function datefun() {
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate();

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndtoday').val(output);

    //yesterday
    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate() - 1;

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndyesterday').val(output);

    //tomorrow

    var d = new Date();

    var month = d.getMonth() + 1;
    var day = d.getDate() + 1;

    var output = (day < 10 ? '0' : '') + day + '/' +
        (month < 10 ? '0' : '') + month + '/' +
        d.getFullYear();
    $('#hndtomorrow').val(output);
}

function datefunction() {
    //    debugger;
    //    var date = $('#datepicker1').val();
    //    $('#app_date_current').html(date);
    //    $('#app_date_current1').html(date);
    //    $('#app_date_current2').html(date);
    //    $('#app_date_current3').html(date);
    //    labcount();
    //    //labAdvice();
}

$('#datepicker1').change(function () {
    var date = $('#datepicker1').val();
    $('#app_date_current').html(date);
    $('#app_date_current1').html(date);
    $('#app_date_current2').html(date);
    $('#app_date_current3').html(date);
    labcount();
});


$('#datepicker2').change(function () {
    var date = $('#datepicker2').val();
    $('#app_date_current').html(date);
    $('#app_date_current1').html(date);
    $('#app_date_current2').html(date);
    $('#app_date_current3').html(date);
    labcount();
});


$('#datepicker3').change(function () {
    var date = $('#datepicker3').val();
    $('#app_date_current').html(date);
    $('#app_date_current1').html(date);
    $('#app_date_current2').html(date);
    $('#app_date_current3').html(date);
    labcount();
});


$('#datepicker4').change(function () {
    var date = $('#datepicker4').val();
    $('#app_date_current').html(date);
    $('#app_date_current1').html(date);
    $('#app_date_current2').html(date);
    $('#app_date_current3').html(date);
    labcount();
});

function Lableftarrow() {

    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
    }
    else if ($('#app_date_current').html() == 'Yesterday') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() - 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() + 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }


    var displaydate = $('#app_date_current').html();
    var date = '';
    var month = '';
    var displaydates = displaydate.split("/");
    displaydate = displaydates[1];
    if (displaydate == '01' || displaydate == '03' || displaydate == '05' || displaydate == '07' || displaydate == '08' || displaydate == '10' || displaydate == '12') {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '30' + '/' + '11' + '/' + displaydates[2];
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
            else if (displaydate == '01') {
                date = parseInt(displaydates[1]) + parseInt(1);
                var year = (displaydates[2]) - (1);
                date = '31' + '/' + '12' + '/' + year;
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
            else if (displaydate == '03') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '28' + '/' + '02' + '/' + displaydates[2];
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
            else {
                date = displaydates[1] - 1;
                if (date < 10) {
                    date = '0' + date;
                }
                date = '30' + '/' + date + '/' + displaydates[2];
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
        }

    }
    else if (displaydate == '04' || displaydate == '06' || displaydate == '09' || displaydate == '11') {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
    }
    else {
        if (displaydates[0] > 1) {
            date = displaydates[0] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + '01' + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
    }
    if (date == $('#hndtoday').val()) {
        $('#app_date_current').html('Today');
        $('#app_date_current1').html('Today');
        $('#app_date_current2').html('Today');
        $('#app_date_current3').html('Today');
    }
    if (date == $('#hndyesterday').val()) {
        $('#app_date_current').html('Yesterday');
        $('#app_date_current1').html('Yesterday');
        $('#app_date_current2').html('Yesterday');
        $('#app_date_current3').html('Yesterday');
    }
    if (date == $('#hndtomorrow').val()) {
        $('#app_date_current').html('Tomorrow');
        $('#app_date_current1').html('Tomorrow');
        $('#app_date_current2').html('Tomorrow');
        $('#app_date_current3').html('Tomorrow');
    }
    labcount();
    //labAdvice();
}


function Labrightarrow() {
    if ($('#app_date_current').html() == 'Today') {


        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }


    else if ($('#app_date_current').html() == 'Yesterday') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() - 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate() + 1;

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        $('#app_date_current').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }
    var displaydate = $('#app_date_current').html();
    var date = '';
    var month = '';
    var displaydates = displaydate.split("/");
    displaydate = displaydates[1];
    if (displaydate == '01' || displaydate == '03' || displaydate == '05' || displaydate == '07' || displaydate == '08' || displaydate == '10' || displaydate == '12') {
        if (displaydates[0] < 31) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                year = parseInt(displaydates[2]) + parseInt(1);
                date = '01' + '/' + '01' + '/' + year;
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
            else {
                date = parseInt(displaydates[1]) + parseInt(1);
                if (date < 10) {
                    date = '0' + date;
                }
                date = '01' + '/' + date + '/' + displaydates[2];
                $('#app_date_current').html(date);
                $('#app_date_current1').html(date);
                $('#app_date_current2').html(date);
                $('#app_date_current3').html(date);
            }
        }
    }
    else if (displaydate == '04' || displaydate == '06' || displaydate == '09' || displaydate == '11') {
        if (displaydates[0] < 30) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
    }
    else {
        if (displaydates[0] < 28) {
            date = parseInt(displaydates[0]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = date + '/' + displaydates[1] + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').html(date);
            $('#app_date_current1').html(date);
            $('#app_date_current2').html(date);
            $('#app_date_current3').html(date);
        }
    }
    if ($('#app_date_current').html() == $('#hndtoday').val()) {
        $('#app_date_current').html('Today');
        $('#app_date_current1').html('Today');
        $('#app_date_current2').html('Today');
        $('#app_date_current3').html('Today');
    }
    if ($('#app_date_current').html() == $('#hndyesterday').val()) {
        $('#app_date_current').html('Yesterday');
        $('#app_date_current1').html('Yesterday');
        $('#app_date_current2').html('Yesterday');
        $('#app_date_current3').html('Yesterday');
    }
    if ($('#app_date_current').html() == $('#hndtomorrow').val()) {
        $('#app_date_current').html('Tomorrow');
        $('#app_date_current1').html('Tomorrow');
        $('#app_date_current2').html('Tomorrow');
        $('#app_date_current3').html('Tomorrow');
    }
    labcount();
    //labAdvice();
}

function labcount() {
    //$('.testcount').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'LCO'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    var tr = '';
                    if (data.length > 0) {
                        console.log(data);
                        for (var i = 0; i < data.length; i++) {
                            //var adviceCount = (data[0].advicecount) + (data[0].ipAdviceCount);
                            $('#AdviceCount').html(data[0].advicecount);
                            $('#pendingorder').html(data[0].pending_order + '/<span>' + data[0].completed_order + '</span>');
                            $('#pendingjob').html(data[0].pending_job + '/<span>' + data[0].completed_job + '</span>');
                            $('#lab_data_flag').val(data[0].lab_data_flag);
                        }
                    }

                }
                else {
                    console.log(data);
                }
            }
            labAdvice();
            laborderview();
            jobview();
            // $('.testcount').hide();
        }
    });
}

function labAdvice() {
    //$('.load-labadvice').show();
    $('#loaderimg').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'S'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labadvicetable').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#labadvicetable').html(Norecord);
            }
            else {

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

                    var tr = '';
                    var Action = '';
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            var first_name = data1[i].first_name;
                            var order_status = '', order_id = '';
                            if (data1[i].order_id == null || data1[i].order_id == '') {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-submit btn-xs mt5"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';
                                order_status = '-';
                                order_id = '-';
                            }
                            else if (data1[i].order_status == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Pending)\")\'; ><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                order_status = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                                order_id = data1[i].order_id;
                            }
                            else if (data1[i].order_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                order_status = '<a href="javascript:void(0)" style="color:green;">Completed</a>';
                                order_id = data1[i].order_id;
                            }
                            else if (data1[i].order_status == 3) {
                                //Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                Action = '<span style="color:red;">-</span>';
                                order_status = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                order_id = data1[i].order_id;
                            }
                            tr = tr + '<tr><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</span></td><td>' + data1[i].doctor_name + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + data1[i].created_on + '</td><td>' + data1[i].rowcount + '</td><td>' + order_id + '</td><td>' + order_status + '</td><td>' + Action + '</td></tr>';
                        }
                        var head = '<thead><tr><th>Patient Name</th><th>Doctor Name</th><th>Mobile No</th><th>Visit Date</th><th>No. of Tests</th><th>Order No</th><th>Status</th><th>Action</th></tr></thead>';
                        var Sbody = '<tbody>';
                        var Ebody = '</tbody>';
                        $('#labadvicetable').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#labadvicetable').html(Norecord);
                    }

                }
                else {
                    console.log(data);
                }

            }
            $('#loaderimg').hide();

            LoadIPLabAdvice();
        }
    });
}

function LoadIPLabAdvice() {
    $('#loaderimg').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'IPS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#iplabadvicetable').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#iplabadvicetable').html(Norecord);
            }
            else {

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

                    var tr = '';
                    var Action = '';
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            var first_name = data1[i].first_name;

                            //if (data1[i].ip_lab_Investigations_status == 1) {
                            //    Action = '<a href="javascript:void(0)" onclick=\'BookIPLabOrder(\"' + data1[i].patient_id + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].prescription_scan_id + '\",\"' + data1[i].suggested_date + '\")\'; >Convert To Order</a>';

                            //}
                            //else if (data1[i].ip_lab_Investigations_status == 3) {
                            //    Action = '<a href="javascript:void(0)" style="color:red;">Order Placed</a>';

                            //}
                            //else if (data1[i].ip_lab_Investigations_status == 4) {
                            //    Action = '<a href="javascript:void(0)" style="color:Green;">Order Completed</a>';
                            //}

                            tr = tr + '<tr data-toggle="collapse" data-target="#ipdemo_' + i + '" class="accordion-toggle"><td><button onclick=ViewIPAdviceDetails("ipdemo_' + i + '","' + data1[i].visit_report_id + '"); class="part-payment btn btn-primary btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</span></td><td>' + data1[i].doctor_name + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + data1[i].visit_report_id + '</td><td>' + data1[i].rowcount + '</td></tr><tr class="hiddenRow accordian-body collapse" id="ipdemo_' + i + '"></tr>';
                        }
                        var head = '<thead><tr><th></th><th>Patient Name</th><th>Doctor Name</th><th>Moblie No</th><th>IP Visit No</th><th>No. of Tests</th></tr></thead>';
                        var Sbody = '<tbody>';
                        var Ebody = '</tbody>';
                        $('#iplabadvicetable').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#iplabadvicetable').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('#loaderimg').hide();
        }
    });
}

function ViewIPAdviceDetails(val, val2) {
    debugger;
    var htmlid = val;
    var visit_report_id = val2;
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'IPLV',
        visit_report_id: visit_report_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {

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

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

                    var trhead = '<td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><th>Lab Prescription</th><th>Suggested Date</th><th>Order ID</th><th>Action</th></tr></thead><tbody>';
                    var tr = '', Action = '', type;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            if (data1[i].ip_lab_Investigations_status == 1) {
                                Action = '<a href="javascript:void(0)" onclick=\'BookIPLabOrder(\"' + data1[i].patient_id + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].prescription_scan_id + '\",\"' + data1[i].Sdate + '\")\'; >Convert To Order</a>';

                            }
                            else if (data1[i].ip_lab_Investigations_status == 3) {
                                Action = '<a href="javascript:void(0)" style="color:red;">Order Placed</a>';

                            }
                            else if (data1[i].ip_lab_Investigations_status == 4) {
                                Action = '<a href="javascript:void(0)" style="color:Green;">Order Completed</a>';
                            }
                            tr = tr + '<tr><td>' + data1[i].lab_prescription + '</td><td>' + data1[i].suggested_date + '</td><td>' + data1[i].order_id + '</td><td>' + Action + '</td></tr>'
                        }
                        var trend = '</tbody></table></div></td>';
                        $('#' + htmlid).html(trhead + tr + trend);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}
function BookIPLabOrder(patient_id, ip_visit_report_id, prescription_scan_id, suggested_date) {
    var job_due_date = suggested_date.split('T');
    job_due_date = job_due_date[0];
    
    var Template = {
        lab_id: $('#lab_id').val(),
        patient_id: patient_id,
        visit_report_id: ip_visit_report_id,
        doctor_id: $('#HiddenDoctorID').val(),
        order_status: 1,
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'IPO',
        job_due_date: job_due_date,
        job_status: 1,
        prescription_scan_id: prescription_scan_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {

            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something wrong! Try again');
            }
            else {

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

                    if (data[0].test_p_status == "0") {
                        toastr.warning("No parameters Available for this test, Please add Parameters to this test");
                        $('#loaderimg').hide();
                    }
                    else {
                        //var order_id = data[0].P_order_id;
                        LoadIPLabAdvice();
                        LoadIPOrderView();
                        jobview();
                    }
                }
                else {
                    console.log(data);
                }

                
            }
           
        }
    });
}

function laborderview() {
    // $('.load-overview').show();
    $('#loaderimg').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'LOV'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labJoblist_head').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#labJoblist_head').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        console.log(data1);
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            if (data1[i].invoice_id == null || data1.invoice_id == '') {
                                invoiceAmt = '<span> - </span><br/><span></span>';
                                invoicedue = '<span style="color:yellow;"> - </span>';
                            }
                            else {
                                if (data1[i].balance_amount > 0) {
                                    var img = '<i class="fa fa-money" area-hidden="true"></i>';
                                    //invoicedue = '<span style="color:red;"><i class="fa fa-inr">' + data1[i].balance_amount + '</i><a id="btnLabPayment" data-toggle="modal" data-target="#collectPayment">' + img + '</a></span>';
                                    invoicedue = '<span style="color:red;" class="btn pt-0 pb-0"><a id="btnLabPayment" onclick=\'collectpayment(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\")\' data-toggle="modal" data-target="#collectPayment"><span class="edit btn btn-primary btn-xs mr-15">' + img + '</span><i class="fa fa-inr">' + data1[i].balance_amount + '</i> </a></span>';
                                }
                                else {
                                    var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                    if (data1[i].coupon_id != "" && data1[i].coupon_id != null) {
                                        img = '<i class="fa fa-check" aria-hidden="true"></i> Coupon';
                                    }
                                    invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                }
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].invoice_amount + '</i></span>';
                            }

                            var Order_status = '';
                            if (data1[i].order_id == null || data1[i].order_id == '') {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-submit btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';

                            }
                            else if (data1[i].order_status == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Pending)\")\';><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else if (data1[i].order_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Completed)\" ,\"' + data1[i].invoice_amount + '\",\"' + data1[i].balance_amount + '\")\';>Show Order</a>&nbsp;<button onclick=lab_order_print("' + data1[i].order_id + '");><span class="fa fa-print"></span></button>';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                            }
                            else if (data1[i].order_status == 3) {
                                //  Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                Action = '<span style="color:red;">-</span>';
                                Order_status = '<a herf="javascript:void(0)" style="color:red;">Cancelled</a>';
                            }
                            if (data1[i].payment_status == 'Success' && data1[i].order_status == 1) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }
                            else if (data1[i].payment_status == 'Success' && data1[i].order_status == 2) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }

                            tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="part-payment btn btn-primary btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>' + data1[i].order_id + '</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</td><td>' + data1[i].phone_number_1 + '</td><td>' + Order_status + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td><td>' + Action + '</td><td><button onclick=files_lab("' + data1[i].I2H_order_id + '")  data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'


                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';

                        }
                        $('#labJoblist_body').html(tr);
                        $('#labJoblist_head').empty();
                        var head = ('<thead><tr><th>&nbsp;</th><th>Order No</th><th>Order Date</th><th>Name</th><th>Mobile No</th><th>Status</th><th>Invoice Amount</th><th>Payment Due</th><th>Action</th><th>Files</th></tr></thead>');
                        var Sbody = ('<tbody id=labJoblist_body>');
                        var Ebody = ('</tbody>');
                        $('#labJoblist_head').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#labJoblist_head').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }
            //$('.load-overview').hide();
            $('#loaderimg').hide();
        }
    });

    LoadIPOrderView();
}

function LoadIPOrderView() {
    $('#loaderimg').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'IPOV'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#IPlabJoblist_head').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#IPlabJoblist_head').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        console.log(data1);
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            if (data1[i].invoice_id == null || data1.invoice_id == '') {
                                invoiceAmt = '<span> - </span><br/><span></span>';
                                invoicedue = '<span style="color:yellow;"> - </span>';
                            }
                            else {
                                if (data1[i].balance_amount > 0) {
                                    var img = '<i class="fa fa-money" area-hidden="true"></i>';
                                    //invoicedue = '<span style="color:red;"><i class="fa fa-inr">' + data1[i].balance_amount + '</i><a id="btnLabPayment" data-toggle="modal" data-target="#collectPayment">' + img + '</a></span>';
                                    invoicedue = '<span style="color:red;" class="btn"><a id="btnLabPayment" onclick=\'collectpayment(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\")\' data-toggle="modal" data-target="#collectPayment"><span class="edit btn btn-primary btn-xs mr-15">' + img + '</span><i class="fa fa-inr">' + data1[i].balance_amount + '</i> </a></span>';
                                }
                                else {
                                    var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                    if (data1[i].coupon_id != "" && data1[i].coupon_id != null) {
                                        img = '<i class="fa fa-check" aria-hidden="true"></i> Coupon';
                                    }
                                    invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                }
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].invoice_amount + '</i></span>';
                            }

                            var Order_status = '';
                            if (data1[i].order_id == null || data1[i].order_id == '') {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-submit btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';

                            }
                            else if (data1[i].order_status == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Pending)\")\';><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else if (data1[i].order_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Completed)\" ,\"' + data1[i].invoice_amount + '\",\"' + data1[i].balance_amount + '\")\';>Show Order</a>&nbsp;<button onclick=lab_order_print("' + data1[i].order_id + '");><span class="fa fa-print"></span></button>';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                            }
                            else if (data1[i].order_status == 3) {
                                //  Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                Action = '<span style="color:red;">-</span>';
                                Order_status = '<a herf="javascript:void(0)" style="color:red;">Cancelled</a>';
                            }
                            if (data1[i].payment_status == 'Success' && data1[i].order_status == 1) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }
                            else if (data1[i].payment_status == 'Success' && data1[i].order_status == 2) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }

                            tr = tr + '<tr data-toggle="collapse" data-target="#iporderdemo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("iporderdemo_' + i + '","' + data1[i].order_id + '",""); class="part-payment btn btn-primary btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>' + data1[i].order_id + '</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</td><td>' + data1[i].phone_number_1 + '</td><td>' + Order_status + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td><td>' + Action + '</td></tr><tr class="hiddenRow accordian-body collapse" id="iporderdemo_' + i + '"></tr>'

                        }
                        $('#IPlabJoblist_body').html(tr);
                        $('#IPlabJoblist_head').empty();
                        var head = ('<thead><tr><th>&nbsp;</th><th>Order No</th><th>Order Date</th><th>Name</th><th>Mobile No</th><th>Status</th><th>Invoice Amount</th><th>Payment Due</th><th>Action</th></tr></thead>');
                        var Sbody = ('<tbody id=IPlabJoblist_body>');
                        var Ebody = ('</tbody>');
                        $('#IPlabJoblist_head').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#IPlabJoblist_head').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }
            //$('.load-overview').hide();
            $('#loaderimg').hide();
        }
    });
}

function lab_order_print(order_id) {
    window.open('/PatientDashboard/labresult_order?orderid=' + order_id + '&doctorId=' + $('#HiddenDoctorID').val());
}


function orderdetails(val, val2) {
    //var val1 = val.split(',');
    var htmlid = val;
    var orderid = val2;
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'LOD',
        order_id: orderid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var trhead = '<td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><th>Job ID</th><th>Type</th><th>Test Name</th><th>Cost(Rs)</th><th>Date</th></tr></thead><tbody>';
                    var tr = '', Action = '', type;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            if (data[i].test_type == "1") type = "Test";
                            else type = "Panel";
                            tr = tr + '<tr><td>' + data[i].job_id + '</td><td>' + type + '</td><td>' + data[i].test_name + '</td><td>' + data[i].order_cost + '</td><td>' + data[i].job_add_date + '</td></tr>'
                        }
                        var trend = '</tbody></table></div></td>';
                        $('#' + htmlid).html(trhead + tr + trend);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function jobview() {
    // $('.load-jobview').show();
    $('#loaderimg').show();
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'JSD',
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#Jobdetails').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#Jobdetails').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        console.log(data1);
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc, jobstatus = '', duedate = '-';
                            debugger;
                            if (data1[i].job_due_date == null) {
                                duedate = '-';
                            }
                            else {
                                duedate = data1[i].job_due_date;
                            }

                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            debugger;
                            if (data1[i].invoice_id != null && data1[i].invoice_id != '' && data1[i].invoice_status == 3) {
                                if (data1[i].job_status == null || data1[i].job_status == '') {
                                    Action = '<a href="javascript:void(0)" class="btn btn-submit btn-xs" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\","(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';
                                }
                                else if (data1[i].job_status == 1) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                                }
                                else if (data1[i].job_status == 2) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:green;">Completed</a>';
                                }
                                else if (data1[i].job_status == 3) {
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                            }
                            else if (data1[i].isIP == 1 && data1[i].job_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                jobstatus = '<a href="javascript:void(0)" style="color:red;">Completed</a>';
                            }
                            else if (data1[i].isIP == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else if (data1[i].payment_status == "Success" && data1[i].job_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                jobstatus = '<a href="javascript:void(0)" style="color:red;">Completed</a>';
                            }
                            else if (data1[i].payment_status == "Success") {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                            }


                            else {
                                if (data1[i].job_status == 3) {
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                                else {
                                    Action = '<span style="color:red;">payment not completed</span>';
                                }
                            }
                            //tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '</td><td>' + data1[i].patient_id + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + Action + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'
                            tr = tr + '<tr><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</span></td><td>' + data1[i].job_id + '<span style="color: #999; font-size: 11px;">(' + data1[i].order_id + ')</span>' + '</td><td>' + data1[i].test_name + '</td><td>' + duedate + '</td><td>' + jobstatus + '</td><td><ul class="list-inline"><li>' + Action + '</li></ul></td></tr>';
                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';
                        }
                        var head = '<thead><tr><th>Patient Name</th><th>Job ID</th><th>Test Name</th><th>Due date</th><th>Status</th><th>Action</th></tr></thead>';
                        var Sbody = '<tbody>';
                        var Ebody = '</tbody>'
                        $('#Jobdetails').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#Jobdetails').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }

               
            }
            // $('.load-jobview').hide();
            $('#loaderimg').hide();
        }
    });
}

function onlabadvice(first_name, phone_number_1, patient_id, photoSrc, visit_report_id, order_id, OrderStatus, invoice_amount, balance_amount) {
    debugger;
    $('#labparameterss').hide();
    $('#MpatientPhoto').html('<img class="img-responsive text-center imgphoto" src=' + photoSrc + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>')
    $('#MPatient_id').html(patient_id);
    $('#MPatientName').html(first_name);
    $('#MphoneNo').html(phone_number_1);
    $('#labvid').html(visit_report_id);
    $('#Morderstatusid').html(OrderStatus);
    if (order_id == "null") {
        $('#Morderid').html('-');
        $('#Cancelorder').hide();
    } else {
        $('#Morderid').html(order_id);
        order_id = $.trim(order_id);
        $('#Cancelorder').html('<i class="fa fa-trash" onclick=cancelorder("' + order_id + '");></i>');
        $('#Cancelorder').show();
    }
    getjobdetails(visit_report_id, order_id);
}

function getjoborderload(visit_report_id, order_id) {
    var Template = {
        order_id: order_id,
        visit_report_id: visit_report_id,
        patient_id: $('#MPatient_id').html(),
        Dml_Indicator: 'JS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            debugger;
            $('#laborderjob_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#laborderjob').hide();
                $('#modalLabPayment').hide();
                $('#modalLabInvoice').hide();
            }
            else {

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

                    var totcost = 0, totamount = 0;
                    var tr = '';
                    var j = 0;
                    if (data.length > 0) {
                        $('#DoctorName').html(data[0].first_name);
                        if (data[0].invoice_id != '' && data[0].invoice_id != null) {

                            //$('#Morderstatusid').html('(Completed)')
                            $('#MorderPrint').show();
                            $('#MorderPrint').html('<a href="javascript:void(0);" onclick=orderprint("' + data[0].invoice_id + '")><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>');
                            $('#btnLabCostSave').hide();
                            $('#btnLabCoup').hide();
                            $('#btnaddnewtest').hide();
                            $('#labtestjob').hide();
                            $('#Prescriptionhead').hide();
                            $('#paymentdetails').show();
                            $('#modalLabInvoice').hide();
                            $('#paymentdetails').empty();
                            $('#modalLabPayment').show();
                            $('#paymentdetails').html('<tr class="text-yw"><td>Invoice Amt</td><td>Balance Amt</td></tr><tr class="text-wb"><td>' + data[0].invoice_amount + '</td><td>' + data[0].balance_amount + '</td></tr>');
                            $('#invoice_status').val('1');
                            $('#Cancelorder').hide();
                        }
                        else {
                            $('#MorderPrint').hide();
                            $('#labtestjob').show();
                            $('#modalLabInvoice').show();
                            $('#btnLabCostSave').show();
                            $('#btnLabCoup').show();
                            $('#btnaddnewtest').show();
                            $('#paymentdetails').hide();
                            $('#modalLabPayment').hide();
                            $('#invoice_status').val('0');
                        }
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            var job_cost = '', discount = '', job_amount = '';
                            if (data[i].job_cost == '' || data[i].job_cost == null) {
                                job_cost = 0;
                            }
                            else {
                                if (data[i].job_status == 3) {
                                    job_cost = 0;
                                }
                                else {
                                    job_cost = data[i].job_cost;
                                    totcost = parseFloat(totcost) + parseFloat(job_cost)
                                }
                            }
                            if (data[i].discount == '' || data[i].discount == null) {
                                discount = 0;
                            }
                            else {
                                if (data[i].job_status == 3) {
                                    discount = 0;
                                }
                                else {
                                    discount = data[i].discount;
                                }
                            }
                            if (data[i].job_amount == '' || data[i].job_amount == null) {
                                job_amount = job_cost;
                                totamount = parseFloat(totamount) + parseFloat(job_amount)
                            }
                            else {
                                job_amount = data[i].job_amount;
                                totamount = parseFloat(totamount) + parseFloat(job_amount)
                            }
                            if (data[i].job_status == 1) {
                                //<a href="javascript:void(0);" onclick=ontestid("' + data[i].test_id + '","' + data[i].job_id + '","' + data[i].order_id + '","(Pending)")>+ Result </a>;
                                tr = tr + '<tr><td>' + data[i].job_id + '</td><td>' + data[i].test_name + '</td><td>' + data[i].job_due_date + '</td><td><div class="col-md-12 padding0"><button class="delete btn btn-danger btn-xs" data-toggle="popover" title="Delete" onclick=canceljob("' + data[i].job_id + '");><i class="fa fa-trash" aria-hidden="true"></i></button></div></td><td><input type="text" class="edf sm-field" name="cost_val" onkeyup="sixcomotwo(this.id);costval(this.id);" value="' + job_cost + '" id="cost_val_' + j + '" /></td><td><input type="text" class="edf sm-field mr-15" onkeyup=disval(this.id); value="' + discount + '" name="dis_val" id="dis_val_' + j + '" /><select class="edf xs-field" onchange=labDisDrop(this.id); id="labDisDrop_' + j + '" name="labDisDrop"><option value="1">%</option><option value="2">₹</option></select></td><td><select class="edf sm-field" onchange=taxval(this.id); name="tax_val" id="tax_val_' + j + '" ><option value=1>0%</option><option value=2>5%</option><option value=3>12%</option><option value=4>18%</option><option value=5>28%</option></select></td><td class="text-right"><input type="text" class="edf sm-field" readonly name="tax_val"  value="' + job_amount + '"  id="amt_val_' + j + '" /></td></tr>';
                                $('#Morderstatusid').html('(Pending)');
                            }
                            else if (data[i].job_status == 2) {
                                //<a href="javascript:void(0);" onclick=completedtestid("' + data[i].test_id + '","' + data[i].job_id + '","' + data[i].order_id + '","(Completed)")>Show Result </a>
                                tr = tr + '<tr><td>' + data[i].job_id + '</td><td>' + data[i].test_name + '</td><td>' + data[i].job_due_date + '</td><td><div class="col-md-12 padding0"><i class="fa fa-print" onclick=jobprint("' + data[i].job_id + '","' + $('#HiddenDoctorID').val() + '");></i></div></td><td><input type="text" class="edf sm-field" name="cost_val" onkeyup="sixcomotwo(this.id); costval(this.id);" value="' + job_cost + '" id="cost_val_' + j + '" /></td><td><input type="text" class="edf sm-field mr-15" onkeyup=disval(this.id); value="' + discount + '" name="dis_val" id="dis_val_' + j + '" /><select class="edf xs-field" onchange=labDisDrop(this.id); id="labDisDrop_' + j + '" name="labDisDrop"><option value="1">%</option><option value="2">₹</option></select></td><td><select class="edf sm-field" onchange=taxval(this.id); name="tax_val" id="tax_val_' + j + '" ><option value=1>0%</option><option value=2>5%</option><option value=3>12%</option><option value=4>18%</option><option value=5>28%</option></select></td><td class="text-right"><input type="text" class="edf sm-field" readonly name="tax_val"  value="' + job_amount + '"  id="amt_val_' + j + '" /></td></tr>';
                                $('#Cancelorder').hide();

                            }
                            else if (data[i].job_status == 3) {
                                tr = tr + '<tr><td>' + data[i].job_id + '</td><td>' + data[i].test_name + '</td><td>' + data[i].job_due_date + '</td><td><div class="col-md-12 padding0">Cancelled</div></td><td><input type="text" class="edf sm-field" name="cost_val" onkeyup="sixcomotwo(this.id); costval(this.id);" value="' + job_cost + '" id="cost_val_' + j + '" /></td><td><input type="text" class="edf sm-field mr-15" onkeyup=disval(this.id); value="' + discount + '" name="dis_val" id="dis_val_' + j + '" /><select class="edf xs-field" onchange=labDisDrop(this.id); id="labDisDrop_' + j + '" name="labDisDrop"><option value="1">%</option><option value="2">₹</option></select></td><td><select class="edf sm-field" onchange=taxval(this.id); name="tax_val" id="tax_val_' + j + '" ><option value=1>0%</option><option value=2>5%</option><option value=3>12%</option><option value=4>18%</option><option value=5>28%</option></select></td><td class="text-right"><input type="text" class="edf sm-field" readonly name="tax_val"  value="' + job_amount + '"  id="amt_val_' + j + '" /></td></tr>';
                            }

                        }
                        $('#laborderjob').show();
                        $('#laborderjob_body').append(tr);
                        $('#laborderjob_footer').empty();
                        $('#laborderjob_footer').append('<tr><td></td><td></td><td></td><td></td><td>' + parseFloat(totcost).toFixed(2) + '</td><td></td><td></td><td>' + parseFloat(totamount).toFixed(2) + '</td></tr>');
                        var j = 0;

                        for (var i = 0; i < data.length; i++) {
                            j++;
                            var discount_type = data[i].discount_type;
                            var job_tax = data[i].job_tax
                            if (discount_type == '' || discount_type == null) {
                                discount_type = 1;
                            }
                            if (job_tax == '' || job_tax == null) {
                                job_tax = 1;
                            }
                            $('#labDisDrop_' + j).val(discount_type);
                            $('#tax_val_' + j).val(job_tax);
                        }
                        //$("#laborderjob_body").find("input,textarea,select").attr("disabled", "disabled");

                    }
                    else {
                        $('#laborderjob').hide();
                        $('#modalLabPayment').hide();
                        $('#modalLabInvoice').hide();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


function orderprint(order_id, doctorId) {
    window.open('/PatientDashboard/labinvoice?orderid=' + order_id + '&doctorId=' + $('#HiddenDoctorID').val());
}

function canceljob(val) {
    if ($('#invoice_status').val() == '0' || $('#invoice_status').val() == '') {
        var Template = {
            job_id: val,
            Dml_Indicator: 'JC'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

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

                        var visit_report_id = $('#labvid').html();
                        var order_id = $('#Morderid').html();
                        getjoborderload(visit_report_id, order_id);
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
    else {
        toastr.warning('Invoice already generated. Unable to Delete the test.');

    }
}

function cancelorder(val) {
    var Template = {
        order_id: val,
        Dml_Indicator: 'OC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var visit_report_id = $('#labvid').html();
                    var order_id = $('#Morderid').html();
                    toastr.success('Order has Cancelled Successfully');
                    $('#btncloseX').click();
                }
                else {
                    console.log(data);
                }
                
            }
        }
    });
}

var costtxtid = '';
function costval(id) {
    debugger;
    costid = id;
    var amtval = $('#' + costid).val();
    var costval = id.split('_');
    $('#dis_val_' + costval[2]).val(0);
    $('#tax_val_' + costval[2]).val(1);
    $('#amt_val_' + costval[2]).val(amtval);

    var rowCount = $('#laborderjob_body tr').length;
    var totcost = 0, totamt = 0, totcosts = 0, totamts = 0;
    for (var i = 1; i <= rowCount; i++) {
        totcost = $('#cost_val_' + i).val();
        if (totcost == '' || totcost == null) {

        }
        else {
            totcosts = parseFloat(totcosts) + parseFloat(totcost);
        }
        totamt = $('#amt_val_' + i).val();
        if (totamt == '' || totamt == null) {

        }
        else {
            totamts = parseFloat(totamts) + parseFloat(totamt);
        }
    }
    $('#laborderjob_footer').empty();
    $('#laborderjob_footer').html('<tr><td></td><td></td><td></td><td></td><td>' + totcosts + '</td><td></td><td></td><td>' + totamts + '</td></tr>');

}






function labDisDrop(id) {
    debugger;
    Disid = id;
    //var taxval = $('#' + Disid).val();
    var costid = id.split('_');
    var costval = $('#cost_val_' + costid[1]).val();
    var distype = $('#labDisDrop_' + costid[1]).val();
    var disval = $('#dis_val_' + costid[1]).val();
    var taxval = $('#tax_val_' + costid[1]).val();
    if (distype != null && distype != " ") {
        if (distype == 1) {
            if (disval >= 0 && disval < 100) {
                var amtval = (parseFloat(costval) / 100) * (parseFloat(disval));
                amtval = parseFloat(costval) - parseFloat(amtval);
            }
            else {
                toastr.warning("Enter Valid Discount Percentage");
                $('#' + Disid).val(0);
            }
        }
        else {
            var disval1 = disval.trim();
            if (parseInt(costval) > parseInt(disval1)) {
                var amtval = parseFloat(costval) - parseFloat(disval1);
            }
            else {
                toastr.warning("Enter Valid Discount Amount");
                $('#' + Disid).val(0);

            }
        }
    }
    else {
        alert("Please Select Discount Type");
        $('#amt_val_' + costid[2]).val(0);
        $('#' + Disid).val(0);
        $('#cost_val_' + costid[2]).val(costval);
    }


    if (taxval == 1) {
        amtval = amtval + (amtval * 0.00);
    }
    else if (taxval == 2) {
        amtval = amtval + (amtval * 0.05);
    }
    else if (taxval == 3) {
        amtval = amtval + (amtval * 0.12);
    }
    else if (taxval == 4) {
        amtval = amtval + (amtval * 0.18);
    }
    else if (taxval == 5) {
        amtval = amtval + (amtval * 0.28);
    }

    amtval = amtval.toFixed(2);
    $('#amt_val_' + costid[1]).val(amtval);

    //$('#laborderjob_body').find("input").each(function () {
    //    // get the current row
    //    debugger;
    //    var currentRow = $(this).closest("tr");

    //    var col1 = currentRow.find("td:eq(5)").val(); // get current row 1st TD value
    //    //var col2 = currentRow.find("td:eq(5)").text(); // get current row 2nd TD
    //    //var col3 = currentRow.find("td:eq(7)").text(); // get current row 3rd TD
    //    var data = col1 ;

    //    alert(data);
    //});

    var rowCount = $('#laborderjob_body tr').length;
    var totcost = 0, totamt = 0, totcosts = 0, totamts = 0;
    for (var i = 1; i <= rowCount; i++) {
        totcost = $('#cost_val_' + i).val();
        if (totcost == '' || totcost == null) {

        }
        else {
            totcosts = parseFloat(totcosts) + parseFloat(totcost);
            totcosts = totcosts.toFixed(2);
        }
        totamt = $('#amt_val_' + i).val();
        if (totamt == '' || totamt == null) {

        }
        else {
            totamts = parseFloat(totamts) + parseFloat(totamt);
            totamts = totamts.toFixed(2);
        }
    }
    $('#laborderjob_footer').empty();
    $('#laborderjob_footer').html('<tr><td></td><td></td><td></td><td></td><td>' + totcosts + '</td><td></td><td></td><td>' + totamts + '</td></tr>');



}
function disval(id) {
    debugger;
    Disid = id;
    var disval = $('#' + Disid).val();
    var costid = id.split('_');
    var costval = $('#cost_val_' + costid[2]).val();
    var distype = $('#labDisDrop_' + costid[2]).val();
    var taxval = $('#tax_val_' + costid[2]).val();
    if (distype != null && distype != " ") {
        if (distype == 1) {
            if (disval >= 0 && disval < 100) {
                var amtval = (parseFloat(costval) / 100) * (parseFloat(disval));
                amtval = parseFloat(costval) - parseFloat(amtval);
            }
            else {
                toastr.warning("Enter Valid Discount Percentage");
                $('#' + Disid).val(0);
            }
        }
        else {
            var disval1 = disval.trim();
            if (parseInt(costval) > parseInt(disval1)) {
                var amtval = parseFloat(costval) - parseFloat(disval1);
            }
            else {
                toastr.warning("Enter Valid Discount Amount");
                $('#' + Disid).val(0);

            }
        }
    }
    else {
        toastr.warning("Please Select the Discount Type");
        $('#amt_val_' + costid[2]).val(0);
        $('#' + Disid).val(0);
        $('#cost_val_' + costid[2]).val(costval);
    }


    if (taxval == 1) {
        amtval = amtval + (amtval * 0.00);
    }
    else if (taxval == 2) {
        amtval = amtval + (amtval * 0.05);
    }
    else if (taxval == 3) {
        amtval = amtval + (amtval * 0.12);
    }
    else if (taxval == 4) {
        amtval = amtval + (amtval * 0.18);
    }
    else if (taxval == 5) {
        amtval = amtval + (amtval * 0.28);
    }

    amtval = amtval.toFixed(2);
    if (amtval == "NaN") {
        amtval = 0;
    }
    $('#amt_val_' + costid[2]).val(amtval);


    var rowCount = $('#laborderjob_body tr').length;
    var totcost = 0, totamt = 0, totcosts = 0, totamts = 0;
    for (var i = 1; i <= rowCount; i++) {
        totcost = $('#cost_val_' + i).val();
        if (totcost == '' || totcost == null) {

        }
        else {
            totcosts = parseFloat(totcosts) + parseFloat(totcost);
        }
        totamt = $('#amt_val_' + i).val();
        if (totamt == '' || totamt == null) {

        }
        else {
            totamts = parseFloat(totamts) + parseFloat(totamt);
        }
    }
    $('#laborderjob_footer').empty();
    $('#laborderjob_footer').html('<tr><td></td><td></td><td></td><td></td><td>' + totcosts + '</td><td></td><td></td><td>' + totamts + '</td></tr>');
}
function taxval(id) {
    Disid = id;
    //var disval = $('#' + Disid).val();
    var taxval = $('#' + Disid).val();
    var costid = id.split('_');
    var costval = $('#cost_val_' + costid[2]).val();
    var distype = $('#labDisDrop_' + costid[2]).val();
    var disval = $('#dis_val_' + costid[2]).val();
    var taxval = $('#tax_val_' + costid[2]).val();
    if (distype != null && distype != " ") {
        if (distype == 1) {
            if (disval >= 0 && disval < 100) {
                var amtval = (parseFloat(costval) / 100) * (parseFloat(disval));
                amtval = parseFloat(costval) - parseFloat(amtval);
            }
            else {
                toastr.warning("Enter the Valid Discount Percentage");
                $('#' + Disid).val(0);
            }
        }
        else {
            var disval1 = disval.trim();
            if (parseInt(costval) > parseInt(disval1)) {
                var amtval = parseFloat(costval) - parseFloat(disval1);
            }
            else {
                toastr.warning("Enter the Valid Discount Amount");
                $('#' + Disid).val(0);

            }
        }
    }
    else {
        toastr.warning("Please Select the Discount Type");
        $('#amt_val_' + costid[2]).val(0);
        $('#' + Disid).val(0);
        $('#cost_val_' + costid[2]).val(costval);
    }

    if (taxval == 1) {
        amtval = amtval + (amtval * 0.00);
    }
    else if (taxval == 2) {
        amtval = amtval + (amtval * 0.05);
    }
    else if (taxval == 3) {
        amtval = amtval + (amtval * 0.12);
    }
    else if (taxval == 4) {
        amtval = amtval + (amtval * 0.18);
    }
    else if (taxval == 5) {
        amtval = amtval + (amtval * 0.28);
    }

    amtval = amtval.toFixed(2);
    $('#amt_val_' + costid[2]).val(amtval);

    var rowCount = $('#laborderjob_body tr').length;
    var totcost = 0, totamt = 0, totcosts = 0, totamts = 0;
    for (var i = 1; i <= rowCount; i++) {
        totcost = $('#cost_val_' + i).val();
        if (totcost == '' || totcost == null) {

        }
        else {
            totcosts = parseFloat(totcosts) + parseFloat(totcost);
        }
        totamt = $('#amt_val_' + i).val();
        if (totamt == '' || totamt == null) {

        }
        else {
            totamts = parseFloat(totamts) + parseFloat(totamt);
        }
    }
    $('#laborderjob_footer').empty();
    $('#laborderjob_footer').html('<tr><td></td><td></td><td></td><td></td><td>' + totcosts + '</td><td></td><td></td><td>' + totamts + '</td></tr>');

}

function jobprint(job_id, doctorId) {
    window.open('/PatientDashboard/labresult?jobid=' + job_id + '&doctorId=' + doctorId);
}

function completedtestid(first_name, phone_number_1, patient_id, photoSrc, visit_report_id, order_id, job_id, test_id, jobstatus) {
    $('#patientdetails').show();
    var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
    $('#mparamPrint1').html(print);
    $('#labparameterss').show();
    $('#mparamPrint1').val(job_id);
    $('#Mjobid').html(job_id);
    $('#MJobstatusid').html(jobstatus);


    //$('#labparameterss').hide();
    $('#MpatientPhoto_1').html('<img class="img-responsive text-center imgphoto" src=' + photoSrc + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>')
    $('#MPatient_id_1').html(patient_id);
    $('#MPatientName_1').html(first_name);
    $('#MphoneNo_1').html(phone_number_1);
    debugger;
    if (visit_report_id != null && visit_report_id != "" && visit_report_id != "null") {
        $('#labvid_1').html(visit_report_id);
    }
    else { $('#labvid_1').html('-'); }


    var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
    $('#mparamPrint1').html(print);
    //$("button").attr("aria-expanded", "false");
    //$('#labparameterss').show();
    //$('#Mjobid').html(job_id);
    //$('#mparamPrint1').val(job_id);
    //$('#MJobstatusid').html(jobstatus);
    //$('#myResultviewModal').animate({ scrollTop: 600 }, 'slow');
    //$('#labJob-section').removeClass('in');

    var Template = {
        order_id: order_id,
        job_id: job_id,
        added_by: $('#HiddenDoctorID').val(),
        test_id: test_id,
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'PIS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labParameters_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    console.log(data);
                    var tr = '', observation = '', reference_value = '', unit = '';
                    var j = 0;

                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            if (data[i].observation == null || data[i].observation == '') {
                                observation = '';
                            }
                            else {
                                observation = data[i].observation;
                            }
                            if (data[i].reference_value == null || data[i].reference_value == '') {
                                reference_value = '';
                            }
                            else {
                                reference_value = data[i].reference_value;
                            }
                            if (data[i].unit == null || data[i].unit == '') {
                                unit = '';
                            }
                            else {
                                unit = data[i].unit;
                            }
                            if (data[i].result_id == null || data[i].result_id == '') {

                            }
                            else {
                                tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + reference_value + '</td><td>' + unit + '</td></tr>';
                            }
                        }
                        $('#DoctorName_1').html(data[0].doctor_name);
                        if (data[0].conclusion == null || data[0].conclusion == "") $('#txtconclusion').val('');
                        else $('#txtconclusion').val(data[0].conclusion);
                        //$('#txtconclusion').val(data[0].conclusion);
                        $('#labParameters_body').html(tr);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });

}


//ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"(Your Order has not been placed yet)\")
function ontestid(first_name, phone_number_1, patient_id, photoSrc, visit_report_id, order_id, job_id, test_id, jobstatus) {
    debugger;
    $('#patientdetails').show();
    $('#labParameters_body').empty();
    var print = '<a href=javascript:void(0); onclick=jobprint("' + job_id + '","' + $('#HiddenDoctorID').val() + '");><span class="f14" role="button" data-backdrop="static" data-keyboard="false"><i class="fa fa-print"></i>Print</span></a>';
    $('#mparamPrint1').html(print);
    $('#labparameterss').show();
    $('#mparamPrint1').val(job_id);
    $('#Mjobid').html(job_id);
    $('#MJobstatusid').html(jobstatus);
    $('#MpatientPhoto_1').html('<img class="img-responsive text-center imgphoto" src=' + photoSrc + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>')
    $('#MPatient_id_1').html(patient_id);
    $('#MPatientName_1').html(first_name);
    $('#MphoneNo_1').html(phone_number_1);
    if (visit_report_id != null || visit_report_id != "") {
        $('#labvid_1').html(visit_report_id);
    }
    else {
        $('#labvid_1').html('-');
    }
    var Template = {
        order_id: order_id,
        job_id: job_id,
        added_by: $('#HiddenDoctorID').val(),
        test_id: test_id,
        lab_id: $('#lab_id').val(),
        Dml_Indicator: 'PSS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labParameters_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    $('#labParameters_body').empty();
                    var tr = '', observation = '';
                    var j = 0;
                    if (data.length > 0) {
                        console.log(data);
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            if (data[i].observation == null || data[i].observation == '') {
                                observation = '';
                            }
                            else {
                                observation = data[i].observation;
                            }
                            if (data[i].parameter_name == "Triglycerides" && data[i].test_name == "LIPID PROFILE" && data[i].test_id == "L7-T7") {
                                tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" onchange="calculate_vldl();" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td></tr>';
                            }
                            else if ((data[i].parameter_name == "HDL (Low Density Lipoproteins)" || data[i].parameter_name == "Total Cholesterol" || data[i].parameter_name == "VLDL") && data[i].test_name == "LIPID PROFILE" && data[i].test_id == "L7-T7") {
                                tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" onchange="calculate_vldl();" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td></tr>';
                            }

                            else {
                                tr = tr + '<tr><td>' + data[i].result_id + '</td><td>' + data[i].parameter_name + '</td><td><input type="text" class="sm-field" name="obs_val" value="' + observation + '" id="obs_val_' + j + '" /></td><td>' + data[i].reference_value + '</td><td>' + data[i].unit + '</td></tr>';
                            }
                        }
                        $('#test_name').val(data[0].test_name);
                        $('#DoctorName').html(data[0].doctor_name);
                        $('#DoctorName_1').html(data[0].doctor_name);
                        $('#txtconclusion').val(data[0].conclusion);
                        $('#labParameters_body').html(tr);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });

}
function calculate_vldl() {
    debugger;
    var triglycerides = ($('#obs_val_2').val()) / 5;
    if (triglycerides != 0) {
        $('#obs_val_5').val(triglycerides);
    }
        var HDL = $('#obs_val_3').val();
        var tot_cholesterol = $('#obs_val_1').val();
        var vldl = $('#obs_val_5').val();
        if(HDL !=0 && tot_cholesterol !=0 && vldl !=0)
        {
            var LDL = parseInt(vldl) + parseInt(HDL) - parseInt(tot_cholesterol);
            var non_hdl = HDL - tot_cholesterol;
            var ratio = HDL / tot_cholesterol;
            $('#obs_val_4').val(LDL);
            $('#obs_val_6').val(ratio);
            $('#obs_val_7').val(non_hdl);
        }
}
function getjobdetails(visit_report_id, order_id) {
    // $('.load-addjob').show();
    var Template = {
        visit_report_id: visit_report_id,
        Dml_Indicator: 'TS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            $('#labtestjob_body').empty();

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

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

                    var tr = '';
                    var j = 0;
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            tr = tr + '<tr><td>' + j + '</td><td>' + data[i].lab_prescription + '</td><td><div class="col-md-12 padding0"><div class="Labwalkintrigger" data-id=' + data[i].prescription_scan_id + '><span class="hide">Due on </span><input class="Labwalkindatepicker md-field" type="text" value="+ Add to job" id="Labwalkindatepicker' + j + '" style="border:0;background-color:transparent;"><p class="Labwalkinresultsec hide"></p></div></div></td></tr>';
                        }
                        $('#labtestjob_body').html(tr);
                        $('#DoctorName').html(data[0].doctorName);
                        if (data[0].created_on == '' || data[0].created_on == null) {
                            $('#Prescriptionhead').html('');
                        }
                        else {
                            $('#Prescriptionhead').html('Test adviced during visit on ' + data[0].created_on);
                        }
                    }
                }
                else {
                    console.log(data);
                }
                
            }
            //getjobpaneldetails(visit_report_id,j);
            getjoborderload(visit_report_id, order_id);
            $('.load-addjob').hide();
        }
    });
}

//$('.Labwalkindatepicker').change(function () {
//});

//not used
function getjobpaneldetails(visit_report_id, j) {
    var Template = {
        visit_report_id: visit_report_id,
        Dml_Indicator: 'PS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

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

                    if (data.length > 0) {
                        var k = 1;
                        var L = 0;
                        for (var i = 0; i < data.length; i++) {
                            j++;
                            tr = tr + '<tr><td>' + j + '</td><td>' + data[i].test_name + '</td><td><div class="col-md-12 padding0"><div class="Labwalkintrigger"><span class="hide">Due on </span><input class="Labwalkindatepicker md-field" type="text" value="+ Due Date" id="Labwalkindatepicker1" style="border:0;background-color:transparent;"><p class="Labwalkinresultsec hide"> + Results</p></div></div></td><td><input type="text" class="edf sm-field" name="cost_val" value=' + data[i].test_cost + ' id="cost_val_' + j + '" /></td><td><input type="text" class="edf sm-field" name="dis_val" id="dis_val_' + j + '" /><select class="edf xs-field" id="labDisDrop_' + j + '" name="labDisDrop"><option value="1">%</option><option value="2">₹</option></select></td><td><input type="text" class="edf sm-field" name="tax_val" id="tax_val_' + j + '" /></td><td class="text-right">₹ 243</td></tr>';
                        }
                        $('#labtestjob_body').append(tr);
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}


$('#Add_Lab_record').click(function () {
    var patient_id = $('#MPatient_id').html();
    if (patient_id == '' || patient_id == null) {
        $('#PmodalLabPaitentSearch').show();
        $('#PmodalLabPaitentSearch').fadeOut(8000);
        $('#PmodalLabPaitentSearch').html('select the patient');
        $('#modalLabPaitentSearch').focus();
        $('#modalLabPaitentSearch').val('');
        return false;
    }
    var SelFacility = $("#report").val();
    var SelFacilityId = $("#labtype").val();
    var DueDate = $('#txtduedate').val();
    if ($.trim((SelFacility)) == "") {
        $('#Preport').show();
        $('#Preport').fadeOut(8000);
        $('#Preport').html('Enter Test Name');
        $('#report').focus();
        $('#report').val('');
        return false;
    }
    if ($.trim((SelFacilityId)) == 0) {
        $('#Plabtype').show();
        $('#Plabtype').fadeOut(8000);
        $('#Plabtype').html('Select the lab type');
        $('#labtype').focus();
        $('#labtype').val('');
        return false;
    }
    if ($.trim((DueDate)) == "") {
        $('#Ptxtduedate').show();
        $('#Ptxtduedate').fadeOut(8000);
        $('#Ptxtduedate').html('Select the due date');
        $('#txtduedate').focus();
        $('#txtduedate').val('');
        return false;
    }
    $('#loaderimg').show();
    $('#paitentsearchdiv').hide();
    $('#labJobSection').show();
    var duedates = DueDate.split('/');
    duedates = duedates[2] + '-' + duedates[1] + '-' + duedates[0]
    var visit_report_id = $('#labvid').html();
    var Dml_Indicator = '';
    if (visit_report_id == '   NA    ') {
        Dml_Indicator = 'OIWV';
    }
    else {
        Dml_Indicator = 'OI';
    }
    var Template = {
        lab_id: $('#lab_id').val(),
        patient_id: $('#MPatient_id').html(),
        visit_report_id: visit_report_id,
        doctor_id: $('#HiddenDoctorID').val(),
        order_status: 1,
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        test_name: $('#report').val(),
        test_id: $('#labtypetest').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var order_id = '';
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            order_id = data[0].order_id;
                            $('#Morderid').html(order_id);
                            $('#Cancelorder').html('<i class="fa fa-trash" onclick=cancelorder("' + order_id + '");></i>');
                            $('#Cancelorder').show();
                        }
                        var Template = {
                            visit_report_id: $('#labvid').html(),
                            order_id: order_id,
                            test_name: $('#report').val(),
                            job_due_date: duedates,
                            job_status: 1,
                            lab_id: $('#lab_id').val(),
                            Dml_Indicator: 'PLDI',
                            test_id: $('#labtypetest').val()
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Template/lab_home',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(Template),
                            success: function (data) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    var data = data.data;
                                    if (data[0].test_p_status == "1") {
                                        var Template = {
                                            visit_report_id: $('#labvid').html(),
                                            order_id: order_id,
                                            test_name: $('#report').val(),
                                            job_due_date: duedates,
                                            job_status: 1,
                                            lab_id: $('#lab_id').val(),
                                            Dml_Indicator: 'JI',
                                            test_id: $('#labtypetest').val(),
                                            order_details_id: data[0].order_details_id
                                        }
                                        $.ajax({
                                            async: true,
                                            type: 'POST',
                                            url: '/Template/lab_home',
                                            contentType: 'application/json; charset=UTF-8',
                                            data: JSON.stringify(Template),
                                            success: function (data) {
                                                getjobdetails($('#labvid').html(), order_id);
                                                $("#report").val('');
                                                $("#labtype").val('1');
                                                $('#txtduedate').val('');
                                            }
                                        });
                                    }
                                    else {
                                        toastr.warning("No Parameters for this test, Please add Parameters to this test");
                                        $('#loaderimg').hide();
                                    }
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });
                    }
                }
                else {
                    console.log(data);
                }
            }

        }

    });

});


function addtojob(dateval, labprescriptionid)
{
    var job_due_date = dateval.split('/');
    job_due_date = job_due_date[2] + '-' + job_due_date[1] + '-' + job_due_date[0];

    var Template = {
        lab_id: $('#lab_id').val(),
        patient_id: $('#MPatient_id').html(),
        visit_report_id: $('#labvid').html(),
        doctor_id: $('#HiddenDoctorID').val(),
        order_status: 1,
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'OI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            var order_id = '';
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            order_id = data[0].order_id;
                            $('#Morderid').html(order_id);
                            $('#Cancelorder').html('<i class="fa fa-trash" onclick=cancelorder("' + order_id + '");></i>');
                            $('#Cancelorder').show();
                        }
                        var Template = {
                            visit_report_id: $('#labvid').html(),
                            prescription_scan_id: labprescriptionid,
                            job_due_date: job_due_date,
                            job_status: 1,
                            lab_id: $('#lab_id').val(),
                            order_id: order_id,
                            Dml_Indicator: 'TIJ'
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Template/lab_home',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(Template),
                            success: function (data) {
                                var data2 = JSON.parse(data);
                                var data = JSON.parse(data2.data);
                                if (data[0].test_p_status == "0") {
                                    toastr.warning("No Parameters for this test, Please add Parameters to this test");
                                    $('#loaderimg').hide();
                                }
                                else {
                                    getjobdetails($('#labvid').html(), order_id);
                                }
                            }
                        });
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function labtype() {
    var country = {
        Dml_Indicator: "TS"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientDashboard/Lab_Prescription_Ins_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            $('#labtype').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var Country;
                    $.each(data1, function (i, emp) {
                        Country = Country + '<option value="' + emp.lab_type_id + '">' + emp.lab_type_name + '</option>';
                    });
                    $('#labtype').append(Country);
                }
                else {
                    console.log(data);
                }
            }

        }
    });
}

function loadlab_id() {
    var country = {
        Dml_Indicator: "DI",
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data2 = JSON.parse(data);

            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    var Country;
                    $.each(data1, function (i, emp) {
                        $('#lab_id').val(emp.lab_id);
                    });
                    labcount();
                    datefun();
                    labtype();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}



$("#labtestjob").on("click", "p.Labwalkinresultsec", function () {
    //  alert($(this).parent().data('id'));
});




$("#btnLabParamSave").click(function () {
    debugger;
    var array = [];
    var j = 0;
    $('#labParameters_body tr').each(function () {
        var values = [], lblval = [];
        $(this).find("input").each(function () {
            j++;
            values.push($(this).val());
        });
        if (values == "") {
            $('#Pobs_val').show();
            $('#Pobs_val').fadeOut(8000);
            $('#Pobs_val').html('Observation Value cannot be empty');
            $('#obs_val_' + j).focus();
            $('#obs_val_' + j).val('');
            return false;
        }
        array.push(values);
    });
    var conclusion = $('#txtconclusion').val();
    //if (conclusion == '' || conclusion==null) {
    //    $('#Pobs_val').show();
    //    $('#Pobs_val').fadeOut(8000);
    //    $('#Pobs_val').html('Enter the conclusion');
    //    $('#txtconclusion').focus();
    //    $('#txtconclusion').val('');
    //    return false;
    //}
    //after validation
    var arrays = [];
    var j = 0;
    var ptsID = '', obsval = '';

    var rowCount = $('#labParameters_body tr').length;
    if (rowCount > 0) {
        $('#labParameters_body tr').each(function () {
            var $row = jQuery(this).closest('tr');
            var $columns = $row.find('td');
            var values = "";
            jQuery.each($columns, function (i, item) {
                ptsID = $(this).parent("tr").find("td:first").text();
            });
            var values = [];
            $(this).find("input").each(function () {
                values.push($(this).val());
                obsval = ($(this).val());
            });

            var ParameterResult = {
                //order_id: ptsID,
                //job_id: '',
                result_id: ptsID,
                observation: obsval,
                added_by: $('#HiddenDoctorID').val(),
                conclusion: $('#txtconclusion').val(),
                Dml_Indicator: 'RU'
            }
            $.ajax({
                async: true,
                type: 'POST',
                url: '/Template/lab_home',
                contentType: 'application/json; charset=UTF-8',
                data: JSON.stringify(ParameterResult),
                success: function (data) {
                    var order_id = '';
                    var data2 = JSON.parse(data);
                    if (jQuery.isEmptyObject((data2.data))) {

                    }
                    else {

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

                            if (data.length > 0) {
                                var a = data[0].VOrder_status;
                                if (a == null || a == '') {
                                    $('#Morderstatusid').html('(Completed)');
                                }
                                else {
                                    $('#Morderstatusid').html('(Pending)');
                                }
                            }
                        }
                        else {
                            console.log(data);
                        }

                        
                    }

                    $('#myResultviewModal').animate({ scrollTop: 600 }, 'slow');
                    $('#labJob-section').removeClass('in');
                    $('#labJob-section').addClass('in');
                    $('#labparameterss').hide();
                    $('.close').click();
                    var visit_report_id = $('#labvid').html();
                    var order_id = $('#Morderid').html();
                    getjoborderload(visit_report_id, order_id)
                    $('#txtconclusion').val('');
                    $('#labParameters_body').empty();
                }

            });


        });
    }
    else {

        var ParameterResult = {
            added_by: $('#HiddenDoctorID').val(),
            conclusion: $('#txtconclusion').val(),
            job_id: $('#Mjobid').html(),
            Dml_Indicator: 'RUJ'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(ParameterResult),
            success: function (data) {
                var order_id = '';
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {

                }
                else {

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

                        if (data.length > 0) {
                            var a = data[0].VOrder_status;

                            if (a == null || a == '') {
                                $('#Morderstatusid').html('(Completed)');
                            }
                            else {
                                $('#Morderstatusid').html('(Pending)');
                            }
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
                $('#txtconclusion').val('');
                $('#myResultviewModal').animate({ scrollTop: 600 }, 'slow');
                $('#labJob-section').removeClass('in');
                $('#labJob-section').addClass('in');
                $('#labparameterss').hide();
                var visit_report_id = $('#labvid').html();
                var order_id = $('#Morderid').html();
                getjoborderload(visit_report_id, order_id)
            }

        });
    }

})



function addwalkin() {
    $('#patientdetails1').hide();
    $('#paitentsearchdiv').show();
    $('#labtestjob').hide();
    $('#Prescriptionhead').hide();
    $('#labparameterss').hide();
    $('#labJobSection').hide();
    $('#btnaddnewtest').hide();
}

$('#modalLabPaitentSearch').change(function () {
    $('#patientdetails1').show();
    $('#btnaddnewtest').show();
    var patientname = $('#modalLabPaitentSearch').val();
    var patientnames = patientname.split('/');
    if (patientname == '') {
        $('#PmodalLabPaitentSearch').show();
        $('#PmodalLabPaitentSearch').fadeOut(8000);
        $('#PmodalLabPaitentSearch').html('check the patient name');
        $('#modalLabPaitentSearch').focus();
        $('#modalLabPaitentSearch').val('');
        return false;
    }
    if (patientnames.length > 2) {
        $('#MPatient_id').html(patientnames[4]);
        $('#MPatientName').html(patientnames[0]);
        $('#MphoneNo').html(patientnames[1]);
        $('#DoctorName').html(' Self');
        $('#labvid').html('   NA    ');
    }
    else {
        toastr.warning("There is no Registered Patient");
    }
});

$('#btnLabCostSave').click(function () {
    debugger;
    var rowCount = $('#laborderjob_body tr').length;
    var K = 0, totamt = 0;
    for (var i = 1; i <= rowCount; i++) {
        totamt = totamt + $('#amt_val_' + i).val();
        if (totamt <= 0) {
            toastr.warning('Invoice cannot be generated in zero value');
            return false;
        }
    }
    if (totamt <= 0) {
        toastr.warning('Invoice cannot be generated in zero value');
        return false;
    }
    $('#loaderimg').show();
    var array = [];
    var j = 0;       
    var orderId = '', totamount = '', invoiceId = '';
    var ptsID = '';
    var j = 0;
    $('#laborderjob_body tr').each(function () {
        j++;
        var $row = jQuery(this).closest('tr');
        var $columns = $row.find('td');
        var values = "";
        jQuery.each($columns, function (i, item) {
            ptsID = $(this).parent("tr").find("td:first").text();
        });
        var ParameterResult = {
            job_id: ptsID,
            job_cost: $('#cost_val_' + j).val(),
            discount: $('#dis_val_' + j).val(),
            discount_type: $('#labDisDrop_' + j).val(),
            job_tax: $('#tax_val_' + j).val(),
            job_amount: $('#amt_val_' + j).val(),
            patient_id: $('#MPatient_id').html(),
            coupon_id: $('#coupon_lab_id').val(),
            Dml_Indicator: 'UJ'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(ParameterResult),
            success: function (data) {
                K++;
                //alert(rowCount +'  '+ K);
                var order_id = '';
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                }
                else {

                    if (data2.msg == "Success") {
                        var data = data2.data;
                        if (data.length > 0) {
                            orderId = data[0].order_id;
                            totamount = data[0].totamount;
                            invoiceId = data[0].InvoiceId;
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
                if (rowCount == K) {
                    var d = new Date();
                    var month = d.getMonth() + 1;
                    var day = d.getDate();
                    var output = d.getFullYear() + '-' +
                        (month < 10 ? '0' : '') + month + '-' +
                        (day < 10 ? '0' : '') + day;
                    var InvoiceDate = output;
                    var InvoiceName = 'LabOrder ' + orderId;
                    var InvoiceAmount = totamount;
                    var inv_status = '1';
                    if ($('#couponmsg').val() == "1") {
                        InvoiceAmount = "0";
                        inv_status = "3";
                    }
                    var invoice = {
                        invoice_id: invoiceId,
                        Patient_id: $('#MPatient_id').html(),
                        doctor_id: $('#HiddenDoctorID').val(),
                        invoice_description: InvoiceName,
                        invoice_date: InvoiceDate,
                        invoice_amount: InvoiceAmount,
                        invoice_status: inv_status,
                        balance_amount: InvoiceAmount,
                        order_id: orderId,
                        Dml_Indicator: 'I'
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/caseStudy/invoice_payment',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(invoice),
                        success: function (data) {

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

                                $('#loaderimg').hide();
                                toastr.success('Invoice Generated Sucessfully, Invoice No : ' + invoiceId);
                                labcount();
                                $('#btnclose').click();
                                $('#btncloseX').click();
                                $('#couponmsg').val('');
                            }
                            else {
                                console.log(data);
                            }
                        }
                    });
                }
            }
        });
    });
});



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

    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }
    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    if ($('#Selorder_status').val() == 4) {
        $('#datefilter').show();
        $('#patientName_filter').hide();
        $('#btnsubmit_order').show();
        return false;
    }
    else if ($('#Selorder_status').val() == 5) {
        $('#datefilter').hide();
        $('#patientName_filter').show();
        $('#btnsubmit_order').show();
        return false;
    }
    else {
        $('#datefilter').hide();
        $('#patientName_filter').hide();
        $('#btnsubmit_order').hide();
    }

    var FDate = '', EDate = '', PName = '';
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Dml_Indicator = '';
    if ($('#Selorder_status').val() == 0) {
        Dml_Indicator = 'LOV';
    }
    else if ($('#Selorder_status').val() == 4) {
        var date = $('#FDate').val();
        var dates = date.split('/');
        FDate = dates[2] + '-' + dates[1] + '-' + dates[0];

        var date = $('#EDate').val();
        var dates = date.split('/');
        EDate = dates[2] + '-' + dates[1] + '-' + dates[0];
        Dml_Indicator = 'LODW';
    }
    else if ($('#Selorder_status').val() == 5) {
        PName = $('#PName').val();
        Dml_Indicator = 'LONA';
    }
    else {
        Dml_Indicator = 'LOVO';
    }
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        order_status: $('#Selorder_status').val(),
        lab_id: $('#lab_id').val(),
        FDate: FDate,
        EDate: EDate,
        PName: PName
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labJoblist_head').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#labJoblist_head').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            if (data1[i].invoice_id == null || data1.invoice_id == '') {
                                invoiceAmt = '<span> - </span><br/><span></span>';
                                invoicedue = '<span style="color:yellow;"> - </span>';
                            }
                                //else if (data1[i].invoice_amount == null || data1[i].invoice_amount == '') {

                                //}
                                //else if (data1[i].balance_amount == null || data1[i].balance_amount == '') {

                                //}
                            else {
                                if (data1[i].balance_amount > 0) {
                                    var img = '<i class="fa fa-money" area-hidden="true"></i>';
                                    //invoicedue = '<span style="color:red;"><i class="fa fa-inr">' + data1[i].balance_amount + '</i><a id="btnLabPayment" data-toggle="modal" data-target="#collectPayment">' + img + '</a></span>';
                                    invoicedue = '<span style="color:red;" class="btn"><a id="btnLabPayment" onclick=\'collectpayment(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\")\' data-toggle="modal" data-target="#collectPayment"><span class="edit btn btn-primary btn-xs mr-15">' + img + '</span><i class="fa fa-inr">' + data1[i].balance_amount + '</i> </a></span>';

                                }
                                else {
                                    var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                    if (data1[i].coupon_id != "" && data1[i].coupon_id != null) {
                                        img = '<i class="fa fa-check" aria-hidden="true"></i> Coupon';
                                    }
                                    invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                }
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].invoice_amount + '</i></span>';
                            }
                            var Order_status = '';
                            if (data1[i].order_id == null || data1[i].order_id == '') {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-success btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';
                            }
                            else if (data1[i].order_status == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Pending)\")\';>Add Result</a>';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else if (data1[i].order_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Completed)\" ,\"' + data1[i].invoice_amount + '\",\"' + data1[i].balance_amount + '\")\';>Show Result</a>';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                            }
                            else if (data1[i].order_status == 3) {
                                //  Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                Action = '<span style="color:red;">-</span>';
                                Order_status = '<a herf="javascript:void(0)" style="color:red;">Cancelled</a>';
                            }
                            if (data1[i].payment_status == 'Success' && data1[i].order_status == 1) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }
                            else if (data1[i].payment_status == 'Success' && data1[i].order_status == 2) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }

                            tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="part-payment btn btn-primary btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>' + data1[i].order_id + '</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</td><td>' + data1[i].phone_number_1 + '</td><td>' + Order_status + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td><td><button onclick=files_lab("' + data1[i].I2H_order_id + '")  data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'


                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';

                        }
                        $('#labJoblist_head').empty();
                        var head = ('<thead><tr><th>&nbsp;</th><th>Order Id</th><th>Order Date</th><th>Name</th><th>Mobile No</th><th>Status</th><th>Amount</th><th>Due</th><th>Files</th></tr></thead>');
                        var Sbody = ('<tbody id=labJoblist_body>');
                        var Ebody = ('</tbody>');
                        $('#labJoblist_head').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#labJoblist_head').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }

        }
    });

});



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

    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }

    var FDate = '', EDate = '', PName = '';
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Dml_Indicator = '';
    if ($('#Selorder_status').val() == 0) {
        Dml_Indicator = 'LOV';
    }
    else if ($('#Selorder_status').val() == 4) {
        var date = $('#FDate').val();
        var dates = date.split('/');
        FDate = dates[2] + '-' + dates[1] + '-' + dates[0];

        var date = $('#EDate').val();
        var dates = date.split('/');
        EDate = dates[2] + '-' + dates[1] + '-' + dates[0];
        Dml_Indicator = 'LODW';
    }
    else if ($('#Selorder_status').val() == 5) {
        PName = $('#PName').val();
        var patientnames = PName.split('/');
        PName = patientnames[(patientnames.length) - (1)];
        Dml_Indicator = 'LONA';
    }
    else {
        Dml_Indicator = 'LOVO';
    }
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        order_status: $('#Selorder_status').val(),
        lab_id: $('#lab_id').val(),
        FDate: FDate,
        EDate: EDate,
        PName: PName
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#labJoblist_head').empty();
            var data2 = JSON.parse(data)
            if (jQuery.isEmptyObject((data2.data))) {
                $('#labJoblist_head').html(Norecord);
            }
            else {
;
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;

                            var photoSrc;
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";

                            }
                            else {

                                photoSrc = PatientPhoto + patient_photo;

                            }
                            if (data1[i].invoice_id == null || data1.invoice_id == '') {
                                invoiceAmt = '<span> - </span><br/><span></span>';
                                invoicedue = '<span style="color:yellow;"> - </span>';
                            }
                                //else if (data1[i].invoice_amount == null || data1[i].invoice_amount == '') {

                                //}
                                //else if (data1[i].balance_amount == null || data1[i].balance_amount == '') {

                                //}
                            else {
                                if (data1[i].balance_amount > 0) {
                                    var img = '<i class="fa fa-money" area-hidden="true"></i>';
                                    //invoicedue = '<span style="color:red;"><i class="fa fa-inr">' + data1[i].balance_amount + '</i><a id="btnLabPayment" data-toggle="modal" data-target="#collectPayment">' + img + '</a></span>';
                                    invoicedue = '<span style="color:red;" class="btn"><a id="btnLabPayment" onclick=\'collectpayment(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\")\' data-toggle="modal" data-target="#collectPayment"><span class="edit btn btn-primary btn-xs mr-15">' + img + '</span><i class="fa fa-inr">' + data1[i].balance_amount + '</i> </a></span>';
                                }
                                else {
                                    var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                    if (data1[i].coupon_id != "" && data1[i].coupon_id != null) {
                                        img = '<i class="fa fa-check" aria-hidden="true"></i> Coupon';
                                    }
                                    invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                }
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].invoice_amount + '</i></span>';
                            }

                            var Order_status = '';
                            if (data1[i].order_id == null || data1[i].order_id == '') {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';

                            }
                            else if (data1[i].order_status == 1) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Pending)\")\';>Add Result</a>';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else if (data1[i].order_status == 2) {
                                Action = '<a href="javascript:void(0)" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Completed)\" ,\"' + data1[i].invoice_amount + '\",\"' + data1[i].balance_amount + '\")\';>Show Result</a>';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                            }
                            else if (data1[i].order_status == 3) {
                                //  Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"  onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                Action = '<span style="color:red;">-</span>';
                                Order_status = '<a herf="javascript:void(0)" style="color:red;">Cancelled</a>';
                            }

                            if (data1[i].payment_status == 'Success' && data1[i].order_status == 1) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" class="btn btn-warning btn-xs">Pending</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }
                            else if (data1[i].payment_status == 'Success' && data1[i].order_status == 2) {
                                Action = 'mobile order';
                                Order_status = '<a herf=""#" style="color:green;">Completed</a>';
                                var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                                invoicedue = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                invoiceAmt = '<span><i class="fa fa-inr">' + data1[i].total_cost + '</i></span>';
                            }


                            tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="part-payment btn btn-primary btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>' + data1[i].order_id + '</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</td><td>' + data1[i].phone_number_1 + '</td><td>' + Order_status + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td><td><button onclick=files_lab("' + data1[i].I2H_order_id + '")  data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'


                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';

                        }
                        $('#labJoblist_head').empty();
                        var head = ('<thead><tr><th>&nbsp;</th><th>Order Id</th><th>Order Date</th><th>Name</th><th>Mobile No</th><th>Status</th><th>Amount</th><th>Due</th><th>Files</th></tr></thead>');
                        var Sbody = ('<tbody id=labJoblist_body>');
                        var Ebody = ('</tbody>');
                        $('#labJoblist_head').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#labJoblist_head').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }

        }
    });
});


$('#SelJob_status').change(function () {
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();

        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();
    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Dml_Indicator = '';

    if ($('#SelJob_status').val() == 4) {
        $('#datefilter_1').show();
        $('#patientName_filter_1').hide();
        $('#btnsubmit_job').show();
        return false;
    }
    else if ($('#SelJob_status').val() == 5) {
        $('#datefilter_1').hide();
        $('#patientName_filter_1').show();
        $('#btnsubmit_job').show();
        return false;
    }
    else {
        $('#datefilter_1').hide();
        $('#patientName_filter_1').hide();
        $('#btnsubmit_job').hide();
    }

    if ($('#SelJob_status').val() == 0) {
        Dml_Indicator = 'JSD';
    }
    else {
        Dml_Indicator = 'JSDO'
    }
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        lab_id: $('#lab_id').val(),
        job_status: $('#SelJob_status').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#Jobdetails').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#Jobdetails').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        console.log(data1);
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc, jobstatus = '';
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            if (data1[i].invoice_id != null && data1[i].invoice_id != '' && data1[i].invoice_status == 3) {
                                if (data1[i].job_status == null || data1[i].job_status == '') {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" class="btn btn-submit btn-xs" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\","(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';
                                }
                                else if (data1[i].job_status == 1) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                                }
                                else if (data1[i].job_status == 2) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:green;">Completed</a>';
                                }
                                else if (data1[i].job_status == 3) {
                                    // Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"   onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                            }
                            else if (data1[i].payment_status == "Success") {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else {
                                if (data1[i].job_status == 3) {
                                    // Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"   onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                                else {
                                    Action = '<span style="color:red;">payment not completed</span>';
                                }
                            }
                            //tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '</td><td>' + data1[i].patient_id + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + Action + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'
                            tr = tr + '<tr><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</span></td><td>' + data1[i].job_id + '<span style="color: #999; font-size: 11px;">(' + data1[i].order_id + ')</span>' + '</td><td>' + data1[i].test_name + '</td><td>' + data1[i].job_due_date + '</td><td>' + jobstatus + '</td><td><ul class="list-inline"><li>' + Action + '</li></ul></td></tr>';
                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';
                        }
                        var head = '<thead><tr><th>Patient Name</th><th>Job ID</th><th>Test Name</th><th>Due date</th><th>Status</th><th>Action</th></tr></thead>';
                        var Sbody = '<tbody>';
                        var Ebody = '</tbody>'
                        $('#Jobdetails').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#Jobdetails').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }

        }
    });
});



$('#btnsubmit_job').click(function () {
    if ($('#app_date_current').html() == 'Today') {
        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();

        var output = (day < 10 ? '0' : '') + day + '/' +
            (month < 10 ? '0' : '') + month + '/' +
            d.getFullYear();
        date = output;
    }

    else if ($('#app_date_current').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Dml_Indicator = '';


    if ($('#SelJob_status').val() == 0) {
        Dml_Indicator = 'JSD';
    }
    else if ($('#SelJob_status').val() == 4) {
        Dml_Indicator = 'JSDW';
        var date = $('#FDate_job').val();
        var dates = date.split('/');
        var FDate1 = dates[2] + '-' + dates[1] + '-' + dates[0];

        var date = $('#EDate_job').val();
        var dates = date.split('/');
        var EDate1 = dates[2] + '-' + dates[1] + '-' + dates[0];
    }
    else if ($('#SelJob_status').val() == 5) {
        var PName1 = $('#PName_job').val();
        var patientnames = PName1.split('/');
        PName1 = patientnames[(patientnames.length) - (1)];
        Dml_Indicator = 'JSNA';
    }
    else {
        Dml_Indicator = 'JSDO'
    }

    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        lab_id: $('#lab_id').val(),
        job_status: $('#SelJob_status').val(),
        PName: PName1,
        FDate: FDate1,
        EDate: EDate1
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#Jobdetails').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#Jobdetails').html(Norecord);
            }
            else {

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

                    var tr = '', Action = '', invoiceAmt = '', invoicedue = '';
                    if (data1.length > 0) {
                        console.log(data1);
                        for (var i = 0; i < data1.length; i++) {
                            var patient_photo = data1[i].photo;
                            var photoSrc, jobstatus = '';
                            var PatientPhoto = $('#patphotopath').val();
                            if ($.trim(patient_photo) == "" || patient_photo == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                photoSrc = PatientPhoto + patient_photo;
                            }
                            if (data1[i].invoice_id != null && data1[i].invoice_id != '' && data1[i].invoice_status == 3) {
                                if (data1[i].job_status == null || data1[i].job_status == '') {
                                    Action = '<a href="javascript:void(0)" class="btn btn-submit btn-xs" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\","(Your Order has not been placed yet)\")\';><i class="fa fa-cart-plus" aria-hidden="true"></i></a>';
                                }
                                else if (data1[i].job_status == 1) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                                }
                                else if (data1[i].job_status == 2) {
                                    Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'completedtestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Completed)\")\'; >Show Result</a>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:green;">Completed</a>';
                                }
                                else if (data1[i].job_status == 3) {
                                    // Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"   onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                            }
                            else if (data1[i].payment_status == "Success") {
                                Action = '<a href="javascript:void(0)" data-toggle="modal" data-target="#myResultviewModal_result" data-backdrop="static" data-keyboard="false"  onclick=\'ontestid(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"' + data1[i].job_id + '\",\"' + data1[i].test_id + '\",\"(Pending)\")\';>Add Result</a>';
                                jobstatus = '<a href="javascript:void(0)" class="btn btn-warning btn-xs">Pending</a>';
                            }
                            else {
                                if (data1[i].job_status == 3) {
                                    // Action = '<a href="#" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs"   onclick=\'onlabadvice(\"' + data1[i].first_name + '\",\"' + data1[i].phone_number_1 + '\",\"' + data1[i].patient_id + '\",\"' + photoSrc + '\",\"' + data1[i].visit_report_id + '\",\"' + data1[i].order_id + '\",\"(Cancel)\")\'; style="color:red;">' + data1[i].order_id + '</a>';
                                    Action = '<span style="color:red;">-</span>';
                                    jobstatus = '<a href="javascript:void(0)" style="color:red;">Cancelled</a>';
                                }
                                else {
                                    Action = '<span style="color:red;">payment not completed</span>';
                                }
                            }
                            //tr = tr + '<tr data-toggle="collapse" data-target="#demo_' + i + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + i + '","' + data1[i].order_id + '"); class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>' + data1[i].add_date + '</td><td>' + data1[i].first_name + '</td><td>' + data1[i].patient_id + '</td><td>' + data1[i].phone_number_1 + '</td><td>' + Action + '</td><td>' + invoiceAmt + '</td><td>' + invoicedue + '</td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + i + '"></tr>'
                            tr = tr + '<tr><td>' + data1[i].first_name + '<span style="color: #999; font-size: 11px;">(' + data1[i].patient_id + ')</span></td><td>' + data1[i].job_id + '<span style="color: #999; font-size: 11px;">(' + data1[i].order_id + ')</span>' + '</td><td>' + data1[i].test_name + '</td><td>' + data1[i].job_due_date + '</td><td>' + jobstatus + '</td><td><ul class="list-inline"><li>' + Action + '</li></ul></td></tr>';
                            //'<tr data-toggle="collapse" data-target="#demo1" class="accordion-toggle"><td><button class="btn btn-default btn-xs"><span class="glyphicon glyphicon-eye-open"></span></button></td><td>1</td><td>15-05-2019</td><td>Anand</td><td>Parthiban</td><td>6758768545</td><td><span>1599</span><br/><a id="btnLabInvoice" class="" data-toggle="modal"  data-target="#myResultviewModal" class="btn btn-primary btn-xs" >+ Invoice</a></td><td><span style="color:yellow;">478</span> <br /><a id="btnLabPayment"  data-toggle="modal" data-target="#btnLabCollectPayment">+ Payment</a></td></tr>'
                            //'<tr class="hiddenRow accordian-body collapse" id="demo1"><td colspan="12"><div><table class="table table-condensed body-borderless table_borderless"><thead><tr><td>Job ID</td><td>Test Name</td><td>Status</td><th>Action</th></tr></thead><tbody><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr><tr><td>23</td><td>HbA1C</td><td>Status</td><td>Link</td></tr></tbody></table></div></td></tr>';
                        }
                        var head = '<thead><tr><th>Patient Name</th><th>Job ID</th><th>Test Name</th><th>Due date</th><th>Status</th><th>Action</th></tr></thead>';
                        var Sbody = '<tbody>';
                        var Ebody = '</tbody>'
                        $('#Jobdetails').html(head + Sbody + tr + Ebody);
                    }
                    else {
                        $('#Jobdetails').html(Norecord);
                    }
                }
                else {
                    console.log(data);
                }
            }

        }
    });
});



$('#modalLabPaitentSearch').keypress(function (e) {
    if (e.which == '13') {
        $('#btnLabPaitentSearch').click();

    }
});


$('#btncloseX').click(function () {
    clear();
});

$('#btnclose').click(function () {
    clear();
});


function clear() {
    $('#DoctorName').html('');
    $('#labvid').html('');

    $('#MPatient_id').html('');
    $('#MPatient_id_1').html('');
    $('#MPatientName').html('');
    $('#MPatientName_1').html('');
    $('#MphoneNo').html('');
    $('#MphoneNo_1').html('');
    $('#labvid').html('');
    $('#labvid_1').html('');
    $('#age').html('');

    $('#laborderjob_body').empty();
    $('#labtestjob_body').empty();
    $('#labParameters_body').empty();

    $('#txtconclusion').empty();
    $('#labtypetest').val(1);

    $('#Morderid').html('');
    $('#Morderstatusid').html('');
    $('#btnaddnewtest').show();
    $('#labJobSection').show();

    $('#patientdetails').show();
    $('#btnaddnewtest').show();
    $('#laborderjob_footer').empty();


    $('#paymentdetails').empty();
    $('#modalLabPayment').hide();
    $('#modalLabInvoice').hide();
    $('#labtestjob').show();
    labcount();
}





// payment start point

function collectpayment(Pname, Phoneno, patient_id, photo) {
    debugger;
    var val = $('#MPatientName').html();
    var patientId = '';
    if ($.trim($('#MPatientName').html()) == '' || $.trim($('#MPatientName').html()) == null) {
        $('#PPatientName').html(Pname);
        $('#PPatientpno').html(Phoneno);
        $('#PPatientid').html(patient_id);
        $('#PPatientPhoto').html('<img class="img-responsive text-center imgphoto" src=' + photo + ' alt="Patient Image" width="40" onerror="changedefault(this)"/>');
        patientId = patient_id;
        $('#MPatient_id').html(patient_id);
    }
    else {
        $('#PPatientName').html($('#MPatientName').html());
        $('#PPatientpno').html($('#MphoneNo').html());
        $('#PPatientid').html($('#MPatient_id').html());
        patientId = $('#MPatient_id').html();
    }

    if (patientId == '' || patientId == null) {
        patientId = $('#PPatientid').html();
    }

    var InvoiceId = {
        Patient_id: patientId,
        Dml_Indicator: 'IS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    if (data.length > 0) {
                        $('#InvoiceId').val(data[0].InvoiceId);
                    }
                }
                else {
                    console.log(data);
                }
            }
            ActiveInvoice();

        }
    });
}

$('#btnAddInvoice').click(function () {
    var InvoiceDate = $('#InvoiceDate').val();
    var InvoiceName = $('#InvoiceName').val();
    var InvoiceAmount = $('#InvoiceAmount').val();
    if ($.trim(InvoiceDate) == '') {
        $('#PInvoiceDate').show();
        $('#PInvoiceDate').fadeOut(8000);
        $('#PInvoiceDate').html('Select the invoice date');
        $('#InvoiceDate').focus();
        $('#InvoiceDate').val('');
        return false;
    }
    if ($.trim(InvoiceName) == '') {
        $('#PInvoiceName').show();
        $('#PInvoiceName').fadeOut(8000);
        $('#PInvoiceName').html('Enter the invoice name');
        $('#InvoiceName').focus();
        $('#InvoiceName').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the invoice amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    if ($.trim(InvoiceAmount) == '0') {
        $('#PInvoiceAmount').show();
        $('#PInvoiceAmount').fadeOut(8000);
        $('#PInvoiceAmount').html('Enter the valid amount');
        $('#InvoiceAmount').focus();
        $('#InvoiceAmount').val('');
        return false;
    }
    var InvoiceDates = InvoiceDate.split('/');
    InvoiceDate = InvoiceDates[2] + "-" + InvoiceDates[1] + "-" + InvoiceDates[0];
    var invoice = {
        invoice_id: $('#InvoiceId').val(),
        Patient_id: $('#PPatientid').html(),
        doctor_id: $('#HiddenDoctorID').val(),
        invoice_description: $('#InvoiceName').val(),
        invoice_date: InvoiceDate,
        invoice_amount: $('#InvoiceAmount').val(),
        invoice_status: 1,
        balance_amount: $('#InvoiceAmount').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
            }
            $('#InvoiceDate').val('');
            $('#InvoiceName').val('');
            $('#InvoiceAmount').val('');
            collectpayment();
        }
    });
});





$('#cpi_activeInvoice_body').on('click', 'tr', function () {
    $('#cpi_activeInvoice_sec').removeClass().addClass('col-md-12 padding0');
    $('#cpi_activeInvoice_body > tr').removeClass('active');
    $('#cpi_activeInvoice_body > tr').css('fontSize', '12px');
    $(this).addClass('active');
    var id = $(this).attr('data-invoice');
    var val = id.split(',');
    ActiveInvoiceDetails(val[0], val[1]);
    $("#cpiActiveDetails").show();

});


$('#cpiDetailToggle').click(function () {
    $('#cpi_activeInvoice_body > tr').removeClass('active');
    $('#cpi_activeInvoice_body > tr').css('fontSize', '14px');
    $("#cpiActiveDetails").hide();
    $('#cpi_activeInvoice_sec').removeClass().addClass('col-md-12 padding0');
});


function ActiveInvoice() {
    debugger;
    $('#cpHistoryInvoice-section').removeClass('in');
    $('#cpi_activeInvoice_table').addClass('us-db-loader-active-inv');
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'AI',
        patient_id: $('#PPatientid').html()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            debugger;
            var tr = '';
            $('#cpi_activeInvoice_body').empty();
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data = JSON.parse(data);
                var data = data.data;
                if (data.length > 0) {

                    for (var i = 0; i < data.length; i++) {

                        //tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>Payment</td></tr>';
                        tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td><a class="payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);"  data-backdrop="static" title="CASH" data-keyboard="true" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-money" area-hidden="true"></i></a><a class="payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);" data-backdrop="static" title="CARD" data-keyboard="true" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 2 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-credit-card" area-hidden="true"></i><a class="payment btn addicon-btn   btn-sm mr-20" href="javascript:void(0);" data-backdrop="static" data-keyboard="true" onclick=add_payment1(\"' + data[i].lab_order_id + '\");><i class="fa fa-hourglass-half" area-hidden="true"></i></a><span class="payment btn addicon-btn   btn-sm mr-20"><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\", \"' + data[i].invoice_description + '\") \';></i></span></td><td><a class="delete btn deleteicon-btn   btn-sm" href="javascript:void(0);" onclick=Delete_Active_invoice(\"' + data[i].invoice_id + '\",\"' + data[i].lab_order_id + '\")><i class="fa fa-trash" aria-hidden="true"></i></a></td></tr>';

                    }
                    $('#cpi_activeInvoice_body').html(tr);
                    $('#CpiInvoiceTotal').html(parseFloat(data[0].invoice_total) - parseFloat(data[0].invoice_payment));
                    $('#CpiInvoicePayment').html(data[0].invoice_payment);
                    $('#CpiInvoiceTotal_amt').html(data[0].invoice_total);
                }
            }
            $('#cpi_activeInvoice_table').removeClass('us-db-loader-active-inv');
        }
    });
}


function ActiveInvoiceDetails(id, amount) {
    $('#curinvoiceid').val(id);
    $('#curamount').val(amount);
    var invoice = {
        invoice_id: $('#curinvoiceid').val(),
        Patient_id: $('#MPatient_id').html(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'PD',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),

        success: function (data) {
            $('#tblinvoiceamtdetails_body').empty();
            var tr = '';
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#totamt').html(amount);
                $('#paidamt').html('0');
                $('#balanceamt').html('0');
            }
            else {

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

                    $('#totamt').html('0');
                    $('#paidamt').html('0');
                    $('#balanceamt').html('0');
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var paymenttype = '';
                            if (data[i].payment_type == 1) {
                                paymenttype = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                paymenttype = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                paymenttype = 'Payment Gateway';
                            }
                            else {
                                paymenttype = 'Online';
                            }
                            tr = tr + '<tr><td>' + data[i].payment_id + '</td><td>' + paymenttype + '</td><td>' + data[i].payment_amount + '</td></tr>';
                            $('#totamt').html(data[0].invoice_amount);
                            $('#paidamt').html(data[0].payment_amount);
                            $('#balanceamt').html(data[0].balance_amount);
                            $('#payment_details').html('<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 2 + '\",\"' + $('#curinvoiceid').val() + '\")\';>Fully Paid by Card</a>/<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + $('#curinvoiceid').val() + '\")\';>Fully Paid by Card</a>');
                            //$('#payment_details').html('<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';>Fully Paid by Card</a>/<a href="javascript:void(0);" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 2 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';>Fully Paid by Card</a>');
                        }
                    }
                    else {
                        $('#totamt').html(amount);
                    }
                    $('#tblinvoiceamtdetails_body').html(tr);
                }
                else {
                    console.log(data);
                }
            }
        }

        //success: function (data) {
        //    $('#tblinvoiceamtdetails_body').empty();
        //    var tr = '';
        //    if (jQuery.isEmptyObject((data))) {

        //    }
        //    else {
        //        debugger;
        //        var data = JSON.parse(data);
        //        if (data.length > 0) {
        //            for (var i = 0; i < data.length; i++) {
        //                var paymenttype = '';
        //                if (data[i].payment_type == 1) {
        //                    paymenttype = 'Cash';
        //                }
        //                else if (data[i].payment_type == 2) {
        //                    paymenttype = 'Card';
        //                }
        //                else {
        //                    paymenttype = 'Payment Gateway';
        //                }
        //                tr = tr + '<tr><td>' + data[i].payment_id + '</td><td>' + paymenttype + '</td><td>' + data[i].payment_amount + '</td></tr>';
        //            }
        //        }
        //        $('#tblinvoiceamtdetails_body').html(tr);
        //    }
        //}
    });
}
function add_payment1(labid) {
    $('#add_cpi_invoice').prop('disabled', false);
    $('#pack_id').val(labid);
    $('#Selpaymenttype').val('1');
    $('#modal_collectpayment_inner').modal('toggle');
}


$('#add_cpi_invoice').click(function () {
    if ($('#Selpaymenttype').val() == 4) {
        if ($.trim($('#transaction_id').val()) == '') {
            $('#Ptransaction_id').show();
            $('#Ptransaction_id').fadeOut(4000);
            $('#Ptransaction_id').html('enter the transaction_id');
            $('#transaction_id').focus();
            $('#transaction_id').val('');
            return false;
        }
    }
    if ($.trim($('#paymentamount').val()) == '' || $.trim($('#paymentamount').val()) == '0') {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('enter the invoice amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        return false;
    }
    $('#add_cpi_invoice').prop('disabled', true);
    var previousval = 0;
    $('#tblinvoiceamtdetails > tbody  > tr').each(function () {
        $(this).find("td:gt(1)").each(function () {
            var temp = $(this).html();
            previousval = parseFloat(previousval) + parseFloat(temp);
        });
    });
    previousval = parseFloat(previousval) + parseFloat($('#paymentamount').val());
    var invoice_status = '', balance_amount = '', patient_id = '', invoice_id = '', doc_id = '', package_id = '';
    console.log($('#curamount').val());
    if (previousval > parseFloat($('#curamount').val())) {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('Check amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        $('#add_cpi_invoice').prop('disabled', false);
        return false;
    }
    else if (previousval < parseFloat($('#curamount').val())) {
        invoice_status = 2;
        balance_amount = parseFloat($('#curamount').val()) - parseFloat(previousval);
    }
    else {
        invoice_status = 3;
        balance_amount = 0;
        patient_id = $('#MPatient_id').html();
        invoice_id = $('#curinvoiceid').val();
        package_id = $('#pack_id').val();
        if (package_id != null || package_id == "") {
            if (package_id.length > 3) {
                doc_id = $('#pack_id').val().split('-')[0];
                if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == ($('#HospitalId').val())) {
                    get_package_details(package_id, invoice_id, patient_id);
                }
            }
        }
    }
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#MPatient_id').html(),
        payment_amount: $('#paymentamount').val(),
        payment_type: $('#Selpaymenttype').val(),
        invoice_id: $('#curinvoiceid').val(),
        invoice_status: invoice_status,
        balance_amount: balance_amount,
        transaction_id: $("#transaction_id").val(),
        Dml_Indicator: 'PI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                }
                else {
                    console.log(data);
                }
            }
            $('#paymentamount').val('');
            $('#transaction_id').val('');
            $('#transaction').hide();
            $('#Selpaymenttype').val('');
            ActiveInvoiceDetails($('#curinvoiceid').val(), balance_amount);
            ActiveInvoice();
            HistroyInvoice();
            labAdvice();
            laborderview();
            jobview();
            $('#add_cpi_invoice').prop('disabled', false);
        }
    });
});


$('#cpHistoryInvoiceId').click(function () {
    HistroyInvoice();

});


function fullpayment(balance_amount, payment_type, invoice_id, lab_order_id) {

    var invoice_status = 3;

    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#PPatientid').html(),
        payment_amount: balance_amount,
        payment_type: payment_type,
        invoice_id: invoice_id,
        invoice_status: invoice_status,
        balance_amount: 0,
        Dml_Indicator: 'PI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                }
                else {
                    console.log(data);
                }
            }
            $('#paymentamount').val('');
            //$("#cpiActiveDetails").hide();
            var doc_id;
            if (lab_order_id.length > 3) {
                doc_id = lab_order_id.split('-')[0];
                if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == ($('#HospitalId').val())) {
                    get_package_details(lab_order_id, invoice_id, $('#PPatientid').html());
                }
            }
            ActiveInvoice();
            HistroyInvoice();
            toastr.success("Full Payment Added successfully!");
            $('.paymentclose').click();
            labAdvice();
            laborderview();
            jobview();
            //ActiveInvoiceDetails($('#curinvoiceid').val(), $('#curamount').val())
        }
    });
}

$(document).on("click", ".popover .cpPopClose", function () {
    $(this).parents(".popover").popover('hide');
});

function HistroyInvoice(patientId) {
    $('.cpi_historyInvoice_table').addClass('us-db-loader-history-inv');
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'HS',
        patient_id: $('#MPatient_id').html()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var tr = '';
            $('#cpi_historyInvoice_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    if (data.length > 0) {
                        var tr1 = '', tr2 = '', tr3 = '', j = 1;
                        var invoice_id = '';
                        var a = data.length;
                        for (var i = 0; i < data.length; i++) {
                            var payment_type = '';
                            if (data[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else {
                                payment_type = '';
                            }
                            if (a == j) {

                                if (data[i].invoice_id == data[i].invoice_id) {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                    tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td class="ptr"><a tabindex="0" class="" data-html="true" data-toggle="popover" data-placement="bottom" data-trigger="click" title="<span class=\'cpPopClose pull-right\'><i class=\'fa fa-times\' aria-hidden=\'true\'></i></span><table class=\'table\'><thead><tr><th>Pay date</th><th>Amt</th><th>Pay Type</th></tr></thead><tbody>' + tr2 + '</tbody></table>">History</a></td></tr>';
                                    tr2 = '';
                                }
                            }
                            else {
                                if (data[i].invoice_id != data[j].invoice_id) {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                    tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td class="ptr"><a tabindex="0" class="" data-html="true" data-toggle="popover" data-placement="bottom" data-trigger="click" title="<span class=\'cpPopClose pull-right\'><i class=\'fa fa-times\' aria-hidden=\'true\'></i></span><table class=\'table\'><thead><tr><th>Pay date</th><th>Amt</th><th>Pay Type</th></tr></thead><tbody>' + tr2 + '</tbody></table>">History</a></td></tr>';
                                    tr2 = '';
                                }
                                else {
                                    tr2 = tr2 + '<tr><td>' + data[i].paid_date + '</td><td>' + data[i].payment_amount + '</td><td>' + payment_type + '</td></tr>';
                                }
                            }

                            j++;

                            // tr = tr + '<tr><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td class="ptr"><a tabindex="0" class="" data-html="true" data-toggle="popover" data-placement="top" data-trigger="click" title="<table class=\'table\'><tbody><td>col1</td><td>col1</td><td>col1</td></tr><tr><td>col1</td><td>col1</td><td>col1</td></tr></tbody></table>">History</a></td></tr>';
                        }
                        tr = tr
                        $('#cpi_historyInvoice_body').html(tr);
                        $("[data-toggle=popover]").popover();
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('.cpi_historyInvoice_table').removeClass('us-db-loader-history-inv');
        }
    });
}




function historydetails() {
    '<td>col1</td><td>col1</td><td>col1</td></tr><tr><td>col1</td><td>col1</td><td>col1</td></tr>';
}


function paymentClear() {
    $('#PPatientName').html('');
    $('#PPatientpno').html('');
    $('#PPatientid').html('');
    $('#PPatientName').html('');
    $('#cpi_activeInvoice_body').empty();
    $('#cpi_historyInvoice_body').empty();
    $('#CpiInvoiceTotal').html('');
    $('#CpiInvoicePayment').html('');

}

$('#paycolse').click(function () {
    paymentClear();
    $('#btncloseX').click();
});

$('#paycolse1').click(function () {
    paymentClear();
    $('#btncloseX').click();
});

//Cancelorder
//'<i class="fa fa-trash" onclick="canceljob(&quot;L2-J83&quot;);"></i>';

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

    if ($("#cpHistoryInvoice-section").hasClass("in")) {
        $('.paymentcollection').animate({ scrollTop: 600 }, 'slow');
    }
    else {
        $('.paymentcollection').animate({ scrollTop: 600 }, 'slow');
    }

});

// Payment end point


function chkreport() {
    var Dml_Indicator = '';
    if ($('#labtypetest').val() == 1) {
        Dml_Indicator = 'Chktest_TS';
    }
    else {
        Dml_Indicator = 'Chktest_PS';
    }
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: Dml_Indicator,
        testid: $('#lab_data_flag').val(),
        testname: $('#report').val(),
        lab_id: $('#lab_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#Preport').show();
                $('#Preport').fadeOut(8000);
                $('#Preport').html('Select test name from option');
                $('#report').focus();
                $('#report').val('');
                return false;
            }
            else {

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

                    if (data.length > 0) {

                    }
                    else {
                        $('#Preport').show();
                        $('#Preport').fadeOut(8000);
                        $('#Preport').html('Select test name from option');
                        $('#report').focus();
                        $('#report').val('');
                        return false;
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    })
};




function get_package_details(package_id, invoice_id, patient_id) {
    var package_data = {
        indicator_id: "GPD",
        package_id: package_id,
        patient_id: patient_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {

            var data2 = JSON.parse(data);
            var data = data2.data;
            if (jQuery.isEmptyObject((data)) || data.length == "0") {
            }
            else if (data.length > 0) {
                var no_of_consultation, cosult_details, lab_deatils, pharmadetails, j = 0, data_list = [], list_data = '';
                var data1 = JSON.parse(data);
                cosult_details = data1.Table;
                lab_deatils = data1.Table1;
                pharmadetails = data1.Table2;
                var data = new Array();
                var data1 = new Array();
                if (cosult_details[0]["no_of_consultation"] != null || cosult_details[0]["no_of_consultation"] != '') {
                    for (i = 0; i < cosult_details[0]["no_of_consultation"]; i++) {
                        if (cosult_details[0]["no_of_consultation"] > i) {
                            data["package_id"] = cosult_details[0]["package_id"];
                            data["patient_id"] = patient_id;
                            data["coupon_status"] = "1";
                            data["coupon_expire_date"] = cosult_details[0]["date_of_expire"];
                            data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                            data["type_id"] = cosult_details[0]["consult_id"];
                            data["type"] = "1";
                            insert_coupon(data);
                        }
                    }
                }
                data = [];
                if (lab_deatils[0]["no_of_package"] != null || lab_deatils[0]["no_of_package"] != '') {
                    for (i = 0; i < lab_deatils[0]["no_of_package"]; i++) {
                        if (lab_deatils[0]["no_of_package"] > i) {
                            data["package_id"] = lab_deatils[0]["package_id"];
                            data["patient_id"] = patient_id;
                            data["coupon_status"] = "1";
                            data["coupon_expire_date"] = lab_deatils[0]["date_of_expire"];
                            data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                            data["type_id"] = lab_deatils[0]["lab_package_id"];
                            data["type"] = "2";
                            insert_coupon(data);
                        }
                    }
                }
                data = [];
                if (pharmadetails[0]["no_of_free_delivery"] != null || pharmadetails[0]["no_of_free_delivery"] != '') {
                    for (i = 0; i < pharmadetails[0]["no_of_free_delivery"]; i++) {
                        if (pharmadetails[0]["no_of_free_delivery"] > i) {
                            data["package_id"] = pharmadetails[0]["package_id"];
                            data["patient_id"] = patient_id;
                            data["coupon_status"] = "1";
                            data["coupon_expire_date"] = pharmadetails[0]["date_of_expire"];
                            data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                            data["type_id"] = pharmadetails[0]["package_pharmacy_details_id"];
                            data["type"] = "3";
                            insert_coupon(data);
                        }
                    }
                }
            }
            package_purchase_insert(package_id, invoice_id);
        }
    });
}

function insert_coupon(data_list) {
    var package_data = {
        indicator_id: "PCDI",
        package_id: data_list.package_id,
        patient_id: data_list.patient_id,
        coupon_status: data_list.coupon_status,
        coupon_expire_date: data_list.coupon_expire_date,
        coupon_consumed_by: data_list.coupon_consumed_by,
        type_id: data_list.type_id,
        type: data_list.type
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
        }
    });
}


function package_purchase_insert(package_id, invoice_id) {
    var package_data = {
        indicator_id: "PPDI",
        package_id: package_id,
        patient_id: invoice_id.split('-')[0],
        invoice_id: invoice_id,
        booking_device: "1",
        payment_type: "1",
        created_by: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data2 = JSON.parse(data);
            var data = data2.data;
            if (data.length > 0) {
                toastr.success("Thank you for buying this package!!!");
            }
        }
    });
}


function Invoice_lab_print(order_id, visit_report_id, invoice_id, invoice_description) {
    var dml_indicatr = '', invoice_details = invoice_description.split('-');
    //if (invoice_details[0] == "package") {
    //    dml_indicatr = "PP";  //package print
    //}
    //else {
    //    dml_indicatr = "NP"; //normal invoice print
    //}
    //if (dml_indicatr == "PP") {
    //    window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
    //}
    //else if (order_id != '' && order_id != "null") {
    //    window.open('/PatientDashboard/labinvoice?orderid=' + invoice_id + '&doctorId=' + $('#HiddenDoctorID').val());
    //}
    //else {
    //    window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
    //}

    if (invoice_details[0] == "package") {
        dml_indicatr = "PP";  //package print
        window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
    }
    else {
        dml_indicatr = "NP"; //normal invoice print
        var invoice = invoice_description.split(' ');
        if (invoice[0] == "LabOrder") {
            if (order_id != '' && order_id != "null") {
                window.open('/PatientDashboard/labinvoice?orderid=' + invoice_id + '&doctorId=' + $('#HiddenDoctorID').val());
            }
        }
        else {
            if (visit_report_id == null || visit_report_id == "" || visit_report_id == "null") {
                dml_indicatr = "PP";
            }
            window.open('/PatientDashboard/doctorfees?visitreportid=' + visit_report_id + '&invoice_id=' + invoice_id + '&indicator=' + dml_indicatr + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
        }
    }

}



//lab order with package coupon code started


$('#btnLabCoup').click(function () {
    $('#tblcoupcheck').modal('toggle');
});


function lab_coupon_check() {
    if ($.trim($('#coup_id').val()).length == "") {
        $('#Pcoup_id').show();
        $('#Pcoup_id').fadeOut(8000);
        $('#Pcoup_id').html('Please enter coupon number');
        $('#coup_id').focus();
        $('#coup_id').val('');
        return false;
    }
    if ($.trim($('#coup_id').val()).length > 0) {
        var package_data = {
            Dml_Indicator: "COUPC",
            coupon_id: $('#coup_id').val(),
            patient_id: $('#MPatient_id').html(),
            doctor_id: $('#HiddenDoctorID').val(),
            order_id: $('#Morderid').html()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(package_data),
            success: function (data) {
                $('#tblcoupcheck').modal('toggle');
                var data2 = JSON.parse(data);
                var data = data2.data;
                if (jQuery.isEmptyObject((data)) || data.length == "0") {
                    toastr.warning("Invalid Coupon Number");
                }
                else {

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

                        console.log(data1);
                        if (data1[0].coupon_msg == "success") {
                            toastr.success("Coupon Applied Successfully");
                            $('#coupon_lab_id').val($('#coup_id').val());
                            $('#couponmsg').val("1");
                        }
                            //else if (data1[0].coupon_msg == "coupon_no_panel") {
                            //    var mesage = $('#MPatientName').html() + ", have this panel for coupon -" + data1[0].panel_name + ' (' + data1[0].panel_id + ')';
                            //    alert(mesage);
                            //    $('#coupon_lab_id').val('');
                            //    $('#couponmsg').val('');
                            //}
                        else {
                            toastr.warning("Invalid Coupon Number");
                            $('#coupon_lab_id').val('');
                            $('#couponmsg').val('');
                        }
                        $('#coup_id').val('');
                    }
                    else {
                        console.log(data);
                    }

                   
                }
            }
        });
    }
}



//lab order with package coupon code ended
function files_lab(order_id) {
    var data = {
        order_id: order_id,
        Dml_Indicator: "FL"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {

            var data2 = JSON.parse(data);
            var data = data2.data;
            console.log(data);
            if (data.Table[0].health_concern != '' && data.Table[0].health_concern != null) {
                $('#health_concern').html(data.Table[0].health_concern);
            }
            else {
                $('#health_concern').html("    -");
            }
            $('#tblAppointmentFiles_body').empty();
            if (data.Table[0].lab_files != '' && data.Table[0].lab_files != null) {

                var files = data.Table[0].lab_files.split("&&");

                var file_tr = '', k = 1;
                for (var i = 0; i < files.length; i++) {
                    var d, n, drloimage;
                    d = new Date();
                    n = d.getTime();
                    var file = $('#hdnHomeCareFilesView').val() + "HomeCareFiles/ParvathyFiles/" + files[i] + "?" + n;
                    file_tr = file_tr + '<tr><td>' + k + '</td><td><a href = ' + file + ' target=_blank> File </a></td></tr>';

                    k = k + 1;
                }
                $('#tblAppointmentFiles_body').html(file_tr);


            }
        }
    });
}
//paymenttype if value=4 transaction id will enable
$("#Selpaymenttype").change(function () {
    var value = $("#Selpaymenttype").val();
    if (value == 4) {
        $("#transaction").show();
    }
    else {
        $("#transaction").hide();
    }
})
