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 () {
    //package_dashboard();
    //table_package(); 
    var roleID = $('#HRoleId').val();
    var productCode = $('#HProductCode').val();
    debugger;
    if (roleID == "3") {
        $('#setuppackageicon').hide();
        package_dashboard();
    }
    else if (roleID == "1") {
        $('#setuppackageicon').hide();
        package_dashboard();
    }
    else {
        package_dashboard('2', 'hospital_care');
        //package_dashboard();

    }
});
//tab click
$(function () {

    var package_type = 1;
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        debugger;
        var target = $(e.target).attr("href")
        if (target == '#home_care') {
            package_type = 1;
            package_dashboard(package_type, 'home_care');
        }
        if (target == '#daily_care1') {
            package_type = 1;
            daily_care(package_type, 'daily_care');
        }
        if (target == '#hospital_care') {
            package_type = 2;
            package_dashboard(package_type, 'hospital_care');
        }
    });
});

$('#pa_sear_modal').click(function () {
    $('#patdata').hide();
    $('#patient_name').html('');
    $('#patient_number').html('');
    $('#patient_id1').val('');
    $('#packagecard').html('');
});

function package_dashboard(package_type, Package_category) {
    $("#Total_Home_Collection_Order").hide();
    $("#Self_Collection").hide();
    $("#Third_Party_Collection").hide();
    $("#Live_Package").show();
    //$("#Setup_New_package").show();
    $("#Package_Patients").show();
    $("#Sell_To_Patient").show();
    var package_data = {
        indicator_id: "PDASH",
        doctor_id: $('#HiddenDoctorID').val(),
        hospital_id: $('#HospitalId').val(),
        package_type: package_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) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1.length);
                if (Package_category == "hospital_care") { id = "pkgeTable" } if (Package_category == "daily_care") { id = "tbl_daily_care" } if (Package_category == "home_care") { id = "tbl_home_care" }
                console.log(Package_category + '<--->' + data);
                if (jQuery.isEmptyObject((data1))) {
                    tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="' + id + '" />');
                    tr.append("<thead><tr><th>S No</th><th>Patient Name/Phone Number</th><th>Package Name</th><th>Bought Date</th><th>Price(Rs)</th><th>Valid Upto(days)</th><th>Sold By</th><th>Actions</th><th>Files</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
                else{
                    $('#package_dash_table').empty();
                    $('#daily_care').empty();
                    $('#home_care').empty();
                    var j = 0;

                    var b = data1.Table;
                    var cb = data1.Table1;
                    $('#livepaccount').html(cb[0].no_of_package);

                    tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="' + id + '" />');
                    tr.append("<thead><tr><th>S No</th><th>Patient Name/Phone Number</th><th>Package Name</th><th>Bought Date</th><th>Price(Rs)</th><th>Valid Upto</th><th>Sold By</th><th>Actions</th><th>Files</th></tr></thead><tbody>");
                    $.each(b, function (i, emp) {
                        j++;
                        $('#pacpatientcount').html(b.length);
                        $('#livepaccount').html(emp.no_of_live_package);
                        var patdata = "-", sold_by = '', pat_numer = '', phlebo_doctor_name = '';
                        if (emp.created_by == "USD") {
                            sold_by = "DOCTOR";
                        }
                        else {
                            sold_by = "MOBILE APP";
                        }
                        if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                            pat_numer = "-"
                        }
                        else {
                            pat_numer = emp.phone_number_1;
                        }
                        patdata = emp.first_name + '/' + pat_numer + '/' + emp.patient_id;
                        val = 1;
                        if (Package_category == "hospital_care") { val = 2 }
                        row_data = "<tr><td>" + j + "</td><td>" + patdata + "</td><td>" + emp.package_name + "</td><td>" + (emp.date_of_purchase) + "</td><td>" + emp.cost_of_package + "</td><td>" + emp.valid_upto + "</td><td>" + sold_by + "</td><td><button class='UM_82 btn btn-primary btn-xs'><span class='' data-toggle='popover' title='View Coupon Details' data-target='#urpkgeView' onclick=package_view(" + emp.package_purchase_details_id + "," + val + ")>Coupon Details</span></button></td><td><button onclick=files_package('" + emp.package_purchase_details_id + "')  data-toggle='modal' data-target='#appointment_files'>View Files</button></td></tr>";
                        tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    var id = '';
                    var divId = 'package_dash_table';
                    if (Package_category == "hospital_care") { id = "pkgeTable"; divId = "package_dash_table"; } if (Package_category == "daily_care") { id = "tbl_daily_care"; divId = "daily_care"; } if (Package_category == "home_care") { id = "tbl_home_care"; divId = "home_care"; }
                    $.when($('#' + divId).append(tr)).then($('#' + id).DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                    check_priviliges();
                }
            }
            else {
                console.log(data1);
            }
        },
    });
}
function files_package(package_id) {
    debugger;
    var package_data = {
        indicator_id: "FP",
        package_id: package_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 data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#tblAppointmentFiles_body').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table[0].package_files != '' && data.Table[0].package_files != null) {
                        $('#health_concern').html(data.Table[0].health_concern);
                    }
                    else {
                        $('#health_concern').html("    -");
                    }
                    if (data.Table[0].package_files != '' && data.Table[0].package_files != null) {

                        var files = data.Table[0].package_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);


                    }
                    else {
                        $('#tblAppointmentFiles_body').html(Norecord);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}




function daily_care(package_type, Package_category) {
    debugger;
    $("#Live_Package").show();
    $("#setuppackageicon").show();
    $("#Package_Patients").show();
    $("#Sell_To_Patient").show();
    $("#Total_Home_Collection_Order").hide();
    $("#Self_Collection").hide();
    $("#Third_Party_Collection").hide();
    var curdate = "";
    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);
    }


    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);
    }
    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);
    }
    else {
        curdate = $('#app_date_current').html();
        var res = curdate.split("/");
        curdate = res[2] + '-' + res[1] + '-' + res[0];
    }
    curdate = $('#app_date_current').html();
    var res = curdate.split("/");
    curdate = res[2] + '-' + res[1] + '-' + res[0];

    var package_data = {
        indicator_id: 'daily',
        doctor_id: $('#HiddenDoctorID').val(),
        hospital_id: $('#HospitalId').val(),
        package_type: package_type,
        coupon_useby_date: curdate
    }
    $.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) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (Package_category == "daily_care") { id = "tbl_daily_care" }
                if (jQuery.isEmptyObject((data1))) {
                    if (Package_category == "daily_care" || Package_category == "home_care") {
                        tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="' + id + '" />');
                        tr.append("<thead><tr><th>S No</th><th>Patient Name/Phone Number</th><th>Package Name</th><th>Coupon status</th><th>Address</th><th>Package Date</th><th>Slot Time</th><th>Phlebo</th><th>Appointment Date</th><th>Actions</th><th>Files</th></tr></thead><tbody>");
                        tr.append("</tbody>");
                    }
                }
                else {
                    $('#daily_care').empty();
                    var j = 0;

                    var b = data1.Table;

                    if (Package_category == "daily_care" || Package_category == "home_care") {
                        tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="' + id + '" />');
                        tr.append("<thead><tr><th>S No</th><th>Patient Name/Phone Number</th><th>Package Name</th><th>Coupon status</th><th>Address</th><th>Package Date</th><th>Slot Time</th><th>Phlebo</th><th>Appointment Date</th><th>Actions</th><th>Files</th></tr></thead><tbody>");
                    }

                    $.each(b, function (i, emp) {
                        j++;
                        $('#pacpatientcount').html(b.length);
                        $('#livepaccount').html(emp.no_of_live_package);
                        var patdata = "-", sold_by = '', pat_numer = '', phlebo_doctor_name = '';

                        if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                            pat_numer = "-"
                        }
                        else {
                            pat_numer = emp.phone_number_1;
                        }
                        patdata = emp.first_name + '/' + pat_numer + '/' + emp.patient_id;

                        if (Package_category == "daily_care" || Package_category == "home_care") {
                            var status = '';
                            var details = '&nbsp;&nbsp;&nbsp;<a class="btn btn-primary" href="javascript:void(0)"; onclick=\'phlebo_detail(\"' + emp.patient_id + '\",\"' + emp.first_name + '\",\"' + pat_numer + '\",\"' + emp.phlebo_id + '\",\"' + emp.service + '\")\'>Details</a>';
                            if (emp.phlebo_status == 1) { status = "Reject" } else if (emp.phlebo_status == 2) { status = '<span>Assigned</span>' + details }
                            else if (emp.phlebo_status == 3) { status = "Accept" + details }
                            else if (emp.phlebo_status == 4) { status = "Navigating to Customer Location" + details }
                            else if (emp.phlebo_status == 5) { status = "Start Service" + details }
                            else if (emp.phlebo_status == 6) { status = "Add Notes" + details }
                            else if (emp.phlebo_status == 7) { status = "End Service" + details }
                            else if (emp.phlebo_status == 8) { status = "Feedback" + details }
                            else { status = '<button><span class="red" data-toggle="popover" title="Assign Service Provider" data-target="#urpkgeView" onclick=\'Assign_Service_Provider(\"' + emp.package_purchase_details_id + '\",\"' + emp.coupon_id + '\",\"' + emp.package_first_date + '\",\"' + emp.package_first_time + '\")\'>Assign Service Provider</span></button>' };
                            if (emp.phlebo_doctor_name != null && (emp.service != null && emp.service != '')) {
                                phlebo_doctor_name = emp.phlebo_doctor_name + '(' + emp.service + ')';
                            }
                            else {
                                if (emp.phlebo_doctor_name != null) phlebo_doctor_name = emp.phlebo_doctor_name;
                                else phlebo_doctor_name = '-';
                            }
                            if (emp.slot_start_time == "" || emp.slot_start_time == null) { emp.slot_start_time = "-" }
                            if (emp.coupon_status == 1) { emp.coupon_status = 'Active' } else { emp.coupon_status = 'Used' };
                            var address = emp.address_line_1 + ',' + emp.address_line_2 + ',' + emp.town_village;
                            row_data = "<tr><td>" + j + "</td><td>" + patdata + "</td><td>" + emp.package_name + "</td><td>" + emp.coupon_status + "</td><td>" + address + "</td><td>" + emp.package_first_date + "</td><td>" + emp.package_first_time + "</td><td>" + phlebo_doctor_name + "</td><td>" + emp.slot_start_time + "</td><td>" + status + "</td><td><button onclick=files_package('" + emp.package_purchase_details_id + "')  data-toggle='modal' data-target='#appointment_files'>View Files</button></td></tr>";
                        }
                        tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    var id = '';
                    var divId = 'package_dash_table';
                    if (Package_category == "hospital_care") { id = "pkgeTable"; divId = "package_dash_table"; } if (Package_category == "daily_care") { id = "tbl_daily_care"; divId = "daily_care"; } if (Package_category == "home_care") { id = "tbl_home_care"; divId = "home_care"; }
                    $.when($('#' + divId).append(tr)).then($('#' + id).DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));

                }
            }
            else {
                console.log(data1);
            }
        },
    });
}


function phlebo_detail(patdata, name, phone_num, id, service) {
    $('#Service_Details').modal('toggle');
    $('.PatientId').html(patdata);
    if (service != null && service != '') $('.Patient_name').html(name + '(' + service + ')');
    else $('.Patient_name').html(name);
    $('.Patient_number').html(phone_num);
    var package_data = {
        Dml_Indicator: "HL",
        Phlebo_id: id,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/Phlebo_Status',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            console.log(data);
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                var tr = '', j = 0, file_tr = '', k = 0;
                $('#phlebo_log,#phleboattach_log,#physiotreatmenttype').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    if (data.Table.length > 0) {
                        for (var i = 0; i < data.Table.length; i++) {
                            var status = '', notes = '-'; j++;
                            if (data.Table[i].phlebo_status == 1) { status = "Reject" }
                            if (data.Table[i].phlebo_status == 2) { status = "Assigned" }
                            if (data.Table[i].phlebo_status == 3) { status = "Accept" }
                            if (data.Table[i].phlebo_status == 4) { status = "Navigating to Customer Location" }
                            if (data.Table[i].phlebo_status == 5) { status = "Start Service" }
                            if (data.Table[i].phlebo_status == 6) { status = "Add Notes", notes = data.Table[i].notes }
                            if (data.Table[i].phlebo_status == 7) { status = "End Service" }
                            if (data.Table[i].phlebo_status == 8) { status = "Feedback" }
                            tr = tr + '<tr><td>' + j + '</td><td>' + status + '</td><td>' + notes + '</td><td>' + data.Table[i].created_on + '</td></tr>';
                        }
                        $('#phlebo_log').html(tr);
                    }
                    if (data.Table1.length > 0) {
                        var files = data.Table1[0].homecarefiles;
                        files = files.split(",");
                        for (var i = 0; i < files.length; i++) {
                            k++;
                            var d, n, drloimage;
                            d = new Date();
                            n = d.getTime();
                            var file = $('#hdnHomeCareFilesView').val() + "HomeCareFiles/HomeCareFiles/" + files[i] + "?" + n;
                            file_tr = file_tr + '<tr><td>' + k + '</td><td><a href = ' + file + ' target=_blank> File </a></td><td>' + data.Table1[0].created_on + '</td></tr>';
                        }
                        $('#phleboattach_log').html(file_tr);
                    }
                    if (data.Table2.length > 0) {
                        $('#physiotreatmenttype').html(data.Table2[0].treatment_name);
                    }
                    else {
                        $('#physiotreatmenttype').html("-");
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function Assign_Service_Provider(id, coupon_id, date, time) {

    $('#req_date,#req_time,#hndpackage_purchase_details_id,#hndcoupon_id,#hcphoto,#hcname,#hcphone_number,#hcpackname,#hcpackcost,#hcnever_expiry').val('');
    $('#req_date,#req_time,#hndpackage_purchase_details_id,#hndcoupon_id,#hcphoto,#hcname,#hcphone_number,#hcpackname,#hcpackcost,#hcnever_expiry,#hcpackage_type,#hcpackage_category').html('');
    $('#tblPatientAppiontment').html('');
    $('#req_date').val(date);
    $('#req_time').val(time);
    $('#Home_care_Service_Provider').modal('toggle');
    $('#hndpackage_purchase_details_id').val(id);
    $('#hndcoupon_id').val(coupon_id);
    var package_data = {
        Dml_Indicator: "S",
        package_purchase_details_id: id,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/Phlebo_Status',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            console.log(data);
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    var image = '';
                    for (var i = 0; i < data.Table.length; i++) {
                        if (data.Table[i].photo != "") {
                            image = "https://app.parvathyhospital.com/UserprofileImg/" + data.Table[i].photo;
                        }
                        else {
                            image = "/Content/img/profile_icon.png";
                        }
                        $('#hcphoto').attr('src', "" + image + "");
                        $('.PatientId').html(data.Table[i].patient_id);
                        $('#hcname').html(data.Table[i].first_name);
                        $('#hcphone_number').html(data.Table[i].phone_number_1);

                        $('#hcpackname').html(data.Table[i].package_name);
                        $('#hcpackcost').html(data.Table[i].cost_of_package);


                        $('#hcnever_expiry').html(data.Table[i].never_expiry);
                        if (data.Table[i].never_expiry == 1) {
                            $('#hcnever_expiry').html('Yes');
                            $('#hcpackexdate').html('-');
                        }
                        else {
                            $('#hcnever_expiry').html('No');
                            $('#hcpackexdate').html(data.Table[i].expire_date);
                        }
                        if (data.Table[i].package_type == 1) {
                            $('#hcpackage_type').html('Home Care');
                        }
                        else {
                            $('#hcpackage_type').html('Hospital Care');
                        }
                        if (data.Table[i].package_category == 1) { $('#hcpackage_category').html('Health Package'); }
                        else if (data.Table[i].package_category == 2) { $('#hcpackage_category').html('Master Health Check up'); }
                        else if (data.Table[i].package_category == 3) { $('#hcpackage_category').html('Doctor Home Visit'); $('#SelPhlebo').val(3); }
                        else if (data.Table[i].package_category == 4) { $('#hcpackage_category').html('Nurse Home Visit'); $('#SelPhlebo').val(4); }
                        else if (data.Table[i].package_category == 5) { $('#hcpackage_category').html('Physio Home Visit'); $('#SelPhlebo').val(5); }
                        else if (data.Table[i].package_category == 6) { $('#hcpackage_category').html('Vaccination'); }
                        LoadDoctor();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#SelPhlebo').change(function () {
    LoadDoctor();
});

function LoadDoctor() {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "DL",
        doctor_designation: $('#SelPhlebo option:selected').text(),
        hospital_id: $('#HospitalId').val(),

    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#SelDoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $('#SelDoctor').html(default_opt + SelRole);
                }
                else {

                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';
                        }
                        $('#SelDoctor').html(default_opt + SelRole);
                    }
                    else {
                        $('#SelDoctor').empty();
                        var default_opt = '<option value="0">--Select--</option>';
                        $('#SelDoctor').html(default_opt + SelRole);
                    }

                }

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


$("#start_date").change(function () {
    AddAppiontment();
});


function AddAppiontment() {
    var Dml_Indicator;
    var d = new Date();
    var strDate = (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + "/" + ('0' + (d.getMonth() + 1)).slice(-2) + "/" + d.getFullYear();

    if ($.trim($('#SelDoctor :selected').val()) == "" || $('#SelDoctor :selected').val() == "0") {
        $('#PSelDoctor').show();
        $('#PSelDoctor').fadeOut(8000);
        $('#PSelDoctor').html('Select Doctor');
        $('#SelDoctor').focus();
        $('#SelDoctor :selected').val('0');
        return false;
    }
    if ($.trim($('#start_date').val()) == "") {
        $('#Pstart_date').show();
        $('#Pstart_date').fadeOut(8000);
        $('#Pstart_date').html('Select date');
        $('#start_date').focus();
        $('#start_date').val('');
        return false;
    }
    if (strDate == $('#start_date').val()) {

        Dml_Indicator = 'TAS';
    }
    else {
        Dml_Indicator = 'AS';
    }

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

    var start_date_check = new Date(start_date);
    var today_date = new Date();

    var AppiontmentData = {
        Schedule_date: start_date,
        doctor_id: $('#SelDoctor').val(),
        Dml_Indicator: Dml_Indicator,
        appointment_type: 1
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AppiontmentData),
        success: function (data) {
            console.log(data);
            $('#tblPatientAppiontment').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                if (data.length > 2) {

                    var PatientAppiontment = '';
                    var hospital_id = '';
                    var j = 1;
                    for (var i = 0; i < data1.length; i++) {
                        if (i == 0) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                        }
                        else if (data1[i].hospital_id != hospital_id) {
                            PatientAppiontment = PatientAppiontment + '<div class="clearfix"></div><div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                        }
                        else {
                        }
                        if ((data1[i].doctor_schedule_type == 1 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 7)) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        //else if ((data1[i].doctor_schedule_type == 2 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6) && AppointmentType == 2) {
                        //    PatientAppiontment = PatientAppiontment + '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        //}
                        //else if ((data1[i].doctor_schedule_type == 3 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6 || data1[i].doctor_schedule_type == 7) && AppointmentType == 3) {
                        //    PatientAppiontment = PatientAppiontment + '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        //}
                        hospital_id = data1[i].hospital_id;

                        j++;


                    }
                    if (PatientAppiontment == '' || PatientAppiontment == null) {
                        //var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                        var values = '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" onclick="patient_time_insert()"><i class="fa fa-clock-o" aria-hidden="true">As Per Patient requested Time / ' + $('#req_date').val() + ' ' + $('#req_time').val() + '</i></button></div>'
                        $('#tblPatientAppiontment').append(values);
                    }
                    else {
                        //var values = '<div class="NA" style="text-align:center;"><br/></div>';
                        var values = '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" onclick="patient_time_insert()"><i class="fa fa-clock-o" aria-hidden="true">As Per Patient requested Time / ' + $('#req_date').val() + ' ' + $('#req_time').val() + '</i></button></div>'
                        $('#tblPatientAppiontment').append(PatientAppiontment + '</br>' + values);
                    }
                }
                else {
                    //var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                    var values = '<div class="col-md-2"><button type="button" class="btn btn-primary btn-xs" onclick="patient_time_insert()"><i class="fa fa-clock-o" aria-hidden="true">As Per Patient requested Time / ' + $('#req_date').val() + ' ' + $('#req_time').val() + '</i></button></div>'
                    $('#tblPatientAppiontment').append(values);
                }
                $('#datePickToggle').css('display', 'block');
            }
            else {
                console.log(data1);
            }
        }

    });
}

function datefunction() {
    var date = $('#datepicker').val();
    $('#app_date_current').html(date);
    var package_type = 1;
    daily_care(package_type, 'daily_care');
}

function insert(id) {
    $('#packloader').show();
    var Dml_Indicator = "PAPP";
    if ($('#slotId').val() != '' && $('#slotId').val() != null) {
        Dml_Indicator = "DAPP";
    }

    $('#shade_slot').show();
    $('#txtAppointmentTiming').val($('#' + id).text());

    $('#slot_id').val(id);

    var Patient_id = $('#patient_id1').val();
    var DoctorData = {
        package_purchase_details_id: $('#hndpackage_purchase_details_id').val(),
        coupon_id: $('#hndcoupon_id').val(),
        phlebo_status: 2,
        phlebo_doctor_id: $('#SelDoctor').val(),
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: "I",
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('.PatientId').html(),
        appointment_type: '1',
        doctor_appointment_slot_id: id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/Phlebo_Status',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#packloader').hide();
                }
                else {

                    $('#packloader').hide();
                    toastr.success("Appointment Booked Successfully");
                    $('#Clsservices').click();
                    daily_care('1', 'daily_care');
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


function patient_time_insert() {
    debugger;
    $('#packloader').show();
    $('#shade_slot').show();
    // $('#txtAppointmentTiming').val($('#' + id).text());
    var day;
    switch ($('#req_time').val()) {
        case '1am':
            day = "01:00";
            break;
        case '2am':
            day = "02:00";
            break;
        case '3am':
            day = "03:00";
            break;
        case '4am':
            day = "04:00";
            break;
        case '5am':
            day = "05:00";
            break;
        case '6am':
            day = "06:00";
            break;
        case '7am':
            day = "07:00";
            break;
        case '8am':
            day = "08:00";
            break;
        case '9am':
            day = "09:00";
            break;
        case '10am':
            day = "10:00";
            break;
        case '11am':
            day = "11:00";
            break;
        case '12am':
            day = "00:00";
            break;
        case '1pm':
            day = "13:00";
            break;
        case '2pm':
            day = "14:00";
            break;
        case '3pm':
            day = "15:00";
            break;
        case '4pm':
            day = "16:00";
            break;
        case '5pm':
            day = "17:00";
            break;
        case '6pm':
            day = "18:00";
            break;
        case '7pm':
            day = "19:00";
            break;
        case '8pm':
            day = "20:00";
            break;
        case '9pm':
            day = "21:00";
            break;
        case '10pm':
            day = "22:00";
            break;
        case '11pm':
            day = "23:00";
            break;
        case '12pm':
            day = "24:00";
            break;
    }
    var Patient_id = $('#Patient_Id').val();
    var DoctorData = {
        package_purchase_details_id: $('#hndpackage_purchase_details_id').val(),
        coupon_id: $('#hndcoupon_id').val(),
        phlebo_status: 2,
        phlebo_doctor_id: $('#SelDoctor').val(),
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: "ASPB",
        doctor_id: $('#SelDoctor').val(),
        patient_id: $('.PatientId').html(),
        appointment_type: '1',
        request_date: $('#req_date').val(),
        request_time: day
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/Phlebo_Status',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#packloader').hide();
                }
                else {

                    $('#packloader').hide();
                    toastr.success("Appointment Booked Successfully");
                    $('#Clsservices').click();
                    daily_care('1', 'daily_care');
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}



function package_view(id, val) {
    var package_data = {
        indicator_id: "PVIEW",
        package_purchase_details_id: 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) {
            $('#package_coupon_table').empty();
            $('#urpkgeView').modal('toggle');
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>Coupon Id</th><th>Coupon Type</th><th>Coupon Status</th><th>Issued Date</th><th>Valid Upto</th><th>Appointment date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
                else {
                    var image = '', coupon = '', j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '', type = '-';
                    var b = data1.Table;
                    var c = data1.Table1;
                    $.each(b, function (i, emp) {
                        if (emp.photo != "") {
                            image = "https://app.medwayhospitals.com/UserprofileImg/" + emp.photo;
                        }
                        else {
                            image = "/Content/img/profile_icon.png";
                        }
                        $('#casePhoto1').attr('src', "" + image + "");
                        $('#patname').html(emp.first_name);
                        $('#patnum').html(emp.phone_number_1);
                        $('#packname').html(emp.package_name);
                        $('#packcost').html(emp.cost_of_package);
                        $('#packexdate').html((emp.expire_date).split('T')[0]);
                        $('#Hdnpatient_id').val(emp.patient_id);
                    });
                    tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>Coupon Id</th><th>Coupon Type</th><th>Coupon Status</th><th>Issued Date</th><th>Valid Upto</th><th>Appointment date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                    $.each(c, function (i, emp) {
                        j++;
                        if (emp.coupon_status == 1) coupon = "Active";
                        else if (emp.coupon_status == 3) coupon = "Expired";
                        else if (emp.coupon_status == 4) coupon = "Cancelled";
                        else if (emp.coupon_status == 2) coupon = "Used";
                        if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                        else coupon_issued_date = emp.coupon_issued_date;
                        if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                        else coupon_consumed_date = emp.coupon_consumed_date;
                        if (emp.coupon_consumed_by == '' || (emp.coupon_consumed_by) == null) coupon_consumed_by = '-';
                        else coupon_consumed_by = emp.coupon_consumed_by;
                        if (emp.type == "1") type = "Consulting";
                        else if (emp.type == "2") type = "Lab";
                        else if (emp.type == "3") type = "Pharmacy";
                        else type = "Home Visit";
                        if (emp.coupon_useby_date == "" || emp.coupon_useby_date == null) {
                            emp.coupon_useby_date = '-';
                        }
                        if (coupon_consumed_by == '-') {
                            row_data = "<tr><td>" + emp.coupon_id + "</td><td>" + type + "</td><td>" + coupon + "</td><td>" + emp.created_on + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.coupon_useby_date + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view btn btn-submit btn-xs mr-15' data-toggle='popover' title='Change Status to Completed' data-target='#urpkgeView' onclick=patient_package_completed('" + emp.coupon_id + "')><i class='fa fa-check' aria-hidden='true'></i></span><span class='ur-pkge-cancel ur-pkge-view btn btn-danger btn-xs' data-toggle='popover' title='Cancel Coupon' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                        }
                        else {
                            row_data = "<tr><td>" + emp.coupon_id + "</td><td>" + type + "</td><td>" + coupon + "</td><td>" + emp.created_on + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.coupon_useby_date + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                        } tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function changedefault_package(e) {
    var photoSrc = "";
    console.log("Image Error")
    $(e).attr("src", photoSrc)
}

function patient_package_completed(id) {
    $('#pack_coupon_id').val(id);
    var package_data = {
        indicator_id: "COTPS",
        coupon_id: $('#pack_coupon_id').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_coupon_otp',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                $('#tblotpcheck').modal('toggle');
            }
            else {
                console.log(data);
            }
        }
    });
}


function otp_check_completed() {
    if ($.trim($('#pack_otp').val()).length == "") {
        $('#Ppack_otp').show();
        $('#Ppack_otp').fadeOut(8000);
        $('#Ppack_otp').html('Please enter OTP');
        $('#pack_otp').focus();
        $('#pack_otp').val('');
        return false;
    }
    if ($.trim($('#pack_otp')).length > 0) {
        var package_data = {
            indicator_id: "COTPV",
            coupon_id: $('#pack_coupon_id').val(),
            patient_id: $('#Hdnpatient_id').val(),
            otp: $('#pack_otp').val(),
            doctor_id: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PackageDetails/package_coupon_otp',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(package_data),
            success: function (data) {
                $('#pack_otp').val('');
                $('#tblotpcheck').modal('toggle');
                debugger;
                var j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '';
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var b = data1.Table;
                        if (b[0].Cid == "failure") {
                            toastr.warning("Invalid OTP");
                        }
                        else {
                            $('#package_coupon_table').empty();
                            tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                            tr.append("<thead><tr><th>S No</th><th>Coupon Id</th><th>Coupon Status</th><th>Coupon Expire Date</th><th>Issued Date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                            $.each(b, function (i, emp) {
                                j++;
                                if (emp.coupon_status == 1) coupon = "Active";
                                else if (emp.coupon_status == 3) coupon = "Expired";
                                else if (emp.coupon_status == 4) coupon = "Cancelled";
                                else if (emp.coupon_status == 2) coupon = "Used";
                                if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                                else coupon_issued_date = emp.coupon_issued_date;
                                if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                                else coupon_consumed_date = emp.coupon_consumed_date;
                                if (emp.coupon_consumed_by == '' || emp.coupon_consumed_by == null) coupon_consumed_by = '-';
                                else coupon_consumed_by = emp.coupon_consumed_by
                                if (coupon_consumed_by == '-') {
                                    row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view' data-toggle='popover' title='Change Status' data-target='#urpkgeView' onclick=patient_package_expired('" + emp.coupon_id + "')><i class='fa fa-eye' aria-hidden='true'></i></span><span class='ur-pkge-cancel' data-toggle='popover' title='Cancell Package' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                                }
                                else {
                                    row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                                }
                                tr.append(row_data);
                            });
                            tr.append("</tbody>");
                            $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                                "columnDefs": [{
                                    "orderable": false,
                                }]
                            }));
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}


function patient_package_cancel(id) {
    $('#pack_coupon_id').val(id);
    var package_data = {
        indicator_id: "COTPS",
        coupon_id: $('#pack_coupon_id').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_coupon_otp',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data=JSON.parse(data);
            if (data.msg == "Success") {
                $('#tblotpcheck1').modal('toggle');
            }
            else {
                console.log(data);
            }
        }
    });
}


function otp_check_cancel() {
    if ($.trim($('#pack_otp1').val()).length == "") {
        $('#Ppack_otp1').show();
        $('#Ppack_otp1').fadeOut(8000);
        $('#Ppack_otp1').html('Please enter OTP');
        $('#pack_otp1').focus();
        $('#pack_otp1').val('');
        return false;
    }
    if ($.trim($('#pack_otp1')).length > 0) {
        var package_data = {
            indicator_id: "COTPD",
            coupon_id: $('#pack_coupon_id').val(),
            patient_id: $('#Hdnpatient_id').val(),
            otp: $('#pack_otp1').val(),
            doctor_id: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PackageDetails/package_coupon_otp',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(package_data),
            success: function (data) {
                $('#pack_otp1').val('');
                $('#tblotpcheck1').modal('toggle');
                debugger;
                var j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '';
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var b = data1.Table;
                    if (b[0].Cid == "failure") {
                        toastr.warning("Invalid OTP");
                    }
                    else {
                        $('#package_coupon_table').empty();
                        tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                        tr.append("<thead><tr><th>S No</th><th>Coupon Id</th><th>Coupon Status</th><th>Coupon Expire Date</th><th>Issued Date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                        $.each(b, function (i, emp) {
                            j++;
                            if (emp.coupon_status == 1) coupon = "Active";
                            else if (emp.coupon_status == 3) coupon = "Expired";
                            else if (emp.coupon_status == 4) coupon = "Cancelled";
                            else if (emp.coupon_status == 2) coupon = "Used";
                            if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                            else coupon_issued_date = emp.coupon_issued_date;
                            if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                            else coupon_consumed_date = emp.coupon_consumed_date;
                            if (emp.coupon_consumed_by == '' || emp.coupon_consumed_by == null) coupon_consumed_by = '-';
                            else coupon_consumed_by = emp.coupon_consumed_by
                            if (coupon_consumed_by == '-') {
                                row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view btn btn-submit btn-xs mr-15' data-toggle='popover' title='Change Status to Completed' data-target='#urpkgeView' onclick=patient_package_completed('" + emp.coupon_id + "')><i class='fa fa-eye' aria-hidden='true'></i></span><span class='ur-pkge-cancel ur-pkge-view btn btn-danger btn-xs' data-toggle='popover' title='Decline Coupon' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                            }
                            else {
                                row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                            }
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}



function patient_package_delete(id) {
    var package_data = {
        indicator_id: "POTP",
        package_purchase_details_id: id,
        doctor_id: $('#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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

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

$('#searchpatient').on('input', function () {
    $('#searchpatient').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/PackageDetails/AutoComplete_PatName?rep_list=" + $('#searchpatient').val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    console.log(data);
                    response($.map(data, function (item) {
                        return { label: item.patient_name, value: item.patient_name };
                    }));
                }
            });
        }
    });
});
$('#patsearch').click(function () {
    $('#patdata').hide();
    $('#patient_name').html('');
    $('#patient_number').html('');
    $('#patient_id1').val('');
    $('#packagecard').html('');
    if ($.trim($('#searchpatient').val()).length > 0) {
        $('#packagecard').empty();
        var name1 = [], patient_id = '';
        name = $('#searchpatient').val();
        name1 = name.split('/');
        if (name1[2] != "-") {
            patient_id = name1[2];
        }
        else {
            patient_id = '';
        }
        var package_data = {
            indicator_id: "PSR",
            patient_id: patient_id,
            hospital_id: $('#HospitalId').val(),
            doctor_id: $('#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 data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        $('#patdata').show();
                        var image = '', coupon = '', ph_number;

                        console.log(data1);
                        var b = data1.Table;
                        var c = data1.Table1;
                        var d = data1.Table;
                        var filepath = $('#hdnfilepath1').val();
                        $.each(d, function (i, emp1) {
                            ph_number = emp1.phone_number_1;
                        });
                        if (ph_number != null && ph_number != "") {
                            $.each(b, function (i, emp) {
                                if (emp.photo != "") {
                                    image = filepath + emp.photo;
                                }
                                else {
                                    image = "/Content/img/profile_icon.png";
                                }

                                $('#patient_photo').attr('src', "" + image + "");
                                $('#patient_name').html(emp.first_name);
                                $('#patient_number').html(emp.phone_number_1);
                                $('#patient_id1').val(emp.patient_id);
                            });
                            $.each(c, function (i, emp) {
                                var pkg_price;
                                if (emp.package_image_url != "" || emp.package_image_url != null) {
                                    //image = "https://photos.parvathyhospital.com/" + emp.doctor_id + "/Package/" + emp.package_image_url;
                                    image = filepath + emp.doctor_id + "/Package/" + emp.package_image_url;
                                    //image = "/Content/img/health_package.jpeg";
                                }
                                else {
                                    image = "/Content/img/profile_icon.png";
                                }
                                if (emp.discount_type == "1") {
                                    pkg_price = (parseFloat(emp.price) - parseFloat(emp.discount)).toFixed(2);
                                }
                                else if (emp.discount_type == "2") {
                                    pkg_price = (parseFloat(emp.price) * parseFloat(emp.discount)) / parseInt('100');
                                    pkg_price = (parseFloat(emp.price) - parseFloat(pkg_price)).toFixed(2);
                                }
                                else {
                                    pkg_price = emp.price;
                                }
                                patient_id = $('#patient_id1').val();
                                var package_validity_date = '-';
                                if (emp.package_validity_date != '' && emp.package_validity_date != null && emp.package_validity_date != "null") {
                                    package_validity_date = (emp.package_validity_date).split('T')[0];
                                }
                                //coupon = coupon + " <a href='#' class='ur-sell-pkge' id='individualcard' onclick = get_package_details('"+ emp.package_id +"')><div class='col-md-6 pkg-detail-card'><div class='pkge_detail_block_card col-md-12'><div class='col-md-12 col-sm-3 col-xs-4 padding0'><div class='package-prof_imgblock text-center'><img src=" + image + " class='img-responsive imgphoto' id='packimage'></div></div><div class='col-md-12 col-sm-8 col-xs-8 padding0'><div class='col-md-12 text-center m22'><p class='pkage-name' id='sellpackage_name'>" + emp.package_name + "</p><p class='pkage-name' id='sellpack_cost'>" + emp.price + "</p><p class='pkage-name' id='sellpack_expire_date'>" + (emp.package_validity_date).split('T')[0] + "</p><p class='pkage-name' id='packhigh'>" + emp.price + "</p></div></div></div></div></a>";<p class='pkage-name' id='packhigh'>" + emp.price + "</p>
                                //coupon = coupon + " <a href='#' class='ur-sell-pkge' id='individualcard' onclick = package_invoice_generation(this) data-id=" + emp.package_id + " data-name=" + pkg_price + "><div class='col-md-6 pkg-detail-card'><div class='pkge_detail_block_card col-md-12'><div class='col-md-12 col-sm-3 col-xs-4 padding0'><div class='package-prof_imgblock text-center'><img src=" + image + " class='img-responsive imgphoto' id='packimage'></div></div><div class='col-md-12 col-sm-8 col-xs-8 padding0'><div class='col-md-12 text-center m22'><p class='pkage-name' id='sellpackage_name'>Package Name: " + emp.package_name + "</p><p class='pkage-name' id='sellpack_cost1'>Price(Rs): " + emp.price + "</p><p class='pkage-name' id='sellpack_expire_date'> Valid Date: " + (emp.package_validity_date).split('T')[0] + "</p><p class='pkage-name' id='sellpack_cost'> After Discount: " + pkg_price + "</p></div></div></div></div></a>";
                                //package_type
                                var package_category = '';
                                if (emp.package_category == 1) { package_category = 'Health Package'; }
                                else if (emp.package_category == 2) { package_category = 'Master Health Check up'; }
                                else if (emp.package_category == 3) { package_category = 'Doctor Home Visit' }
                                else if (emp.package_category == 4) { package_category = 'Nurse Home Visit' }
                                else if (emp.package_category == 5) { package_category = 'Physio Home Visit' }
                                else if (emp.package_category == 6) { package_category = 'Vaccination' }
                                var package_type = '';
                                if (emp.package_type == 1) {
                                    package_type = "<div class='col-md-12 hp-name-categories' '>Home Care - " + package_category + "</div>";
                                }
                                else {
                                    package_type = "<div class='col-md-12 hp-name-categories'>Hospital Care - " + package_category + "</div>";
                                }
                                if (emp.package_type == 1)
                                { coupon = coupon + " <a href='#' class='ur-sell-pkge' id='individualcard' onclick = patient_address(this) data-id=" + emp.package_id + " data-name=" + pkg_price + "><div class='col-md-4 pkg-detail-card'><div class='pkge_detail_block_card col-md-12'>" + package_type + "<div class='col-md-12 col-sm-8 col-xs-8 padding0'><div class='col-md-12 text-center m22'><p class='pkage-name' id='sellpackage_name'>" + emp.package_name + "</p><p class='pkage-name' id='sellpack_cost1'><i class='fa fa-inr aria-hidden='true'></i> :<s> " + emp.price + "</s> " + pkg_price + "</p><p class='pkage-name' id='sellpack_expire_date'> Valid Date: " + package_validity_date + "</p></div></div></div></div></a>"; }
                                else {
                                    coupon = coupon + " <a href='#' class='ur-sell-pkge' id='individualcard' onclick = package_invoice_generation(this) data-id=" + emp.package_id + " data-name=" + pkg_price + "><div class='col-md-6 pkg-detail-card'><div class='pkge_detail_block_card col-md-12'>" + package_type + "<div class='col-md-12 col-sm-8 col-xs-8 padding0'><div class='col-md-12 text-center m22'><p class='pkage-name' id='sellpackage_name'>" + emp.package_name + "</p><p class='pkage-name' id='sellpack_cost1'><i class='fa fa-inr aria-hidden='true'></i> :<s>" + emp.price + "</s> " + pkg_price + "</p><p class='pkage-name' id='sellpack_expire_date'> Valid Date: " + package_validity_date + "</p></div></div></div></div></a>";
                                }
                            });
                            $('#packagecard').html(coupon);
                        }
                        else {
                            toastr.warning("Patient Phone Number is not registered. Please Update the Patient Phone number.");
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
    else {
        toastr.warning("Please Select the Patient");
    }
});

function patient_address(e) {
    debugger;
    $('#modal_Patient_address').modal('toggle');
    $('.PatientId').html($('#patient_id1').val());
    $('#adname').html($('#patient_name').html());
    $('#adphone_number').html($('#patient_number').html());
    loadcountry();
    var id = e.getAttribute("data-id")
    var price_amt = e.getAttribute("data-name");
    $('#cur_package_id').val(id);
    $('#cur_package_price_amt').val(price_amt);
    var package_data = {
        patient_id: $('#patient_id1').val(),
        Indicator_id: "SA",
        lab_id: "L1"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/patient_address',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            
            console.log(data);
            var tr = '';
            $('#tblpatientaddress').empty();
            if (jQuery.isEmptyObject((data)) || data.length == 0) {
                //tr = tr + '<a href="javascript:void(0);"><div class="col-sm-12" onclick=address_ins("New")><p>Add new patients</p></div></a>';
                tr = tr + '<div class="col-sm-12 patient-detail-card" onclick=address_ins("New")><p>Add new address</p></div>';
                $('#tblpatientaddress').html(tr);
            }
            else {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    //if (data.patient_address.length > 0) {
                    //    for (var i = 0; i < data.patient_address.length; i++) {
                    //        if (data.patient_address[i].country == "" || data.patient_address[i].country == null) {
                    //            data.patient_address[i].country = '';
                    //        }
                    //        if (data.patient_address[i].state == "" || data.patient_address[i].state == null) {
                    //            data.patient_address[i].state = '';
                    //        }
                    //        if (data.patient_address[i].city == "" || data.patient_address[i].city == null) {
                    //            data.patient_address[i].city = '';
                    //        }
                    //        tr = tr + '<div class="col-sm-12 patient-detail-card" onclick=address_ins(' + data.patient_address[i].address_id + ')><p>' + data.patient_address[i].first_name + '</p><span>' + data.patient_address[i].address_line_1 + ',' + data.patient_address[i].address_line_2 + ',' + data.patient_address[i].town_village + '</span><br/><span>' + data.patient_address[i].city + ',' + data.patient_address[i].state + ',' + data.patient_address[i].country + '</span></div>';
                    //    }
                    //}
                    if (data.patient_address.length > 0) {
                        for (var i = 0; i < data.patient_address.length; i++) {
                            if (data.patient_address[i].country == "" || data.patient_address[i].country == null) {
                                data.patient_address[i].country = '';
                            }
                            if (data.patient_address[i].state == "" || data.patient_address[i].state == null) {
                                data.patient_address[i].state = '';
                            }
                            if (data.patient_address[i].city == "" || data.patient_address[i].city == null) {
                                data.patient_address[i].city = '';
                            }
                            tr = tr + '<div class="col-sm-8 patient-detail-card" onclick=address_ins(' + data.patient_address[i].address_id + ')><p>' + data.patient_address[i].first_name + '</p><span>' + data.patient_address[i].address_line_1 + ',' + data.patient_address[i].address_line_2 + ',' + data.patient_address[i].town_village + '</span><br/><span>' + data.patient_address[i].city + ',' + data.patient_address[i].state + ',' + data.patient_address[i].country + '</span></div>';
                        }
                    }
                    tr = tr + '<div class="col-sm-12 padding0"><p onclick=address_ins("New") class="btn btn-primaryuse only-broder mt20">Add new address</p></div>';
                    $('#tblpatientaddress').html(tr);
                    $('#tblpatientaddress').html(tr);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

function address_ins(id) {
    if (id == "New") {
        $('#btnaddress').show();
        $('#address_details').show();
        $('#tblpatientaddress').hide();
        return false;
    }
    

   
    
        $('#cur_time').val($('#displaytime').html().replace('Slot Time:', ''));
        //$('#cur_time').val($('#displaytime'));
  
    if ($.trim($('#txtdate').val()).length == "") {
        $('#Ptxtdate').show();
        $('#Ptxtdate').fadeOut(8000);
        $('#Ptxtdate').html('Please select the date');
        $('#txtdate').focus();
        $('#txtdate').val('');
        return false;
    }

    if ($.trim($('#cur_time').val()).length == "") {
        $('#Pdisplaytime').show();
        $('#Pdisplaytime').fadeOut(8000);
        $('#Pdisplaytime').html('Please select the Time');
        $('#displaytime').focus();
        $('#displaytime').val('');
        return false;
    }
    if ($("#address_details").is(":visible") == true) {
        if ($.trim($('#txtuserName').val()).length == "") {
            $('#PtxtuserName').show();
            $('#PtxtuserName').fadeOut(8000);
            $('#PtxtuserName').html('Enter First Name');
            $('#PtxtuserName').focus();
            $('#PtxtuserName').val('');
            return false;
        }
        if ($.trim($('#txtLastName').val()).length == "") {
            $('#PtxtLastName').show();
            $('#PtxtLastName').fadeOut(8000);
            $('#PtxtLastName').html('Enter Last Name');
            $('#PtxtLastName').focus();
            $('#PtxtLastName').val('');
            return false;
        }
        if ($.trim($('#txtmobileno').val()).length == "") {
            $('#Ptxtmobileno').show();
            $('#Ptxtmobileno').fadeOut(8000);
            $('#Ptxtmobileno').html('Enter Mobile Number');
            $('#Ptxtmobileno').focus();
            $('#Ptxtmobileno').val('');
            return false;
        }
        if ($.trim($('#txtLine1').val()).length == "") {
            $('#PtxtLine1').show();
            $('#PtxtLine1').fadeOut(8000);
            $('#PtxtLine1').html('Enter Address Line 1');
            $('#PtxtLine1').focus();
            $('#PtxtLine1').val('');
            return false;
        }
        if ($.trim($('#txtLine2').val()).length == "") {
            $('#PtxtLine2').show();
            $('#PtxtLine2').fadeOut(8000);
            $('#PtxtLine2').html('Enter Address Line 2');
            $('#PtxtLine2').focus();
            $('#PtxtLine2').val('');
            return false;
        }
        if ($.trim($('#txtPlace').val()).length == "") {
            $('#PtxtPlace').show();
            $('#PtxtPlace').fadeOut(8000);
            $('#PtxtPlace').html('Enter Address Line 2');
            $('#PtxtPlace').focus();
            $('#PtxtPlace').val('');
            return false;
        }
    }

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

    $('#cur_date').val(curdate);


    var Indicator_id = 'IA';
    if (id != "" && id != null) {
        Indicator_id = 'UA';
    }
    if (Indicator_id == "IA") {

        var address = {
            patient_id: $('#patient_id1').val(),
            Indicator_id: 'IA',
            address_line_1: $('#txtLine1').val(),
            address_line_2: $('#txtLine2').val(),
            town_village: $('#txtPlace').val(),
            country: $('#txtCountry').val(),
            state: $('#txtState').val(),
            city: $('#txtCity').val(),
            email_id: $('#txtEmailid').val(),
            pincode: $('#txtpincode').val(),
            first_name: $('#txtuserName').val(),
            last_name: $('#txtLastName').val(),
            phone_number: $('#txtmobileno').val(),
            address_id: id,
            lab_id: 'L1'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PackageDetails/patient_address',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(address),
            success: function (data) {
                if (jQuery.isEmptyObject((data)) || data.length == 0) {

                }
                else {
                    var data = JSON.parse(data);
                    if (data.msg == "Success") {
                        console.log(data);
                        if (data.details.length > 0) {
                            var address_id = data.details[0].address_id;
                            package_invoice_generation('', address_id);
                        }
                    }
                    else {
                        console.log(data);
                    }
                }
            }
        });
    }
    else {
        package_invoice_generation('', id);
    }
}

function Time(id) {
    $('#displaytime').html('Slot Time:' + id);
}

function loadcountry() {
    var country = {
        Dml_Indicator: "C"
    }

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

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

                }
                else {
                    var Country;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        Country = Country + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtCountry').append(default_opt + Country);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$("#txtCountry").change(function () {
    var state = {
        country_id: $("#txtCountry").val(),
        Dml_Indicator: "S"
    }

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

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {


                    var state;
                    $('#txtState').empty();
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtState').append(default_opt + state);
                }
            }
            else {
                console.log(data1);
            }
        }

    });

});

$("#txtState").change(function () {
    var state = {
        state_id: $("#txtState").val(),
        Dml_Indicator: "CI"
    }

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

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

                }
                else {
                    var City;
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';

                    });
                    $('#txtCity').append(default_opt + City);
                }
            }
            else {
                console.log(data1);
            }
        }

    });

});


function package_invoice_generation(e, address_id) {
    debugger;
    //$("#packagecard").css("pointer-events", "none");
    if (e != '' && e != null) {
        var id = e.getAttribute("data-id")
        var price_amt = e.getAttribute("data-name");
    }
    //$('#cur_date').val($('#txtdate').val());
    //$('#cur_time').val($('#displaytime').html());

    if (id == "" || id == null) {
        id = $('#cur_package_id').val();
    }
    if (price_amt == "" || price_amt == null) {
        price_amt = $('#cur_package_price_amt').val();
    }

    var package_data = {
        indicator_id: "PIG",
        package_id: id,
        patient_id: $('#patient_id1').val(),
        price: price_amt,
        doctor_id: $('#HiddenDoctorID').val(),
        hospital_id: $('#HospitalId').val(),
        package_address_id: address_id,
        package_first_date: $('#cur_date').val(),
        package_first_time: $('#cur_time').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) {
            data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data)) || data.length == 0) {
                }
                else {
                    var data1, b, c, msg, package_id, invoice_id, patient_id, db_msg, pay_msg, patient_id, patient_name, patient_phone_number, patient_visit_id;

                    b = data1.Table;
                    c = data1.Table1;
                    $.each(b, function (i, emp) {
                        db_msg = emp.msg;
                        if (db_msg != "already taken") {
                            msg = "Are you sure you want to Buy this package?";
                            package_id = emp.lab_order_id;
                            invoice_id = emp.invoice_id;
                            patient_id = emp.patient_id;
                        }
                        else {
                            toastr.warning("This Package already sold to the patient");
                            $("#packagecard").css("pointer-events", "");
                        }
                    });
                    $.each(c, function (i, emp) {
                        patient_id = emp.patient_id;
                        patient_name = emp.first_name;
                        patient_phone_number = emp.phone_number_1;
                        patient_visit_id = emp.visit_report_id
                    });
                    if (db_msg != "already taken") {
                        r = confirm(msg);
                        if (r == true) {
                            pay_msg = "Invoice is generated, Do you want to proceed for payment?";
                            pay_msg = confirm(pay_msg);
                            if (pay_msg == true) {
                                collectpayment(patient_id, patient_name, patient_phone_number, patient_visit_id);
                            }
                            else {
                                toastr.success("Thank You!!!");
                                $("#packagecard").css("pointer-events", "");
                            }
                        }
                        else {
                            toastr.success("Thank you!!!");
                            $("#packagecard").css("pointer-events", "");
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


function get_package_details(package_id, invoice_id, patient_id) {
    var package_data = {
        indicator_id: "GPD",
        package_id: package_id,
        patient_id: $('#patient_id1').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        invoice_id: invoice_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 data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else if (data.length > 0) {
                    var no_of_consultation, cosult_details, lab_deatils, pharmadetails, home_care, j = 0, data_list = [], list_data = '';

                    cosult_details = data1.Table;
                    lab_deatils = data1.Table1;
                    pharmadetails = data1.Table2;
                    home_care = data1.Table3;
                    var data = new Array();
                    var data1 = new Array();


                    var package_data = {
                        indicator_id: "PPDI",
                        package_id: package_id,
                        patient_id: $('#patient_id1').val(),
                        invoice_id: invoice_id,
                        booking_device: "1",
                        payment_type: "1",
                        created_by: $('#HiddenDoctorID').val(),
                        doctor_id: $('#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 (packdata) {
                            if (packdata.length > 0) {
                                //alert("Thank you for buying this package!!!");
                                //location.reload();
                                packdata = JSON.parse(packdata);
                                if (packdata.msg == "Success") {
                                    var packdata = packdata.data;
                                    var package_purchase_details_id = packdata.Table[0].package_purchase_details_id;
                                    console.log('-->' + package_purchase_details_id);
                                    if (cosult_details.length > 0) {
                                        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_id1').val();
                                                    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";
                                                    data["package_purchase_details_id"] = package_purchase_details_id;
                                                    insert_coupon(data);
                                                }
                                            }
                                        }
                                    }
                                    data = [];
                                    if (lab_deatils.length > 0) {
                                        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_id1').val();
                                                    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";
                                                    data["package_purchase_details_id"] = package_purchase_details_id;
                                                    insert_coupon(data);
                                                }
                                            }
                                        }
                                    }
                                    data = [];
                                    if (pharmadetails.length > 0) {
                                        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_id1').val();
                                                    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";
                                                    data["package_purchase_details_id"] = package_purchase_details_id;
                                                    insert_coupon(data);
                                                }
                                            }
                                        }
                                    }
                                    data = [];
                                    var visited_day = 0;
                                    if (home_care.length > 0) {
                                        for (i = 0; i < home_care.length; i++) {
                                            data["package_id"] = home_care[0]["package_id"];
                                            data["patient_id"] = patient_id;
                                            data["coupon_status"] = "1";
                                            data["coupon_expire_date"] = home_care[i]["date_of_expire"];
                                            data["coupon_consumed_by"] = $('#HiddenDoctorID').val();
                                            data["type_id"] = home_care[i]["package_home_care_id"];
                                            data["type"] = "4";
                                            data["coupon_useby_date"] = parseInt(visited_day) + parseInt(home_care[i]["visited_day"]);
                                            visited_day = parseInt(visited_day) + parseInt(home_care[i]["visited_day"]);
                                            data["package_first_date"] = home_care[0]['Vpackage_first_date'];
                                            data["package_purchase_details_id"] = package_purchase_details_id;
                                            insert_coupon(data);
                                            console.log('data-->' + data);
                                        }
                                    }
                                    toastr.success("Thank you for buying this package!!!");
                                    location.reload();
                                }
                                else {
                                    console.log(packdata);
                                }
                            }
                        }
                    });
                }
            }
            else {
                console.log(data1);
            }
            // 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,
        doctor_id: $('#HiddenDoctorID').val(),
        coupon_useby_date: data_list.coupon_useby_date,
        package_first_date: data_list.package_first_date,
        package_purchase_details_id: data_list.package_purchase_details_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 data = JSON.parse(data);
            if (data.msg == "Success") {
                if (jQuery.isEmptyObject((data))) {

                }
                else {

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

function package_purchase_insert(package_id, invoice_id) {
    var package_data = {
        indicator_id: "PPDI",
        package_id: package_id,
        patient_id: $('#patient_id1').val(),
        invoice_id: invoice_id,
        booking_device: "1",
        payment_type: "1",
        created_by: $('#HiddenDoctorID').val(),
        doctor_id: $('#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) {
            if (data.length > 0) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    toastr.success("Thank you for buying this Package!!!");
                    location.reload();
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}




//payment start
function collectpayment(patient_id, patient_first_name, patient_phone_number, photoSrc, visit_report_id, slottime) {
    $('#collectPayment').modal('toggle');
    $('.imgphoto').attr('src', photoSrc);
    $('.PatientId').html(patient_id);
    $('.PatientName').html(patient_first_name);
    $('.Patientpno').html(patient_phone_number);
    $('#Hdnpatient_id').val(patient_id);
    $('#PVisitReportID').val(visit_report_id);
    $('#Hdnappointment_date').val(slottime);

    var VisitreportId = {
        Patient_id: $('#Hdnpatient_id').val(),
        slotTime: $('#Hdnappointment_date').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: '15'
    }

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

                }
                else {

                    if (data.Table.length > 0) {
                        var VisitReportID = (data.Table[0].VisitReport_id);
                        //$('#VisitReportID').val(VisitReportID);
                        $('#PVisitReportID').val(VisitReportID);
                        payment_val();
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}
function payment_val() {
    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();

    $('#InvoiceDate').val(output);



    var GetRight = {
        Dml_Indicator: 'RS',
        doctor_user_role_id: $('#hiddenRole_id').val(),
        doctor_user_module_id: '16'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/DoctorRight',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(GetRight),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var roleRight = '';
                    $.each(data1, function (i, emp) {
                        roleRight = emp.doctor_user_role_rights;
                    });

                    if (roleRight == 1) {
                        var InvoiceId = {
                            Patient_id: $('#Hdnpatient_id').val(),
                            doctor_id: $('#HiddenDoctorID').val(),
                            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) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    var data = data.data;
                                    if (jQuery.isEmptyObject((data))) {
                                    }
                                    else {

                                        if (data.length > 0) {
                                            debugger;
                                            $('#InvoiceId').val(data[0].InvoiceId);
                                            $('#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);
                                        }
                                    }
                                    ActiveInvoice();
                                    invoice_quickSelect();
                                }
                                else {
                                    console.log(data);
                                }
                            }
                        });
                    }
                    else {
                        toastr.warning('You have no right to access page. Please Contact administrator');
                        $('.close').click();

                    }
                }
            }
            else {
                console.log(data1);
            }
        },
    });

}


function invoice_quickSelect() {
    var familydetails = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'PS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/doctor_consultation_fees_details_amt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    var tr = '', quickSelect = ''
                    $('#invoice_quickSelect').empty();
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            quickSelect = quickSelect + '<li onclick=\'addinvoice(\"' + data[i].consultation_name + '\")\'>' + data[i].consultation_name + '</li>';
                        }
                        $('#invoice_quickSelect').html(quickSelect);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function addinvoice(InvoiceName) {

    var InvoiceNames = InvoiceName;

    var invoice = {}
    invoice.invoice_id = $('#InvoiceId').val(),
        invoice.Patient_id = $('#Hdnpatient_id').val(),
        invoice.doctor_id = $('#HiddenDoctorID').val(),
        invoice.invoice_description = InvoiceNames,
        invoice.invoice_date = '',
        invoice.invoice_amount = $('#InvoiceAmount').val(),
        invoice.invoice_status = 1,
        invoice.balance_amount = $('#InvoiceAmount').val(),
        invoice.Dml_Indicator = 'QI',
        invoice.visit_report_id = $('#PVisitReportID').val(),

        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/invoice_payment',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(invoice),
            success: function (data) {
                var data = JSON.parse(data);
                if (data.msg == "Success") {
                    var data = data.data;
                    if (jQuery.isEmptyObject((data))) {

                    }
                    else {

                    }
                    collectpayment_afterinsert($('#Hdnpatient_id').val());
                }
                else {
                    console.log(data);
                }
            }
        });

}



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

    var InvoiceDates = InvoiceDate.split('/');
    InvoiceDate = InvoiceDates[2] + "-" + InvoiceDates[1] + "-" + InvoiceDates[0];
    var invoice = {
        invoice_id: $('#InvoiceId').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        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',
        visit_report_id: $('#PVisitReportID').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                }
                $('#InvoiceDate').val('');
                $('#InvoiceName').val('');
                $('#InvoiceAmount').val('');
                collectpayment_afterinsert($('#Hdnpatient_id').val());
            }
            else {
                console.log(data);
            }
        }
    });
});


function collectpayment_afterinsert(patient_id) {
    var InvoiceId = {
        Patient_id: patient_id,
        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) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.length > 0) {
                        $('#InvoiceId').val(data[0].InvoiceId);
                    }
                }
                ActiveInvoice();
            }
            else {
                console.log(data);
            }

        }
    });
}

$('#cpi_activeInvoice_body').on('click', 'tr', function () {

    //$('#cpi_activeInvoice_sec').removeClass().addClass('col-md-8 padding0');
    //$('#modal_collectpayment_inner').toggle();
    $('#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(',');


    var GetRight = {
        Dml_Indicator: 'RS',
        doctor_user_role_id: $('#hiddenRole_id').val(),
        doctor_user_module_id: '17'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/DoctorRight',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(GetRight),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {

                    var roleRight = '';
                    $.each(data1, function (i, emp) {
                        roleRight = emp.doctor_user_role_rights;
                    });
                    if (roleRight == 1) {
                        ActiveInvoiceDetails(val[0], val[1]);
                        $("#cpiActiveDetails").show();
                    }
                    else {
                        toastr.warning('You have no right to access page. Please contact administrator');
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });



});

//$('#cpi_activeInvoice_body > tr').click(function () {
//    debugger;

//});

$('#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 () {
//    $('[data-toggle="popover"]').popover()
//})

//$("[data-toggle=popover]").popover('show');

function ActiveInvoice() {
    $('#cpi_activeInvoice_table').addClass('us-db-loader-active-inv');
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'AI',
        patient_id: $('#Hdnpatient_id').val()
    }
    $.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_activeInvoice_body').empty();
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    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><i class="fa fa-print" onclick=Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\") ></i>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td><a 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>Delete</a></td><td><a href="javascript:void(0);" data-toggle="modal" data-target="#modal_collectpayment_inner" data-backdrop="static" data-keyboard="true">+ Payment</a></td></tr>';
                            tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td><input style="display:none" type="checkbox" id="' + data[i].invoice_id + '" name="checkbox1" value="' + data[i].balance_amount + '" onclick=\'checkval(\"' + data[i].balance_amount + '\",\"' + data[i].invoice_id + '\")\';></td><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td><span class="print btn addicon-btn  mr-15 btn-xs"><i class="fa fa-print" onclick=Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\") ></i></span>' + 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" 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" 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="part-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></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);
                    }
                    else {
                        //$('#CpiInvoiceTotal').html('-');
                        //$('#CpiInvoicePayment').html('-');
                        //$('#CpiInvoiceTotal_amt').html('-');
                    }
                }
                $('#cpi_activeInvoice_table').removeClass('us-db-loader-active-inv');
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#chk_amount').click(function () {
    if ($("[name='checkbox1']").is(":visible")) {
        $("[name='checkbox1']").hide();
        $('.head-payment-wap-popup').removeClass('open');

    } else {
        $("[name='checkbox1']").show();
        $('.head-payment-wap-popup').addClass('open');
        $('#payphonenumber').val($('.Patientpno').html());
    }
});

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

    if ($.trim($('#payphonenumber').val()) == "") {
        $('#Ppayphonenumber').show();
        $('#Ppayphonenumber').fadeOut(8000);
        $('#Ppayphonenumber').html('Enter the phone number');
        $('#payphonenumber').focus();
        $('#payphonenumber').val('');
        return false;
    }

    var smspayment = {
        sms_invoice_no: '',
        email_id: $('#paymailid').val(),
        phone_number: $('#payphonenumber').val(),
        created_by: $('#hiddenUser_id').val(),
        valid_for: '',
        valid_type: '',
        valid_date: '',
        currency: 'INR',
        amount: $('#totpopup_amout >i').html(),
        due_date: '',
        invoice_no: ''
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {

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



function checkval(val, id) {
    debugger;
    var tempval = '';
    if ($('#' + id).prop("checked") == true) {
        tempval = $('#totpopup_amout >i').html();
        if (tempval == '') {
            tempval = 0;
        }
        tempval = parseFloat(tempval) + parseFloat(val);
        $('#totpopup_amout >i').html(tempval);
    }
    else if ($('#' + id).prop("checked") == false) {
        tempval = $('#totpopup_amout >i').html();
        if (tempval == '') {
            tempval = 0;
        }
        tempval = parseFloat(tempval) - parseFloat(val);
        $('#totpopup_amout >i').html(tempval);
    }
}


function add_payment1(labid) {
    $('#pack_id').val(labid);
    $('#Selpaymenttype').val('1');
    $('#modal_collectpayment_inner').modal('toggle');
}


function Delete_Active_invoice(invoice_id, lab_id) {

    var txt;
    var r = confirm("Are You sure You want delete the Invoice: " + invoice_id + "");
    if (r == true) {
        $('#tblDoctorUser1').modal('toggle');
        $('#hndinvoiceId').val(invoice_id);
    } else {

    }
}


function fullpayment(balance_amount, payment_type, invoice_id, lab_order_id) {
    debugger;
    var invoice_status = 3;

    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                }
                $('#paymentamount').val('');
                //$("#cpiActiveDetails").hide();
                debugger;
                if (lab_order_id.length > 5) {
                    var doc_id = lab_order_id.split('-')[0];
                    //if (doc_id == "USD00001") {
                    get_package_details(lab_order_id, invoice_id, $('#Hdnpatient_id').val());
                    //}
                }

                ActiveInvoice();
                HistroyInvoice();
                toastr.success("Full Payment added successfully");
                $('.paymentclose').click();


                //ActiveInvoiceDetails($('#curinvoiceid').val(), $('#curamount').val())
            }
            else {
                console.log(data);
            }

        }
    });

}

$('#mpinsubmit').click(function () {
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'D',
        invoice_id: $('#hndinvoiceId').val(),
        MPIN: $('#mpinnum').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    toastr.warning('Entered MPIN is wrong');
                }

                if (data.length == 0) {
                    toastr.warning("Entered MPIN is wrong");
                }
                else {
                    if (data.length > 0) {
                        if (data[0].StringMsg == 'Success') {
                            toastr.success('Payment Deleted Successfully');
                            ActiveInvoice();
                        }
                        else if (data[0].StringMsg == 'Cannot able to delete') {
                            toastr.success('Payment Received - Unable to Delete Invoice');
                        }
                        else {
                            toastr.warning('Entered MPIN is wrong !!!');
                        }
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
});

function Invoice_lab_print(order_id, visit_report_id, invoice_id) {
    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 + '&doctorId=' + $('#HiddenDoctorID').val() + '&btnval=1', "_blank");
    }
}


function ActiveInvoiceDetails(id, amount) {
    $('#curinvoiceid').val(id);
    $('#curamount').val(amount);
    var invoice = {
        invoice_id: $('#curinvoiceid').val(),
        Patient_id: $('#Hdnpatient_id').val(),
        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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                    $('#totamt').html(amount);
                    $('#paidamt').html('0');
                    $('#balanceamt').html('0');
                }
                else {

                    $('#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 if (data[i].payment_type == 4) {
                                paymenttype = 'Online';
                            }
                            else {
                                paymenttype = '-';
                            }
                            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 + '\",\"' + 1 + '\",\"' + $('#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>');
                        }
                    }
                    else {
                        $('#totamt').html(amount);
                    }
                    $('#tblinvoiceamtdetails_body').html(tr);
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

$('#add_cpi_invoice').click(function () {
    debugger;
    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()) == '') {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('enter the invoice amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        return false;
    }

    var previousval = 0, doc_id;
    $('#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 = '';
    if (previousval > parseFloat($('#curamount').val())) {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('Check amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        return false;
    }
    else if (previousval < parseFloat($('#curamount').val())) {
        invoice_status = 2;
        balance_amount = parseFloat($('#curamount').val()) - parseFloat(previousval);
    }
    else {
        patient_id = $('#Hdnpatient_id').val();
        invoice_id = $('#curinvoiceid').val();
        package_id = $('#pack_id').val();
        doc_id = $('#pack_id').val();
        if (doc_id.length > 5) {
            doc_id = $('#pack_id').val().split('-')[0];
            if (doc_id == "USD00001") {
                get_package_details(package_id, invoice_id, patient_id);
            }
        }
        invoice_status = 3;
        balance_amount = 0;
    }
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('#Hdnpatient_id').val(),
        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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                }
                $('#transaction_id').val('');
                $('#paymentamount').val('');
                $('#Selpaymenttype').val('');
                $('#transaction').hide();
                //$("#cpiActiveDetails").hide();
                ActiveInvoice();
                HistroyInvoice();


                ActiveInvoiceDetails($('#curinvoiceid').val(), $('#curamount').val())
            }
            else {
                console.log(data);
            }

        }
    });



    //tblinvoiceamtdetails
});

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

});

function HistroyInvoice() {
    $('.cpi_historyInvoice_table').addClass('us-db-loader-history-inv');
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'HS',
        patient_id: $('#Hdnpatient_id').val()
    }
    $.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 data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    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++) {

                            //if (i==0) {
                            //    tr1 = '<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>';
                            //    invoice_id = data[i].invoice_id;
                            //}
                            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 if (data[i].payment_type == 4) {
                                payment_type = 'SMS Payment';
                            }
                            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><i class="fa fa-print" onclick=Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\") ></i>' + 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-trigger="click" data-placement="bottom" 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><i class="fa fa-print" onclick=Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\") ></i>' + 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-trigger="click" data-placement="bottom" 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();
                    }
                }
                $('.cpi_historyInvoice_table').removeClass('us-db-loader-history-inv');
            }
            else {
                console.log(data);
            }
        }
    });
}


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

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

});

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



$('#InvoiceName').change(function () {
    var familydetails = {
        consultation_name: $('#InvoiceName').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'MS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/doctor_consultation_fees_details_amt',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(familydetails),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                    var tr = ''
                    if (data.length > 0) {
                        $('#InvoiceAmount').val(data[0].consultation_fees);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

});


function leftarrow() {
    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);
    }
    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);
    }
    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);
    }


    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);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '30' + '/' + '11' + '/' + displaydates[2];
                $('#app_date_current').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);
            }
            else if (displaydate == '03') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '28' + '/' + '02' + '/' + displaydates[2];
                $('#app_date_current').html(date);
            }
            else {
                date = displaydates[1] - 1;
                if (date < 10) {
                    date = '0' + date;
                }
                date = '30' + '/' + date + '/' + displaydates[2];
                $('#app_date_current').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);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').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);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + '01' + '/' + displaydates[2];
            $('#app_date_current').html(date);
        }
    }
    if (date == $('#hndtoday').val()) {
        $('#app_date_current').html('Today');
    }
    if (date == $('#hndyesterday').val()) {
        $('#app_date_current').html('Yesterday');
    }
    if (date == $('#hndtomorrow').val()) {
        $('#app_date_current').html('Tomorrow');
    }
    var package_type = 1;
    daily_care(package_type, 'daily_care');
}


function rightarrow() {
    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);
    }


    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);
    }
    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);
    }
    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);
        }
        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);
            }
            else {
                date = parseInt(displaydates[1]) + parseInt(1);
                if (date < 10) {
                    date = '0' + date;
                }
                date = '01' + '/' + date + '/' + displaydates[2];
                $('#app_date_current').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);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').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);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current').html(date);
        }
    }
    if ($('#app_date_current').html() == $('#hndtoday').val()) {
        $('#app_date_current').html('Today');
    }
    if ($('#app_date_current').html() == $('#hndyesterday').val()) {
        $('#app_date_current').html('Yesterday');
    }
    if ($('#app_date_current').html() == $('#hndtomorrow').val()) {
        $('#app_date_current').html('Tomorrow');
    }
    var package_type = 1;
    daily_care(package_type, 'daily_care');
}

$('#Selorder_status').change(function () {
    if ($('#Selorder_status').val() == '0') {
        $('#datefilter').hide();
        $("#patientName_filter").hide();
        $("#btnsubmit_order").hide();
        patient_lab_order();
    }
    else if ($('#Selorder_status').val() == '1') {
        $('#datefilter').hide();
        $("#patientName_filter").hide();
        $("#btnsubmit_order").hide();
        select_option_filter('AOL');
    }
    else if ($('#Selorder_status').val() == '2') {
        $('#datefilter').hide();
        $("#patientName_filter").hide();
        $("#btnsubmit_order").hide();
        select_option_filter('COL');
    }
    else if ($('#Selorder_status').val() == '3') {
        $('#datefilter').hide();
        $("#patientName_filter").hide();
        $("#btnsubmit_order").hide();
        select_option_filter('CCOL');
    }
    else 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();
    }
});

function patient_lab_order() {
    $("#Live_Package").hide();
    $("#setuppackageicon").hide();
    $("#Package_Patients").hide();
    $("#Sell_To_Patient").hide();
    $("#Total_Home_Collection_Order").show();
    $("#Self_Collection").show();
    $("#Third_Party_Collection").show();
    var date;
    if ($('#app_date_current_1').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_1').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current_1').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current_1').html();

    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        date: date,
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: "OL"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            $('#Jobdetails').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#Jobdetails').html(Norecord);
                }
                else {
                    var invoiceAmt = '', invoicedue = '', j, order_status = '', pickup_by, test_type, phone;

                    if (data.length > 4 && data != null) {
                        var b = data1.Table;
                        var c = data1.Table1;
                        $('#AdviceCount').html(b[0].total_order);
                        $('#pendingorder').html(b[0].self_picup);
                        $('#pendingjob').html(b[0].i2h_pickup);
                        tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="labJoblist" />');
                        tr.append('<thead><tr><th>&nbsp;</th><th>Patient Details</th><th>Payment Status</th><th>Invoice Amount(RS)</th><th>Booked Date</th><th>Pickup Date</th><th>Pickup Time</th><th>Pickup By</th><th>Order Status</th><th>Action</th><th>Files</th></tr></thead>');
                        j = 0;
                        if (c.length > 0) {
                            var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                            $.each(c, function (i, emp) {
                                debugger;
                                if (emp.payment_status == null || emp.payment_status == '') order_status = '-';
                                else order_status = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';;
                                if (emp.phone_number_1 == null || emp.phone_number_1 == "") phone = "-";
                                else phone = emp.phone_number_1;
                                if (emp.pickup_by == '1') {
                                    pickup_by = 'Self';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '2') {
                                    pickup_by = 'I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="blue" data-toggle="popover" data-target="#pattrackdetails" onclick=i2h_order_track("' + emp.I2H_order_id + '")>Order Track</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '3') {
                                    pickup_by = 'Cancelled By Doctor';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '4') {
                                    pickup_by = 'Cancelled By I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pincode_status == '2') {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="edit btn btn-default  btn-sm btn-add" onclick=self_pickup("' + emp.I2H_order_id + '")>self Pickup</button><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                j = j + 1;
                                tr.append(row_data);
                            });
                            $('#Jobdetails').html(tr);
                        }
                        else {
                            $('#Jobdetails').html(Norecord);
                        }
                    }
                    else {
                        $('#Jobdetails').html(Norecord);
                    }

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

function select_option_filter(val) {
    $('#loaderimg').show();
    var date;
    if ($('#app_date_current_1').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_1').html() == 'Yesterday') {
        date = $('#hndyesterday').val();
    }
    else if ($('#app_date_current_1').html() == 'Tomorrow') {
        date = $('#hndtomorrow').val();
    }
    else {
        date = $('#app_date_current_1').html();

    }

    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: val,
        date: date,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            $('#Jobdetails').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    console.log(data1);
                    $('#Jobdetails').html(Norecord);
                }
                else {
                    var invoiceAmt = '', invoicedue = '', j, order_status = '', phone, pickup_by;

                    console.log(data1);
                    var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                    if (data.length > 4 && data != null) {
                        var b = data1.Table;
                        tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="labJoblist" />');
                        tr.append('<thead><tr><th>&nbsp;</th><th>Patient Details</th><th>Payment Status</th><th>Invoice Amount</th><th>Booked Date</th><th>Pickup Date</th><th>Pickup Time</th><th>Pickup By</th><th>Order Status</th><th>Action</th><th>Files</th></tr></thead>');
                        j = 0;
                        $.each(b, function (i, emp) {
                            if (emp.payment_status == null || emp.payment_status == '') order_status = '-';
                            else order_status = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';;
                            if (emp.phone_number_1 == null || emp.phone_number_1 == "") phone = "-";
                            else phone = emp.phone_number_1;
                            if (emp.pickup_by == '1') {
                                pickup_by = 'Self';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            else if (emp.pickup_by == '2') {
                                pickup_by = 'I2H';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            else if (emp.pickup_by == '3') {
                                pickup_by = 'Cancelled By Doctor';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            else if (emp.pickup_by == '4') {
                                pickup_by = 'Cancelled By I2H';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            else if (emp.pincode_status == '2') {
                                pickup_by = '-';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            else {
                                pickup_by = '-';
                                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="edit btn btn-default  btn-sm btn-add" onclick=self_pickup("' + emp.I2H_order_id + '")>self Pickup</button><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                            }
                            j = j + 1;
                            tr.append(row_data);
                        });
                        $('#Jobdetails').html(tr);
                    }
                    else {
                        $('#Jobdetails').html(Norecord);
                    }

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

function orderdetails(val, val2) {
    var htmlid = val;
    var orderid = val2;
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'TD',
        order_id: orderid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            console.log(data);
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var test_type;

                    var tr = '', Action = '';
                    var b = data1.Table;
                    var add_val = "Pickup Address : " + data1.Table1[0].first_name + "," + data1.Table1[0].phone_number + "," + data1.Table1[0].patient_address + "," + data1.Table1[0].town_village + "," + data1.Table1[0].city + "," + data1.Table1[0].state + "-" + data1.Table1[0].pincode;
                    var trhead = '<td colspan="12"><div><p class="pickupaddress"> ' + add_val + '</span> </p><table class="table table-condensed body-borderless table_borderless"><thead><tr><th>Test ID</th><th>Type</th><th>Test Name</th><th>Amount</th><th>Date</th></tr></thead><tbody>';
                    $.each(b, function (i, emp) {
                        if (emp.test_type == "1") test_type = "Panel";
                        else test_type = "test";
                        tr = tr + '<tr><td>' + emp.test_id + '</td><td>' + test_type + '</td><td>' + emp.test_name + '</td><td>' + emp.test_price + '</td><td>' + emp.created_on + '</td></tr>'
                    });
                    var trend = '</tbody></table></div></td>';
                    $('#' + htmlid).html(trhead + tr + trend);
                }
            }
            else {
                console.log(data1);
            }
        }
    });

}

function i2h_pickup(val) {
    $('#loaderimg').show();
    var date;
    var date;
    if ($('#app_date_current_1').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 {
        date = $('#app_date_current_1').html();
    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'I2HP',
        order_id: val,
        date: date,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/i2h_pickup',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
                toastr.warning("Something went wrong, Please try again after some time");
                $('#loaderimg').hide();
            }
            else {
                var data1 = JSON.parse(data);
                if (data.length > 5) {
                    var i2h_id, order_status, order_id = val;
                    if (data1.status == "200") {
                        var i2h_data = data1.data;
                        i2h_id = i2h_data.i2h_order_id;
                        order_status = i2h_data.order_status;
                        order_id = i2h_data.vendor_order_id;
                    }
                    var Template = {
                        doctor_id: $('#HiddenDoctorID').val(),
                        Dml_Indicator: 'I2HPRD',
                        message: data1.message,
                        system_time: data1.system_time,
                        i2h_id: i2h_id,
                        is_order_accepted: data1.is_order_accepted,
                        i2h_order_status: order_status,
                        status: data1.status,
                        order_id: order_id
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Template/lab_home_colection',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(Template),
                        success: function (data) {
                            $('#loaderimg').hide();
                            if (data1.is_order_accepted == true) {
                                toastr.success("Third Party Pickup Successfully Created");
                            }
                            else {
                                alert(data1.message);
                            }
                            location.reload();
                        }
                    });
                }
                else {
                    toastr.warning("Something went wrong, Please try again after some time");
                    $('#loaderimg').hide();
                }
            }
        }
    });
}

function self_pickup(val) {
    $('#loaderimg').show();
    var date;
    if ($('#app_date_current_1').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 {
        date = $('#app_date_current_1').html();
    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'SP',
        order_id: val,
        date: date,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                order_table(data);
            }
            else {
                console.log(data1);
            }
        }
    });
}

function order_table(data) {
    $('#Jobdetails').empty();
    var data1 = JSON.parse(data);
    data1 = data1.data;
    var b = data1.Table;
    var c = data1.Table1;
    $('#AdviceCount').html(b[0].total_order);
    $('#pendingorder').html(b[0].self_picup);
    $('#pendingjob').html(b[0].i2h_pickup);
    tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="labJoblist" />');
    tr.append('<thead><tr><th>&nbsp;</th><th>Patient Details</th><th>Payment Status</th><th>Invoice Amount(RS)</th><th>Booked Date</th><th>Pickup Date</th><th>Pickup Time</th><th>Pickup By</th><th>Order Status</th><th>Action</th><th>Files</th></tr></thead>');
    var j = 0, order_status, phone;
    if (c.length > 0) {
        var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
        $.each(c, function (i, emp) {
            if (emp.payment_status == null || emp.payment_status == '') order_status = '-';
            else order_status = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';;
            if (emp.phone_number_1 == null || emp.phone_number_1 == "") phone = "-";
            else phone = emp.phone_number_1;
            if (emp.pickup_by == '1') {
                pickup_by = 'Self';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            else if (emp.pickup_by == '2') {
                pickup_by = 'I2H';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="blue" data-toggle="popover" data-target="#pattrackdetails" onclick=i2h_order_track("' + emp.I2H_order_id + '")>Order Track</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            else if (emp.pickup_by == '3') {
                pickup_by = 'Cancelled By Doctor';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            else if (emp.pickup_by == '4') {
                pickup_by = 'Cancelled By I2H';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            else if (emp.pincode_status == '2') {
                pickup_by = '-';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            else {
                pickup_by = '-';
                row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="edit btn btn-default  btn-sm btn-add" onclick=self_pickup("' + emp.I2H_order_id + '")>self Pickup</button><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
            }
            j = j + 1;
            tr.append(row_data);
        });
        $('#Jobdetails').html(tr);
    }
    else {
        $('#Jobdetails').html(Norecord);
    }
}

function i2h_cancel_order(id) {
    $('#loaderimg').show();
    var date;
    if ($('#app_date_current_1').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 {
        date = $('#app_date_current_1').html();
    }
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'CO',
        order_id: id,
        date: date,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                order_table(data);
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#btnsubmit_order').click(function () {
    if ($('#Selorder_status').val() == '4') {
        date_filter();
    }
    else if ($('#Selorder_status').val() == '5') {
        name_filter();
    }
    else {
    }
});

function date_filter() {
    if ($.trim($('#FDate').val()).length == "") {
        $('#PFDate').show();
        $('#PFDate').fadeOut(8000);
        $('#PFDate').html('Enter From Date');
        $('#FDate').focus();
        $('#FDate').val('');
        return false;
    }
    if ($.trim($('#EDate').val()).length == "") {
        $('#PEDate').show();
        $('#PEDate').fadeOut(8000);
        $('#PEDate').html('Enter To Date');
        $('#EDate').focus();
        $('#EDate').val('');
        return false;
    }
    if ($.trim($('#EDate,#FDate').val()).length > 0) {
        $('#loaderimg').show();
        var from_Date, to_date, condition;
        from_Date = $('#FDate').val();
        to_date = $('#EDate').val();
        var from_Dates = from_Date.split('/');
        from_Date = from_Dates[2] + '-' + from_Dates[1] + '-' + from_Dates[0];
        var to_dates = to_date.split('/');
        to_date = to_dates[2] + '-' + to_dates[1] + '-' + to_dates[0];
        var Template = {
            doctor_id: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'DF',
            FDate: from_Date,
            EDate: to_date
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home_colection',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                $('#EDate').val('');
                $('#FDate').val('');
                $('#loaderimg').hide();
                $('#Jobdetails').empty();
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                        $('#Jobdetails').html(Norecord);
                    }
                    else {
                        var invoiceAmt = '', invoicedue = '', j, order_status = '', phone, pickup_by;

                        var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                        if (data.length > 4 && data != null) {
                            var b = data1.Table;
                            tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="labJoblist" />');
                            tr.append('<thead><tr><th>&nbsp;</th><th>Patient Details</th><th>Payment Status</th><th>Invoice Amount</th><th>Booked Date</th><th>Pickup Date</th><th>Pickup Time</th><th>Pickup By</th><th>Order Status</th><th>Action</th><th>Files</th></tr></thead>');
                            j = 0;
                            $.each(b, function (i, emp) {
                                if (emp.payment_status == null || emp.payment_status == '') order_status = '-';
                                else order_status = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';;
                                if (emp.phone_number_1 == null || emp.phone_number_1 == "") phone = "-";
                                else phone = emp.phone_number_1;
                                if (emp.pickup_by == '1') {
                                    pickup_by = 'Self';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '2') {
                                    pickup_by = 'I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="blue" data-toggle="popover" data-target="#pattrackdetails" onclick=i2h_order_track("' + emp.I2H_order_id + '")>Order Track</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '3') {
                                    pickup_by = 'Cancelled By Doctor';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '4') {
                                    pickup_by = 'Cancelled By I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pincode_status == '2') {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="edit btn btn-default  btn-sm btn-add" onclick=self_pickup("' + emp.I2H_order_id + '")>self Pickup</button><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                j = j + 1;
                                tr.append(row_data);
                            });
                            $('#Jobdetails').html(tr);
                        }
                        else {
                            $('#Jobdetails').html(Norecord);
                        }

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

function name_filter() {
    if ($.trim($('#PName').val()).length == "") {
        $('#PPName').show();
        $('#PPName').fadeOut(8000);
        $('#PPName').html('Enter Name or Phone Number or Patient Id');
        $('#PName').focus();
        $('#PName').val('');
        return false;
    }
    if ($.trim($('#PName').val()).length > 0) {
        $('#loaderimg').show();
        debugger;
        var Template = {
            doctor_id: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'POL',
            FDate: $('#PName').val().split('/')[2],
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Template/lab_home_colection',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Template),
            success: function (data) {
                $('#PName').val('');
                $('#loaderimg').hide();
                $('#Jobdetails').empty();
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                        $('#Jobdetails').html(Norecord);
                    }
                    else {
                        debugger;
                        var invoiceAmt = '', invoicedue = '', j, order_status = '', phone, pickup_by;

                        var img = '<i class="fa fa-check" aria-hidden="true"></i> Paid';
                        if (data.length > 4 && data != null) {
                            var b = data1.Table;
                            tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="labJoblist" />');
                            tr.append('<thead><tr><th>&nbsp;</th><th>Patient Details</th><th>Payment Status</th><th>Invoice Amount</th><th>Booked Date</th><th>Pickup Date</th><th>Pickup Time</th><th>Pickup By</th><th>Order Status</th><th>Action</th><th>Files</th></tr></thead>');
                            j = 0;
                            $.each(b, function (i, emp) {
                                if (emp.payment_status == null || emp.payment_status == '') order_status = '-';
                                else order_status = '<span class="lh-paid"><a id="btnLabPayment">' + img + '</a></span>';
                                if (emp.phone_number_1 == null || emp.phone_number_1 == "") phone = "-";
                                else phone = emp.phone_number_1;
                                if (emp.pickup_by == '1') {
                                    pickup_by = 'Self';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '2') {
                                    pickup_by = 'I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="blue" data-toggle="popover" data-target="#pattrackdetails" onclick=i2h_order_track("' + emp.I2H_order_id + '")>Order Track</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '3') {
                                    pickup_by = 'Cancelled By Doctor';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pickup_by == '4') {
                                    pickup_by = 'Cancelled By I2H';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else if (emp.pincode_status == '2') {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                else {
                                    pickup_by = '-';
                                    row_data = '<tr data-toggle="collapse" data-target="#demo_' + j + '" class="accordion-toggle"><td><button onclick=orderdetails("demo_' + j + '","' + emp.I2H_order_id + '") class="part-payment btn addicon-btn   btn-sm mr-20"><span class="glyphicon glyphicon-eye-open"></span></button></td><td class="align-middle">' + emp.first_name + "</span></a><br /><span class='mys-ph'>ph : " + phone + '</span>&nbsp;/&nbsp<span class="mys-id">' + emp.I2H_order_id + '</span></td><td>' + order_status + '</td><td>' + emp.total_cost + '</td><td>' + emp.created_on + '</td><td>' + emp.pickupdate + '</td><td>' + emp.slot_time + '</td><td>' + pickup_by + '</td><td>' + emp.order_status + '</td><td><button class="edit btn btn-default  btn-sm btn-add" onclick=self_pickup("' + emp.I2H_order_id + '")>self Pickup</button><button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_pickup("' + emp.I2H_order_id + '");>I2H Pickup</button> <button class="delete btn deleteicon-btn   btn-sm btn-add" onclick=i2h_cancel_order("' + emp.I2H_order_id + '");>Cancel Order</button></td><td><button onclick=files_lab("' + emp.I2H_order_id + '") title="Appointment Files " data-toggle="modal" data-target="#appointment_files">View Files</button></td></tr><tr class="hiddenRow accordian-body collapse" id="demo_' + j + '"></tr>';
                                }
                                j = j + 1;
                                tr.append(row_data);
                            });
                            $('#Jobdetails').html(tr);
                        }
                        else {
                            $('#Jobdetails').html(Norecord);
                        }

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

function Lableftarrow() {
    if ($('#app_date_current_1').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_1').html(output);
    }
    else if ($('#app_date_current_1').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_1').html(output);
    }
    else if ($('#app_date_current_1').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_1').html(output);
    }


    var displaydate = $('#app_date_current_1').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_1').html(date);
        }
        else {
            if (displaydate == '12') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '30' + '/' + '11' + '/' + displaydates[2];
                $('#app_date_current_1').html(date);
            }
            else if (displaydate == '01') {
                date = parseInt(displaydates[1]) + parseInt(1);
                var year = (displaydates[2]) - (1);
                date = '31' + '/' + '12' + '/' + year;
                $('#app_date_current_1').html(date);
            }
            else if (displaydate == '03') {
                date = parseInt(displaydates[1]) + parseInt(1);
                date = '28' + '/' + '02' + '/' + displaydates[2];
                $('#app_date_current_1').html(date);
            }
            else {
                date = displaydates[1] - 1;
                if (date < 10) {
                    date = '0' + date;
                }
                date = '30' + '/' + date + '/' + displaydates[2];
                $('#app_date_current_1').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_1').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + date + '/' + displaydates[2];
            $('#app_date_current_1').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_1').html(date);
        }
        else {
            date = displaydates[1] - 1;
            if (date < 10) {
                date = '0' + date;
            }
            date = '31' + '/' + '01' + '/' + displaydates[2];
            $('#app_date_current_1').html(date);
        }
    }
    if (date == $('#hndtoday').val()) {
        $('#app_date_current_1').html('Today');
    }
    if (date == $('#hndyesterday').val()) {
        $('#app_date_current_1').html('Yesterday');
    }
    if (date == $('#hndtomorrow').val()) {
        $('#app_date_current_1').html('Tomorrow');
    }
    date_order_list();
}

function Labrightarrow() {
    if ($('#app_date_current_1').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_1').html(output);
        $('#app_date_current1').html(output);
        $('#app_date_current2').html(output);
        $('#app_date_current3').html(output);
    }


    else if ($('#app_date_current_1').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_1').html(output);
    }
    else if ($('#app_date_current_1').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_1').html(output);
    }
    var displaydate = $('#app_date_current_1').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_1').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_1').html(date);
            }
            else {
                date = parseInt(displaydates[1]) + parseInt(1);
                if (date < 10) {
                    date = '0' + date;
                }
                date = '01' + '/' + date + '/' + displaydates[2];
                $('#app_date_current_1').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_1').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current_1').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_1').html(date);
        }
        else {
            date = parseInt(displaydates[1]) + parseInt(1);
            if (date < 10) {
                date = '0' + date;
            }
            date = '01' + '/' + date + '/' + displaydates[2];
            $('#app_date_current_1').html(date);
        }
    }
    if ($('#app_date_current_1').html() == $('#hndtoday').val()) {
        $('#app_date_current_1').html('Today');
    }
    if ($('#app_date_current_1').html() == $('#hndyesterday').val()) {
        $('#app_date_current_1').html('Yesterday');
    }
    if ($('#app_date_current_1').html() == $('#hndtomorrow').val()) {
        $('#app_date_current_1').html('Tomorrow');
    }
    date_order_list();
}

$('#datepicker1').change(function () {
    var date = $('#datepicker1').val();
    $('#app_date_current_1').html(date);
    date_order_list()
});

function date_order_list() {
    $('#loaderimg').show();
    var date = $('#app_date_current_1').html();
    var dates = date.split('/');
    date = dates[2] + '-' + dates[1] + '-' + dates[0];
    var Template = {
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'DOL',
        date: date,
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/lab_home_colection',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Template),
        success: function (data) {
            $('#loaderimg').hide();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                order_table(data);
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#PName').on('input', function () {
    $('#PName').autocomplete({
        source: function (request, response) {
            $.ajax({
                async: true,
                url: "/Template/AutoComplete_PatName?rep_list=" + $('#PName').val(),
                type: "POST",
                dataType: "json",
                data: { Prefix: request.term },
                success: function (data) {
                    response($.map(data, function (item) {
                        return { label: item.patient_name, value: item.patient_name };
                    }));

                }
            });
        }
    });
});
//paymenttype if value=4 transaction id will enable
$("#Selpaymenttype").change(function () {
    var value = $("#Selpaymenttype").val();
    if (value == 4) {
        $("#transaction").show();
    }
    else {
        $("#transaction").hide();
    }
})
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 data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.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);


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



