var jsonLength = '';
var li = [];
var a = [];
var SubmitArr = [];
$(document).ready(function () {
    LoadBranchForPatientSearchPopup();
    if ($('#HProductCode').val() == "1") {
    }
    else {
        $('#diabdisplay').hide();
    }
    var patientID = $('#Patient_Id').val();
    var Patient_details = $('#Patient_details').val();
    if (patientID != '' || Patient_details != '') {
        var val1 = '';
        var val2 = '';
        if (patientID != '') {
            loadPatient(val1, val2);
            NewPatient_listTbl();
            $("#pSearch").show();
        }
        else {
            Patient_details_fun(val1, val2);
            $("#pSearch").hide();
            $("#iftablesearch").removeClass("col-md-9");
        }
    }
    else {
        if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
            LoadBranchFilter();
        }
        else {
            //if ($('#hiddenRole_id').val() == 1)
            //{
            //    LoadBranchFilter();
            //}
            loadpatientcount();
            $("#pSearch").show();
        }

    }
    $('.cd-filter-block h4').on('click', function () {
        $(this).toggleClass('closed').siblings('.cd-filter-content').slideToggle(300);
        $('#pSearch').animate({
            scrollTop: $(this).offset().top
        }, 1000);
    })
    $('#fnephropathy').change(function () {
        if ($(this).is(":checked")) {
            $("#fnephroStage").removeClass("hide");
            //$("#fnephroStage").addClass("hide");
        } else {
            $("#fnephroStage").addClass("hide");
        }
        //$('#textbox1').val($(this).is(':checked'));
    });
});

function LoadBranchFilter() {
    debugger;
    $('#SelBranchFilter').empty();

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranchFilter').append(SubDepartment);
                        $('#SelBranchFilter').change();
                    }
                    else {

                        $('#SelBranchFilter').append(default_opt + SubDepartment);
                    }

                    if ($('#hiddenRole_id').val() == 2) {
                        $("#SelBranch_div").show();
                        $('.da-load-patsearch').addClass('hide');
                        $("#SelBranch_div").removeClass('branchsearch');

                    }
                    else {
                        //if ($('#hiddenRole_id').val() == 1) {
                        //    $("#SelBranch_div").show();
                        //    $('.da-load-patsearch').addClass('hide');
                        //    $("#SelBranch_div").removeClass('branchsearch');
                        //    $('#SelBranchFilter').val($('#HospitalBranchID').val());
                        //    //$('#SelBranchFilter').attr('disabled', true);
                        //    //loadpatientcount();
                        //}
                        //else

                        if ($('#hiddenRole_id').val() == 6) {
                            $("#SelBranch_div").show();
                            $('.da-load-patsearch').addClass('hide');
                            $("#SelBranch_div").removeClass('branchsearch');
                            $('#SelBranchFilter').val($('#HospitalBranchID').val());
                            $('#SelBranchFilter').attr('disabled', true);
                            loadpatientcount();
                        }
                        else {
                            $('#SelBranchFilter').val($('#HospitalBranchID').val());
                            $('#SelBranchFilter').attr('disabled', true);
                            loadpatientcount();
                        }

                        //$("#SelBranch_div").hide();

                        //  $("#SelBranch_div").addClass('branchsearch');

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

        }
    });
}

function LoadBranchForPatientSearchPopup() {
    debugger;
    $('#SelBranchSearchPopup').empty();
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {

                        $('#SelBranchSearchPopup').append(SubDepartment);
                    }
                    else {

                        $('#SelBranchSearchPopup').append(default_opt + SubDepartment);
                    }

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

                        $('#SelBranchSearchPopup').val($('#HospitalBranchID').val());
                        $('#SelBranchSearchPopup').attr('disabled', true);

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

        }
    });
}

$("#SelBranchFilter").change(function () {
    $('.da-load-patsearch').addClass('show');
    loadpatientcount();
});

$("#SelFilter").change(function () {
    debugger;
    loadPatient();
});


function loadpatientcount() {
    debugger;
    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'loadcount',
        limitstart: $('#limitstart').val(),
        limitend: $('#limitend').val(),
        branch_id: $("#SelBranchFilter").val() == null || $("#SelBranchFilter").val() == '' ? $('#HospitalBranchID').val() : $("#SelBranchFilter").val(),
        FPatient_id: $("#Mtxtpatient_id").val(),
        patient_first_name: $("#txtname").val(),
        age: $("#pat_sear_age").val(),
        mobile_no: $("#txtphone").val(),
        gender: $("#FddGender").val().join(",")
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
                $('.pagination').empty();
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.length > 0) {
                        debugger;
                        jsonLength = data1[0].count;

                        if (jsonLength > 0 && $('#Patient_Id').val() == '') {
                            $('.pagination').show();
                        }
                        else {
                            $('.pagination').hide();
                        }
                        var tot = parseInt(jsonLength) % 12;
                        var tots = parseInt(jsonLength) / 12;
                        if (tot > 0) {
                            tots = parseInt(tots) + parseInt(1);
                        }
                        jsonLength = tots;

                        //pagenation
                        var firstli = $("<li>", { id: "pageFirst", "class": "disabled" });
                        var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
                        firsta.html("First")
                        firstli.append(firsta);
                        $('.pagination').append(firstli);

                        var prevli = $("<li>", { id: "pagePrev", "class": "disabled" });
                        var preva = $("<a>", { id: "0", "class": "prev", "onclick": "prevPagination()" });
                        preva.html("<<")
                        prevli.append(preva);
                        $('.pagination').append(prevli);


                        for (var i = 1; i < jsonLength + 1; i++) {
                            if (i == 1) {
                                li[i] = $("<li>", { id: "", "class": "active" });
                                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                                a[i].html(i)
                                li[i].append(a[i]);
                                $('.pagination').append(li[i]);
                            } else {
                                li[i] = $("<li>", { id: "" });
                                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                                a[i].html(i)
                                li[i].append(a[i]);
                                $('.pagination').append(li[i]);
                            }

                            if (i >= 10) {
                                break;
                            }
                        }

                        if (jsonLength <= 10) {
                            var nextli = $("<li>", { id: "pageNext", "class": "disabled" });
                            var nexta = $("<a>", { id: "", "class": "next", "onclick": "nextPagination()" });
                            nexta.html(">>")
                            nextli.append(nexta);
                            $('.pagination').append(nextli);

                            var lastli = $("<li>", { id: "pageLast", "class": "disabled" });
                            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
                            lasta.html("Last")
                            lastli.append(lasta);
                            $('.pagination').append(lastli);
                        } else {
                            var nextli = $("<li>", { id: "pageNext", "class": "" });
                            var nexta = $("<a>", { id: "10", "class": "next", "onclick": "nextPagination()" });
                            nexta.html(">>")
                            nextli.append(nexta);
                            $('.pagination').append(nextli);

                            var lastli = $("<li>", { id: "pageLast", "class": "" });
                            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
                            lasta.html("Last")
                            lastli.append(lasta);
                            $('.pagination').append(lastli);
                        }

                    }
                }
                else {
                    console.log(data);
                }
            }
            var val1 = '0';
            var val2 = '12';
            loadPatient(val1, val2);
            // NewPatient_listTbl();
        }


    });
}


function loadPatient(val1,val2) {
    debugger;
    $('#tblPatientSearch').empty();
    var patientID = $('#Patient_Id').val();
    var SeletedValue = $('#SelFilter').val();
    var DML;
    if (patientID != "") {
        DML = "PN";
        $('#btnloadmore').hide();
        $('#tblPatientSearch').empty();
    }
    else {
        //if (SeletedValue == 1) {
        //    DML = "AS";
        //}

        DML = 'NPSL';
    }
    var patientIDs = patientID.split('/');
    patientID = patientIDs[patientIDs.length - 1];
    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: patientID,
        Dml_Indicator: DML,
        limitstart: val1,
        limitend: val2,
        user_role: $('#hiddenRole_id').val(),
        branch_id: $("#SelBranchFilter").val() == null || $("#SelBranchFilter").val() == '' ? $('#HospitalBranchID').val() : $("#SelBranchFilter").val(),
        FPatient_id: $("#Mtxtpatient_id").val(),
        patient_first_name: $("#txtname").val(),
        age: $("#pat_sear_age").val(),
        mobile_no: $("#txtphone").val(),
        gender: $("#FddGender").val().join(",")
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),

        success: function (data) {
            debugger;
            if (jQuery.isEmptyObject((data))) {
                //$('#tblPatientSearch').empty();
                $('#patientsearchtablebody').empty();
                $('#patientsearchtable').dataTable().fnClearTable();
                // $('#patientsearchtable').dataTable().fnDestroy();               
                $('#tblPatientSearch').html('<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>');
            }
            else {
                var data2 = JSON.parse(data);
                console.log(data2)
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var j = 0;
                    var PatientSearch = '';
                    console.log(data1);
                    if (data1.length > 2) {
                        $('#btnloadmore').show();
                        var start = $('#limitstart').val();
                        var end = $('#limitend').val();
                        $('#limitstart').val(end);
                        $('#limitend').val(parseInt(end) + parseInt(21));
                    }
                    else {
                        $('#btnloadmore').hide();
                    }

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

                        var Pname = '', gender = '', dob = '', age = '', ages = '', bloodgroup = '', typediabetics = '', yeardiabetics = '', lastvisit = '', nextvisit = '', Phoneno = '',
                            coupon_id = '', icon_details = '', visit_type_status = '', due_payment = '', due_status = '', PtImage='',is_convert_to_bill ='';
                        var image = emp.photo
                        var doctor_name = '';
                        console.log(image);
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        console.log(PatientPhoto)
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            // photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        Pname = emp.first_name;
                        gender = emp.gender;
                        dob = emp.DOB;
                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;
                        lastvisit = emp.last_visit;
                        nextvisit = emp.next_visit;
                        Phoneno = emp.phone_number_1;
                        coupon_id = emp.coupon_id;
                        visit_type_status = emp.visit_type_status;
                        is_convert_to_bill = emp.is_convert_to_bill;
                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }

                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }
                        if (nextvisit == '' || nextvisit == null) {
                            nextvisit = '-';
                        }
                        if (lastvisit == '' || lastvisit == null) {
                            lastvisit = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }
                        if (emp.total_due_amount > 0) {
                            due_status = 'Due'
                        }
                        j++;
                        var doctor_patient_id = '-';
                        if (emp.doctor_patient_id != '' && emp.doctor_patient_id != null) {
                            doctor_patient_id = emp.doctor_patient_id;
                        }

                        var address_details = '-';

                        if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village;
                        else if (emp.town_village != null) address_details = emp.town_village;

                        var bookoption = '';
                        var bookoptionclass = '';
                        if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                            bookoption = 'disabled';
                            bookoptionclass = 'style="pointer-events: none;"';
                        }
                        var ipredirect = '', iptransfer = '', billingredirect = '', registerbranch = ''; primary_doctor = '', Patienthistory = '', InvestigationsHistory = '', createbill = '', payment = '';
                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;

                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '"><i class="fa fa-plus mr-5" aria-hidden="true"></i>IP Admission</a></p>';
                            }
                            var createbill = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.branch_id + '"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>Create Bill</a></p>'
                        }
                        else {
                            if (visit_type_status == 1) {
                                ip_current_status = '<span class="label label-success">Admitted</span>';
                            }
                            else {
                                ip_current_status = '';
                            }
                            var iptransfer = '<p><a style="cursor:pointer;" class="btn_r btn-blue" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '"><i class="fa fa-bed mr-5" aria-hidden="true"></i>IP Transfer</a></p>';
                            var billingredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>Add Receipt</a></p><p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '"><i class="fa fa-file-text mr-5"></i>View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            Patienthistory = '<p class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Patient History</p>';
                            InvestigationsHistory = '<p class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Investigations History</p>';
                        }
                        if (emp.is_app_installed == 1) {
                            icon_details = '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="Patient App Installed"></i>'
                        }
                        if (emp.total_due_amount > 0) {
                            due_payment = '<span class="label label-danger">Due</span>'
                        }
                        var couponid = ''
                        var packagecoupondetails = ''
                        if (coupon_id != null) {
                            couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
                            packagecoupondetails = '<p class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Package / Coupon Details</p>'
                        }
                        else {
                            couponid = ''
                            packagecoupondetails = ''
                        }
                        // patient history & Investigation history & package / coupn details

                        // var packagecoupondetails = '<p class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Package / Coupon Details</p>'

                        var printcard = '<p><a style="cursor:pointer" class="btn-blue" data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);><i class="fa fa-print mr-5"  aria-hidden="true"></i>Print ID Card</a></p>';
                        if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                            if (visit_type_status == 1) {
                                payment = '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                            }
                        }
                        var watchviplist = ''
                        //if ($('#hiddenRole_id').val() != 2) {
                        watchviplist = watchviplist + '<p class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                            + '<p class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //}
                        if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                            PatientSearch = PatientSearch + '<div class="col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'
                                + icon_details
                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + watchviplist
                                // + '<p class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                //+ '<p class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                //patient history & Investigation history & package / coupon details                        
                                + printcard
                                + payment
                                //+ '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                // + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                                //+ ' <h5>  <a data-toggle="modal" data-target="#patientdetailsmodel" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + due_status + '\",this,\"' + emp.Visit_Report_id + '\",' + emp.AppointmentType + ')\'>' + Pname + '</a> </h5>' + due_payment + '  </div>'
                                + ' <h5 style="margin-top:20px;margin-right:10px;">  <a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + due_status + '\",this,\"' + emp.last_visit_id + '\",' + emp.AppointmentType + ')\'>' + Pname + '</a> </h5>' + due_payment + ' </div>'
                               + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar"> </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }



                        else {
                            PatientSearch = PatientSearch + '<div class="col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'

                                + icon_details

                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                //+'<span class="sr-only">edit</span>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + watchviplist
                                //  + '<p class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                //+ '<p class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                //patient history & Investigation history & package / coupon details                             
                                + printcard
                                //  + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                // + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                               // + ' <h5>  <a data-toggle="modal" data-target="#patientdetailsmodel" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",this,\"' + emp.Visit_Report_id + '\",' + emp.AppointmentType + ')\'>' + Pname + '</a> </h5>' + due_payment + '  </div>'
                                 + ' <h5 style="margin-right: 10px;margin-top: 20px;">  <a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + due_status + '\",+this,\"' + emp.last_visit_id + '\",' + emp.AppointmentType + ')\'>' + Pname + '</a> </h5>' + due_payment + ' </div>'
                                + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar"> </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                //+ '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p> </div>'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }
                    });
                    if (PatientSearch != '') {
                        $('#tblPatientSearch').html(PatientSearch);
                        check_priviliges();
                    }

                    $('.da-load-patsearch').addClass('hide');
                    bindingpatienttable(data1, 1000)

                    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();
                    var downloadfilename = "PatientList" + output;



                }
                else {
                    console.log(data);
                }
            }
            $('.da-load-patsearch').addClass('hide');
        }
    });
}

function bindingpatienttable(data1,totalRecords) {
    var row_data = '';
    $.each(data1, function (i, emp) {

        var gender = '', dob = '', age = '', ages = '', bloodgroup = '', Phoneno = '', registerbranch = ''; primary_doctor = ''; ip_current_status = '', icon_details = '',
        coupon_id = '', visit_type_status = '', PtImage='';
        var doctor_name = ''
        var last_name = ''
        var sec_mobile_no = ''
        var image = emp.photo
        console.log(image);
        var photoSrc;
        var PatientPhoto = $('#hdnPatientPhoto').val();
        console.log(PatientPhoto)
        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
            photoSrc = "/Content/img/profile_icon.png";
        }
        else {
            //photoSrc = PatientPhoto + image;
            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
            photoSrc = PtImage;
        }

        gender = emp.gender;
        dob = emp.DOB;
        age = emp.age;
        bloodgroup = emp.patient_blood_group;
        last_name = emp.last_name;
        Phoneno = emp.phone_number_1;
        sec_mobile_no = emp.second_phone_number;
        registerbranch = emp.register_branch_name;
        primary_doctor = emp.primary_doctor;
        ip_current_status = emp.ip_current_status;
        coupon_id = emp.coupon_id;
        visit_type_status = emp.visit_type_status;


        if (gender == 1) {
            gender = 'Male';
        }
        else if (gender == 2) {
            gender = 'Female';
        }
        else if (gender == 3) {
            gender = 'Others';
        }
        else {
            gender = '-';
        }

        if (dob == "" || dob == null) {
            if (age == "" || age == null) {
                age = '-'
                ages = age + ' years';
            }
            else {
                ages = age;
                ages = age + ' years';
            }
        }
        else {
            dob = new Date(dob);
            var today = new Date();
            var ageval = '';
            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
            age = ageval + ' Years';
            ages = age;
        }
        if (bloodgroup == '' || bloodgroup == null) {
            bloodgroup = '-';
        }
        if (registerbranch == '' || registerbranch == null) {
            registerbranch = '-';
        }
        if (last_name == '' || last_name == null) {
            last_name = '-';
        }
        if (Phoneno == '' || Phoneno == null) {
            Phoneno = '-';
        }
        if (sec_mobile_no == '' || sec_mobile_no == null) {
            sec_mobile_no = '-';
        }
        if (primary_doctor == '' || primary_doctor == null) {
            primary_doctor = '-';
        }


        if (emp.vip_description != null && emp.vip_status == "1")
            icon_details = icon_details + '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>';

        var watchlist_end_date = new Date(emp.watchlist_end_date);
        var currentdate = new Date();

        if (watchlist_end_date >= currentdate && emp.watchlist_status == "1")
            icon_details = icon_details + '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:20px;" title="Watch List"></i>';

        if (emp.is_app_installed == 1) {
            icon_details = icon_details + '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="Patient App Installed"></i>'
        }

        var bookoption = '';
        var bookoptionclass = '';
        if (emp.is_deleted == "1" || emp.is_deleted == "1") {
            bookoption = 'disabled';
            bookoptionclass = 'style="pointer-events: none;"';
        }

        var book_later = '<a class="btn btn-info btn-xs UM_8 btn_r" title="Book_Later" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar-plus-o" aria-hidden="true"></i></a>'

        var book_now = '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-edit btn-xs UM_7" title="Book_Now"  class="btn btn-block btn-flat btn-edit btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '><i class="fa fa-calendar-check-o" aria-hidden="true"></i></a>'

        var editpatient = '<p><a style="cursor:pointer"  class="btn_r btn-blue" data-id="UM_6" data-type="role_rights_edit" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '" data-nav="redirect" ><i class="fa fa-edit mr-5"></i>Patient Edit</a></p>';

        var watchviplist = ''
        //if ($('#hiddenRole_id').val() != 2) {
        var watchviplist = '<p><a style="cursor:pointer" class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus mr-5"></i>Vip List</a></p>'
            + '<p><a style="cursor:pointer" class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus mr-5"></i>Watch List</a></p>'
        //}
        //var watchviplist = '<p><a style="cursor:pointer" class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus mr-5"></i>Vip List</a></p>'
        //    + '<p><a style="cursor:pointer" class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus mr-5"></i>Watch List</a></p>'

        var ipredirect = '', iptransfer = '', billingredirect = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';

        if (ip_current_status == '' || ip_current_status == null) {
            ip_current_status = ''
            if (visit_type_status == 1) {
                var ipredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '"><i class="fa fa-plus mr-5" aria-hidden="true"></i>IP Admission</a></p>';
            }
            var createbill = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.rbranch_id + '"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>Create Bill</a></p>'
        }
        else {
            if (visit_type_status == 1) {
                ip_current_status = '<span class="label label-success">Admitted</span>';
            }
            else {
                ip_current_status = ''
            }
            var iptransfer = '<p></i><a style="cursor:pointer" class="btn_r btn-blue" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '"><i class="fa fa-bed mr-5" aria-hidden="true">IP Transfer</a></p>';
            var billingredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status +'"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>View Receipt</a></p>';
            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
            var Patienthistory = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Patient History</a></p>';
            var InvestigationsHistory = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Investigations History</a></p>';
        }

        // patient history & Investigation history & package / coupon details
        var couponid = '', packagecoupondetails = ''
        if (coupon_id != null) {
            couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
            packagecoupondetails = '<p class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Package / Coupon Details</p>'
        }
        else {
            couponid = ''
            packagecoupondetails = ''
        }
        // var packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")>Package/Coupon Details</a></p>'

        var printcard = '<p><a style="cursor:pointer" class="btn-blue" data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);><i class="fa fa-print mr-5"  aria-hidden="true"></i>Print ID Card</a></p>';

        var trB = '<div class="col-md-12 padding0"><div class="disp_if">' + book_later + book_now + ' <a href="#" class="dropdown-toggle pull-left btn-info-dots" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu  info-dropdown" id=""> <div class="text-left">' + createbill + editpatient + billingredirect + ipredirect + iptransfer + Patienthistory + InvestigationsHistory + packagecoupondetails + watchviplist + printcard + '</div></div></div></div>';

        if (visit_type_status == 1) {
            $('#c_ip_status').removeClass('hidden')
            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.first_name + '\",\"' + Phoneno + '\",\"' + emp.due_status + '\",this,\"' + emp.last_visit_id + '\",' + emp.AppointmentType + ')\'>' + emp.first_name + icon_details + "</a></td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
        }
        else {
            $('#c_ip_status').addClass('hidden')
            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + '<a data-toggle="modal" style="cursor: pointer;" onclick=\'billing_details(\"' + emp.patient_id + '\",\"' + emp.first_name + '\",\"' + Phoneno + '\",\"' + emp.due_status + '\",this,\"' + emp.last_visit_id + '\",' + emp.AppointmentType + ')\'>' + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td class='hidden'>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
        }
        // row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
    });

    $('#patientsearchtablebody').empty();
    $('#patientsearchtable').dataTable().fnClearTable();
    $('#patientsearchtable').dataTable().fnDestroy();
    //debugger;
    $('#patientsearchtablebody').append(row_data);


    datatable('patientsearchtable', 'Patient List', 'A4');
    //$('#patientsearchtable').DataTable().settings()[0]._iRecordsTotal = totalRecords;
    //$('#patientsearchtable').DataTable().draw();

    // Handle page change events
    $('#patientsearchtable').on('page.dt', function () {
        var pageInfo = $('#patientsearchtable').DataTable().page.info();
        handlePageChange(pageInfo.page + 1);
    });
}



/*<a href="javascript:void(0)" onclick=delpatient("' + emp.patient_id + '");><span class="seditapp pull-right sdelh"><i class="fa fa-trash"></i></span></a>*/

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

//function PrintCard(patientid, hospitalid, branch_id, event) {
//    debugger;
//    var did = $(event).attr("data-id");
//    var navigation = $(event).attr("data-nav");
//    var name = $(event).attr("data-name");
//    var columntype = $(event).attr("data-type");
//    debugger;
//    var chkprevilige = check_previlige(did, navigation, name, columntype);
//    $.when(chkprevilige)
//     .then(function (data) {
//         var data1 = JSON.parse(data);
//         if (data1.msg == "Success") {
//             var data1 = data1.data;
//             if (jQuery.isEmptyObject((data1))) {
//             }
//             else {
//                 var j = 0;
//                 var status = data1.Table[0].role_rights_add
//                 if (status == 0) {
//                     return;
//                 }
//                 else {
//                     var load_data = {
//                         indicator_id: "LRD",
//                         ReportId: "75"
//                     }
//                     $.ajax({
//                         async: true,
//                         type: 'POST',
//                         url: '/reports/Hospital_Reports',
//                         contentType: 'application/json; charset=UTF-8',
//                         data: JSON.stringify(load_data),
//                         success: function (data) {
//                             var data1 = JSON.parse(data);
//                             if (data1.msg == "Success") {
//                                 data1 = data1.data;
//                                 if (jQuery.isEmptyObject((data1))) {
//                                 }
//                                 else {
//                                     debugger;
//                                     var ReportName = ''; var reportparameters = "";
//                                     if (data1.Table[0] != null) {
//                                         ReportName = data1.Table[0].report_form_name;
//                                         var dml_indicator = data1.Table[0].dml_indicator;
//                                         reportparameters = data1.Table[0].report_parameters_list;
//                                         $('#iframeHeader').html(ReportName);
//                                         var load_data = {
//                                             dmlind: dml_indicator,
//                                             report_name: ReportName,
//                                             branchid: branch_id,
//                                             hospitalid: hospitalid,
//                                             patientid: patientid,
//                                             reportparameters: reportparameters
//                                         }
//                                         $.ajax({
//                                             async: true,
//                                             type: 'POST',
//                                             url: '/reports/SetReportParameters',
//                                             contentType: 'application/json; charset=UTF-8',
//                                             data: JSON.stringify(load_data),
//                                             success: function (data) {
//                                                // $('#iframepopup').modal('toggle');
//                                                // $('#dvReport').html('<iframe src="/Webform/WebForm1.aspx" id="dvLoadingReport" style="width: 100%;min-height: 450px; max-height: 450px; overflow: auto;"></iframe>');
//                                                 var byteArray = new Uint8Array(data);
//                                                     var blob = new Blob([byteArray], { type: "application/pdf" });
//                                                     var link = window.URL.createObjectURL(blob);
//                                                     //window.open(link, '_blank');
//                                                     iframe = document.createElement('iframe'); //load content in an iframe to print later
//                                                     document.body.appendChild(iframe);
//                                                     iframe.style.display = 'none';
//                                                     iframe.src = link;
//                                                     iframe.onload = function () {
//                                                         setTimeout(function () {
//                                                             iframe.focus();
//                                                             iframe.contentWindow.print();
//                                                         }, 1);
//                                                     };
//                                                 }                                          
//                                         });
//                                     }
//                                 }
//                             }
//                             else {
//                                 console.log(data2);
//                             }
//                         }
//                     });
//                 }
//             }
//         }
//     })
//    }


function PrintCard(patientid, hospitalid, branch_id, event) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
        .then(function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var j = 0;
                    var status = data1.Table[0].role_rights_add
                    if (status == 0) {

                        return;
                    }
                    else {



                        var load_data = {
                            formid: "75",
                            //report_name: ReportName,
                            branchid: branch_id,
                            hospitalid: hospitalid,
                            patientid: patientid,

                        }
                        //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/reports/PrintCrystalReport',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(load_data),
                            success: function (data) {
                                var byteArray = new Uint8Array(data);
                                var blob = new Blob([byteArray], { type: "application/pdf" });
                                var link = window.URL.createObjectURL(blob);
                                //window.open(link, '_blank');
                                iframe = document.createElement('iframe'); //load content in an iframe to print later
                                document.body.appendChild(iframe);

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





function Patient_details_fun(val1, val2) {
    var patientID = $('#Patient_details').val();
    var patientdetails = '', PtImage='';
    patientdetails = " and ((MI.first_name like '%" + patientID + "%') or (MI.phone_number_1 like '%" + patientID + "%') or (MI.phone_number_2 like '%" + patientID + "%') or (PA.Patient_id like '%" + patientID + "%')"
    patientdetails = patientdetails + " or (mad.address_line_1 like '%" + patientID + "%') or (mad.address_line_2 like '%" + patientID + "%') or (mad.town_village like '%" + patientID + "%'))"
    $('#btnloadmore').hide();
    $('#tblPatientSearch').empty();
    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: patientdetails,
        patient_first_name: patientID,
        Dml_Indicator: "PSD",
        limitstart: val1,
        limitend: val2,
        user_role: $('#hiddenRole_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#tblPatientSearch').empty();
                $('#tblPatientSearch').html('<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>');
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var j = 0;
                    var PatientSearch = '';
                    if (data1.length > 0) {
                        $('#btnloadmore').show();
                        var start = $('#limitstart').val();
                        var end = $('#limitend').val();
                        $('#limitstart').val(end);
                        $('#limitend').val(parseInt(end) + parseInt(21));
                        $.each(data1, function (i, emp) {
                            debugger;
                            var doctor_patient_id = '';
                            if (emp.doctor_patient_id == '' || emp.doctor_patient_id == null) {
                                doctor_patient_id = ''
                            }
                            else {
                                doctor_patient_id = ' | ' + emp.doctor_patient_id;
                            }
                            var image = emp.photo
                            var photoSrc, address;
                            var PatientPhoto = $('#hdnPatientPhoto').val();
                            if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                                photoSrc = "/Content/img/profile_icon.png";
                            }
                            else {
                                // photoSrc = PatientPhoto + image;
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                                photoSrc = PtImage;
                            }
                            if (emp.address_line_1 != "" && emp.address_line_1 != null && emp.address_line_2 != "" && emp.address_line_2 != null && emp.town_village != null && emp.town_village != null) {
                                address = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village;
                            }
                            else if (emp.address_line_1 != "" && emp.address_line_1 != null && emp.address_line_2 != "" && emp.address_line_2 != null) {
                                address = emp.address_line_1 + "," + emp.address_line_2;
                            }
                            else if (emp.address_line_1 != "" && emp.address_line_1 != null) {
                                address = emp.address_line_1;
                            }
                            else {
                                address = "";
                            }
                            var patient_id = emp.Patient_id;
                            var patient_first_name = emp.patient_first_name;
                            var phoneNumber1 = emp.phone_number_1;
                            var phoneNumber2 = emp.phone_number_2;
                            var bookoption = '';
                            var bookoptionclass = '';
                            if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                                bookoption = 'disabled';
                                bookoptionclass = 'style="pointer-events: none;"';
                            }
                            PatientSearch = PatientSearch + '<tr><td>' + emp.Patient_id + doctor_patient_id + '</td><td><a href="/casestudy/CaseStudyView?patient_id=' + patient_id + '">' + patient_first_name + '</td><td>' + phoneNumber1 + '</td><td>' + phoneNumber2 + '</td><td>' + address + '</td><td><div class="col-md-7 col-sm-12" style="display:inline-flex;"><a ' + bookoptionclass + bookoption + ' class="btn btn-xs btn-info mtopnbot mr-20 btn-later UM_8" href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.Patient_id + '&PName=' + emp.patient_first_name + '" >Book Later</a><a onclick=direct_appointment_booking("' + patient_id + '") class="btn btn-primaryuse btn-xs mtopnbot mr-20 UM_7" ' + bookoptionclass + bookoption + ' >Book Now</a><a style="display:none" onclick=\'collectpayment(\"' + emp.Patient_id + '\",\"' + emp.patient_first_name + '\",\"' + emp.phone_number_1 + '\",\"' + photoSrc + '\")\'; class="btn btn-primaryuse btn-xs mtopnbot " >Payment</a></div></td></tr>';

                        });
                        var boadystr = '<tbody>';
                        var boadyend = '</tbody></table></div>';
                        var patienthead = '<div class="table-responsive cus-ps-table"><table class="table-responsive table table-bordered table-striped no-footer dataTable"><thead><tr><th>Patient Id</th><th>Patient Name</th><th>phone number 1</th><th>phone number 2</th><th>Address</th><th>Action</th></tr></thead>';
                        if ($(window).width() > 1200) {
                            $('#tblPatientSearch').html(patienthead + boadystr + PatientSearch + boadyend);
                            $('#dashMysheduleTable').DataTable({
                                "lengthChange": false,
                                "info": false,
                                "pageLength": 1000,
                                "bPaginate": false,
                                "ordering": false
                            });
                        }
                        $('#shade_slot').hide();
                        if (PatientSearch != '') {
                            check_priviliges();
                        }
                    }
                    else {
                        $('#btnloadmore').hide();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
    $('#patloader').hide();
}

$('#btnloadmore').click(function () {
    loadPatient();
});


function editpatient(val) {
    alert(val);
}

function delpatient(val) {
    if (confirm('sure you want to delete this patient?')) {
        var PatientSearchData = {
            Doctor_Id: $('#HiddenDoctorID').val(),
            Dml_Indicator: 'PD',
            Condition: val
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PatientSearch/PatientSearch_Select',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(PatientSearchData),
            success: function (data) {
                var data2 = JSON.parse(data);
                if (jQuery.isEmptyObject((data2.data))) {
                    toastr.warning('Something went wrong. Please try after sometime');
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        if (data1.length > 0) {
                            var result = data1[0].result;
                            if (result == 'success') {
                                $('#' + val).hide();

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

                }
            }
        });
    }
    else {
    }
}





////////// watchlist function
//var patient = '';
//function watchviplist(patient_id, Phoneno, age, gender, photoSrc) {
//    alert("hello");
//    debugger;
//    $('#WatchDetails-section').removeClass('in');
//    $('#WatchDetails-section').addClass('in');
//    //if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 3) {
//    //    //$('.close').click();
//    //    setTimeout(function () { $("#myPatientSearchModal").modal('hide'); }, 300);
//    //    return false;
//    //}
//    patient = patient_id;
//    $('#patient_id').html(patient_id);
//    var name = $('#patientname_' + patient_id).val();
//    $('.PatientName').html(photoSrc);
//    $('#patphonenum').html(Phoneno);
//    var age = age + ' Years ' + gender;
//    $('#age').html(age);

//    loadwatch_parameter();

//}


var patient = '';
function watchviplist(patient_id, Phoneno, age, gender, photoSrc, elem, type) {
    debugger;
    PatientGeneralDetails(patient_id, $('#HospitalBranchID').val());
    var did = $(elem).data('id');
    var navigation = $(elem).data('nav')
    var name = $(elem).data('name')
    var columntype = $(elem).data('type')
    // alert(navigation)
    //alert(name)

    check_previlige(did, navigation, name, columntype);
    if (type == "1") {
        $('#WatchDetails-section').removeClass('in');
        $('#VIPDetails-section').addClass('in');

    }
    else {
        $('#VIPDetails-section').removeClass('in');
        $('#WatchDetails-section').addClass('in');
    }

    //if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 3) {
    //    toastr.warning("You have no rights to access this");
    //    setTimeout(function () { $("#myPatientSearchModal").modal('hide'); }, 300);
    //    return false;
    //}
    patient = patient_id;
    $('#patient_id').html(patient_id);
    var name = $('#patientname_' + patient_id).val();
    $('.PatientName').html(photoSrc);
    $('#pat-phno').html(Phoneno);
    var age = age + " " + gender;
    $('#age').html(age);


    loadwatch_parameter();
}


function watchvipclear() {
    $('#patient_id,#patient_name,#patient_phoneno,#age').html('');
}

function loadwatch_parameter() {
    debugger;
    var PrescriptionVisitId = {
        Dml_Indicator: 'P',
        patient_id: patient,
        doctor_id: $('#doctor_Id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PrescriptionVisitId),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    $('#SelParameter').empty();
                    var op = '';
                    var sel = '<option value="0">--select--</option>';
                    for (var i = 0; i < data.length; i++) {
                        op = op + '<option value=' + data[i].watch_parameter_id + '>' + data[i].description + '</option>';
                    }
                    $('#SelParameter').append(sel + op);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
    loadfrequency_parameter();
}

function loadfrequency_parameter() {
    debugger;
    var PrescriptionVisitId = {
        Dml_Indicator: 'F',
        patient_id: patient,
        doctor_id: $('#doctor_Id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PrescriptionVisitId),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
                $('#SelFrequency').empty();
                if (data2.msg == "Success") {
                    var data = data2.data;
                    var op = '';
                    var sel = '<option value="0">--select--</option>';
                    for (var i = 0; i < data.length; i++) {
                        op = op + '<option value=' + data[i].watch_frequency_id + '>' + data[i].description + '</option>';
                    }
                    $('#SelFrequency').append(sel + op);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
    loadwatch_list();
}


function loadwatch_list() {
    //sessionStorage.clear();
    //sessionStorage.removeItem('sess_data');
    var loadwatchlist = {
        Dml_Indicator: 'S',
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(loadwatchlist),
        success: function (data) {
            $('a[data-toggle="SelPriority"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
            $('a[data-toggle="SelPriority"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
            $('a[data-toggle="SelPriority"]').not('[data-title="' + 3 + '"]').removeClass('active').addClass('not-active');
            $('#WatchTable tbody').empty();
            var data2 = JSON.parse(data);
            $('#WatchTableRowCount').val(0);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    for (var i = 0; i < data.length; i++) {
                        var SelPriority = data[0].priority;

                        $('#Chknepropathy').val(SelPriority);
                        $('a[data-toggle=SelPriority][data-title="' + SelPriority + '"]').addClass('active');
                        $('#SelPriority').val(SelPriority);
                        $('#endDate').val(data[0].end_date);
                        $('#watch_id').val(data[0].watch_id);
                        $('#watch_parameter_details_id').val(data[0].watch_parameter_details_id);
                        var rowcount = $.trim($('#WatchTableRowCount').val());
                        var tot_row = (Number(rowcount) + 1);
                        //var ikey = '', target_2_val;
                        //var sess_data = data[i].ParameterDescription + "," + data[i].watch_parameter_id + "," + data[i].FrequencyDescription + "," + data[i].watch_frequency_id + "," + data[i].target_1 + "," + data[i].target_2;
                        var ikey = '', target_2_val, watch_param_id;
                        watch_param_id = data[i].watch_parameter_details_id;
                        var sess_data = data[i].ParameterDescription + "," + data[i].watch_parameter_id + "," + data[i].FrequencyDescription + "," + data[i].watch_frequency_id + "," + data[i].target_1 + "," + data[i].target_2 + "," + data[i].watch_parameter_details_id;
                        ikey = 'row' + tot_row;
                        sessionStorage.setItem(ikey, sess_data);
                        if (data[i].target_2 == null || data[i].target_2 == "") target_2_val = "";
                        else target_2_val = data[i].target_2;
                        // var value = "<tr id='t_" + ikey + "'><td>" + data[i].ParameterDescription + "</td><td>" + data[i].FrequencyDescription + "</td><td>" + data[i].target_1 + "</td><td>" + target_2_val + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                        var value = "<tr id='t_" + ikey + "'><td id='twatch_parameter_details_id_" + ikey + "' hidden>" + data[i].watch_parameter_details_id + "</td><td id='tSelParameter_" + ikey + "' data-id=" + data[i].watch_parameter_id + ">" + data[i].ParameterDescription + "</td><td id='tSelFrequency_" + ikey + "' data-id=" + data[i].watch_frequency_id + ">" + data[i].FrequencyDescription + "</td><td id='ttxttarget1_" + ikey + "'>" + data[i].target_1 + "</td><td id='ttxttarget2_" + ikey + "'>" + target_2_val + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\"," + watch_param_id + ")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

                        $('#WatchTable > tbody:last').append(value);
                        $('#WatchTableRowCount').val(tot_row);
                        if (tot_row > 0) {
                            $('#mWatchlist').prop('checked', true);
                            $('#mWatchSection').show();
                        }
                    }
                }
                else {
                    console.log(data);
                }

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

            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    var status = '';
                    for (var i = 0; i < data.length; i++) {
                        status = data[i].status;
                        if (status == 1) {
                            $('#modalVIP').prop('checked', true);
                            $('#mVIPSection').show();
                            $('#txtVipDetails').val(data[i].description);
                        }
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#SelParameter').change(function () {
    debugger;
    if ($('#SelParameter').val() == 1) {
        $('#lbltarget1').html('SYS');
        $('#lbltarget2').html('DIA');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#target2div').show();
    }
    else if ($('#SelParameter').val() == 2) {
        $('#lbltarget1').html('FBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#target2div').hide();
        
    }
    else if ($('#SelParameter').val() == 3) {
        $('#lbltarget1').html('PBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#target2div').hide();
    }
    else if ($('#SelParameter').val() == 4) {
        $('#lbltarget1').html('WEIGHT');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#target2div').hide();
    }
    else {
        $('#lbltarget1').html('Target 1');
        $('#lbltarget2').html('Target 2');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#target2div').show();
    }
});

$('#addwatchlist').click(function () {
    if ($.trim($('#SelParameter :selected').val()) == "" || $('#SelParameter :selected').val() == "0") {
        $('#PSelParameter').show();
        $('#PSelParameter').fadeOut(8000);
        $('#PSelParameter').html('Select Parameter');
        $('#SelParameter').focus();
        $('#SelParameter :selected').val('0');
        return false;
    }
    if ($.trim($('#SelFrequency :selected').val()) == "" || $('#SelFrequency :selected').val() == "0") {
        $('#PSelFrequency').show();
        $('#PSelFrequency').fadeOut(8000);
        $('#PSelFrequency').html('Select Frequency');
        $('#SelFrequency').focus();
        $('#SelFrequency :selected').val('0');
        return false;
    }
    if ($.trim($('#txttarget1').val()) == "") {
        $('#Ptxttarget1').show();
        $('#Ptxttarget1').fadeOut(8000);
        $('#Ptxttarget1').html('please enter value');
        $('#txttarget1').focus();
        $('#txttarget1').val('');
        return false;
    }
    if ($('#SelParameter').val() == 1) {
        if ($.trim($('#txttarget2').val()) == "") {
            $('#Ptxttarget2').show();
            $('#Ptxttarget2').fadeOut(8000);
            $('#Ptxttarget2').html('please enter value');
            $('#txttarget2').focus();
            $('#txttarget2').val('');
            return false;
        }
    }

    var sess_key;
    var rowcount = $.trim($('#WatchTableRowCount').val());
    var tot_row = (Number(rowcount) + 1);
    var ikey = '';
    // var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val();
    var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val() + "," + 0;
    if (rowcount >= 1) {
        var getEid = $('#WatchTable  tr').last();
        var actId = getEid.prop('id');
        var afterSplit = actId.split('row');
        afterInc = parseInt(afterSplit[1]) + 1;
        console.log(afterInc);
        ikey = 'row' + afterInc;
    }
    else {

        ikey = 'row' + tot_row;
    }
    sessionStorage.setItem(ikey, sess_data);

    //var value = "<tr id='t_" + ikey + "'><td>" + $('#SelParameter :selected').text() + "</td><td>" + $('#SelFrequency :selected').text() + "</td><td>" + $('#txttarget1').val() + "</td><td>" + $('#txttarget2').val() + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    var value = "<tr id='t_" + ikey + "'><td id='twatch_parameter_details_id_" + ikey + "' hidden>0</td><td  id='tSelParameter_" + ikey + "' data-id=" + $('#SelParameter :selected').val() + ">" + $('#SelParameter :selected').text() + "</td><td id='tSelFrequency_" + ikey + "' data-id=" + $('#SelFrequency :selected').val() + ">" + $('#SelFrequency :selected').text() + "</td><td  id='ttxttarget1_" + ikey + "'>" + $('#txttarget1').val() + "</td><td id='ttxttarget2_" + ikey + "'>" + $('#txttarget2').val() + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\",0)'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#WatchTable > tbody:last').append(value);
    $('#WatchTableRowCount').val(tot_row);
    $('#SelParameter').val(0);
    $('#SelFrequency').val(0);
    $('#txttarget1').val('');
    $('#txttarget2').val('');

});

function watchlistedit(val) {

    $('#addwatchlist').hide();
    $('#updatewatchlist').show();
    $('#hnd_watchlist').val(val);

    var gkey = val;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#SelParameter').val(row_data_split[1]);
    $('#SelFrequency').val(row_data_split[3]);
    $('#txttarget1').val(row_data_split[4]);
    $('#txttarget2').val(row_data_split[5]);

    $("#hdn_watch_details_id").val(row_data_split[6]);
    if (row_data_split[1] == 1) {
        $('#lbltarget1').html('SYS');
        $('#lbltarget2').html('DIA');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }
    else if (row_data_split[1] == 2) {
        $('#lbltarget1').html('FBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else if (row_data_split[1] == 3) {
        $('#lbltarget1').html('PBS');
        $('#lbltarget1').show();
        $('#txttarget1').show();
        $('#lbltarget2').hide();
        $('#txttarget2').hide();
    }
    else {
        $('#lbltarget1').html('Target 1');
        $('#lbltarget2').html('Target 2');
        $('#lbltarget1').show();
        $('#lbltarget2').show();
        $('#txttarget2').show();
        $('#txttarget1').show();
    }

}
//function watchlistdelete(val) {
//    sessionStorage.removeItem(val);
//    $('#t_' + val).remove();
//    var a = $.trim($('#WatchTableRowCount').val());
//    var a = (a) - (1);
//    $('#WatchTableRowCount').val(a);
//}
function watchlistdelete(val, watch_id) {
    debugger;
    if (watch_id != 0) {
        var Notesdata = {
            watch_parameter_details_id: watch_id,
            Dml_Indicator: 'D'
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/caseStudy/Watchlist',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(Notesdata),
            success: function (data) {
                if (jQuery.isEmptyObject((data))) {
                }
                else {

                }
            }
        });
        loadwatch_list();
    }
    else {
        sessionStorage.removeItem(val);
        $('#t_' + val).remove();
        var a = $.trim($('#WatchTableRowCount').val());
        var a = (a) - (1);
        $('#WatchTableRowCount').val(a);
    }
}
$('#updatewatchlist').click(function () {
    var table_id = $('#hnd_watchlist').val();


    if ($.trim($('#SelParameter :selected').val()) == "" || $('#SelParameter :selected').val() == "0") {
        $('#PSelParameter').show();
        $('#PSelParameter').fadeOut(8000);
        $('#PSelParameter').html('Select Parameter');
        $('#SelParameter').focus();
        $('#SelParameter :selected').val('0');
        return false;
    }
    if ($.trim($('#SelFrequency :selected').val()) == "" || $('#SelFrequency :selected').val() == "0") {
        $('#PSelFrequency').show();
        $('#PSelFrequency').fadeOut(8000);
        $('#PSelFrequency').html('Select Frequency');
        $('#SelFrequency').focus();
        $('#SelFrequency :selected').val('0');
        return false;
    }
    if ($.trim($('#txttarget1').val()) == "") {
        $('#Ptxttarget1').show();
        $('#Ptxttarget1').fadeOut(8000);
        $('#Ptxttarget1').html('Select Types');
        $('#txttarget1').focus();
        $('#txttarget1').val('');
        return false;
    }
    if ($('#SelParameter').val() == 1) {
        if ($.trim($('#txttarget2').val()) == "") {
            $('#Ptxttarget2').show();
            $('#Ptxttarget2').fadeOut(8000);
            $('#Ptxttarget2').html('Enter the value');
            $('#txttarget2').focus();
            $('#txttarget2').val('');
            return false;
        }
    }

    $('#addwatchlist').show();
    $('#updatewatchlist').hide();





    // var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val();
    var sess_data = $('#SelParameter :selected').text() + "," + $('#SelParameter').val() + "," + $('#SelFrequency :selected').text() + "," + $('#SelFrequency').val() + "," + $('#txttarget1').val() + "," + $('#txttarget2').val() + "," + $("#hdn_watch_details_id").val();

    var ikey = table_id;
    sessionStorage.setItem(ikey, sess_data);

    $('#WatchTable > tbody:last').empty();


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


    for (i = 1; i <= tot_row; i++) {
        var gkey = 'row' + i;
        console.log(sessionStorage.getItem(gkey));
        var row_data = sessionStorage.getItem(gkey);

        if (row_data == null) {
            console.log(gkey + '--------->' + row_data);
        }
        if (row_data != null) {
            row_data = row_data.split(',');



            //var value = "<tr id='t_" + ikey + "'><td>" + $('#SelParameter :selected').text() + "</td><td>" + $('#SelFrequency :selected').text() + "</td><td>" + $('#txttarget1').val() + "</td><td>" + $('#txttarget2').val() + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            //  var value = "<tr id='t_" + gkey + "'><td>" + row_data[0] + "</td><td>" + row_data[2] + "</td><td>" + row_data[4] + "</td><td>" + row_data[5] + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + gkey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
            var value = "<tr id='t_" + gkey + "'><td id='twatch_parameter_details_id_" + gkey + "' hidden>" + row_data[6] + "</td><td id='tSelParameter_" + gkey + "' data-id=" + row_data[1] + ">" + row_data[0] + "</td><td id='tSelFrequency_" + gkey + "' data-id=" + row_data[3] + ">" + row_data[2] + "</td><td id='ttxttarget1_" + gkey + "'>" + row_data[4] + "</td><td id='ttxttarget2_" + gkey + "'>" + row_data[5] + "</td><td><button class='edit btn btn-default  btn-sm btn-add' onclick='watchlistedit(\"" + gkey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-default  btn-sm btn-add' onclick='watchlistdelete(\"" + gkey + "\"," + row_data[6] + ")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

            $('#WatchTable > tbody:last').append(value);
        }
    }

    $('#SelParameter').val(0);
    $('#SelFrequency').val(0);
    $('#txttarget1').val('');
    $('#txttarget2').val('');


});


$('#btnwatchlist').click(function () {
    debugger;
    if ($('#SelPriority').val() == "" && $.trim($('#endDate').val()) == "" && $.trim($('#WatchTableRowCount').val()) == "0") {
        if ($('#txtVipDetails').val() != "") {
            AddVip();
        }
    }
    else {
        if ($('#SelPriority').val() == "") {
            $('#PSelPriority').show();
            $('#PSelPriority').fadeOut(8000);
            $('#PSelPriority').html('Select Priority');
            $('#SelPriority').focus();
            $('#SelPriority').val('');
            return false;
        }
        if ($.trim($('#endDate').val()) == "") {
            $('#PendDate').show();
            $('#PendDate').fadeOut(8000);
            $('#PendDate').html('End Date');
            $('#endDate').focus();
            $('#endDate').val('');
            return false;
        }
        //var Notesdata = {
        //    watch_id: $('#watch_id').val(),
        //    Dml_Indicator: 'D'
        //}
        //$.ajax({
        //    async: true,
        //    type: 'POST',
        //    url: '/caseStudy/Watchlist',
        //    contentType: 'application/json; charset=UTF-8',
        //    data: JSON.stringify(Notesdata),
        //    success: function (data) {
        //        Addwatchlist();
        //        if (jQuery.isEmptyObject((data))) {
        //        }
        //        else {
        Addwatchlist();
        //        }
        //    }
        //});
    }

});


function Addwatchlist() {
    var enddate = $('#endDate').val();
    enddate = enddate.split('/');
    var End_Date = enddate[2] + "-" + enddate[1] + "-" + enddate[0];
    var Notesdata = {
        patient_id: patient,
        created_by: $('#HiddenDoctorID').val(),
        removed_on: '',
        removed_by: $('#HiddenDoctorID').val(),
        doctor_id: $('#HiddenDoctorID').val(),
        priority: $('#SelPriority').val(),
        end_date: End_Date,
        Dml_Indicator: 'I'
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Watchlist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Notesdata),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var watch_id = '';
                    if (data1.length > 0) {
                        $.each(data1, function (i, emp) {
                            watch_id = emp.watch_id;
                        });
                        var tot_rowM = $.trim($('#WatchTableRowCount').val());
                        $("#BtnLabSubmit").html('Update changes');
                        if (tot_rowM > 0) {
                            var L = 0;

                            //for (j = 1; j <= tot_rowM; j++) {
                            //    var a = $('#WatchTable_body').children('tr').eq(L);
                            //    //var a = $('#WatchTable').closest('table').attr('id');
                            //    //var b = a;
                            //    var b = a.prop('id');
                            //    L++;
                            //    var C = b.split('_');
                            //    var gkey = C[1];
                            //    var row_data = sessionStorage.getItem(gkey);
                            //    var K = 0;
                            //    if (row_data == "") {
                            //        console.log(gkey + '--------->' + row_data);
                            //    }
                            //    if (row_data != "" && row_data != null) {
                            //        console.log(gkey + '-------' + row_data);
                            //        row_data = row_data.split(',');
                            //        var sms = {
                            //            Dml_Indicator: 'DI',
                            //            watch_parameter_id: row_data[1],
                            //            watch_id: watch_id,
                            //            watch_frequency_id: row_data[3],
                            //            target_1: row_data[4],
                            //            target_2: row_data[5],
                            //        }
                            //        $.ajax({
                            //            async: true,
                            //            type: 'POST',
                            //            url: '/CaseStudy/Watchlist',
                            //            contentType: 'application/json; charset=UTF-8',
                            //            data: JSON.stringify(sms),
                            //            success: function (data) {
                            //            }
                            //        });
                            //    }
                            //}
                            var customers = new Array();
                            for (j = 0; j < tot_rowM; j++) {
                                var a = $('#WatchTable_body').find("tr").eq(j).prop("id");
                                a = a.split("t_row")[1];
                                var customer = {};

                                customer.watch_id = watch_id;
                                customer.watch_parameter_details_id = $('#twatch_parameter_details_id_row' + a).html();
                                customer.watch_parameter_id = $('#tSelParameter_row' + a).attr("data-id");
                                customer.watch_frequency_id = $('#tSelFrequency_row' + a).attr("data-id");
                                customer.target_1 = $('#ttxttarget1_row' + a).html();
                                customer.target_2 = $('#ttxttarget2_row' + a).html();
                                customer.Dml_Indicator = 'DDT';

                                customers.push(customer);
                            }
                            $.ajax({
                                async: true,
                                type: 'POST',
                                url: '/CaseStudy/Watchlistdetails',
                                contentType: 'application/json; charset=UTF-8',
                                data: JSON.stringify(customers),
                                success: function (data) {
                                    debugger;
                                    var data1 = JSON.parse(data);
                                    console.log(data1);
                                    if (data1.msg == "Success") {
                                        toastr.success("Patient Data Saved Successfully");
                                    }
                                }
                            });


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

            }


            AddVip();
            popclear();
            //  toastr.success("Patient Data Saved Successfully")
            $('#myPatientSearchModal').modal('toggle');
        }
    });
}

function AddVip() {
    debugger
    var description = $.trim($('#txtVipDetails').val());
    var status = "1";
    if (description == '') {
        status = "0";
    }
    var vipdata = {
        patient_id: patient,
        doctor_id: $('#HiddenDoctorID').val(),
        description: description,
        status: status,
        created_by: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'I'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/Viplist',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(vipdata),
        success: function (data) {
            $('#txtVipDetails').val('');
            var data1 = JSON.parse(data);
            console.log(data1);
            if (jQuery.isEmptyObject((data))) {
                //   toastr.success('Patient has been added Successfully')
            }
            else {
            }
        }
    });
}




// new filter start

$('#btnfilter').click(function () {
    debugger;
    if (parseInt($('#tab_val').val()) == 1) {
        loadpatientcount();
    }
    else {
        Diabetes_filter();
        //filter();
    }

});
$('#pat_clear').click(function () {
    debugger;
    $("#filter_visit").val('1');
    $("#nextDate").val("");
    $("#nexttoDate").val("");
})


function pagecount() {
    $('#patloader1').show();
    var ageStart = $.trim($('#slider-range-value1').html());
    var ageEnd = $.trim($('#slider-range-value2').html());

    var Mpatient_id = $('#Mtxtpatient_id').val();
    var Name = $('#txtname').val();

    var male = '', female = '', other = '', None = '';
    if ($('#fmale').prop("checked") == true) {
        male = 1;
    }
    else if ($('#fmale').prop("checked") == false) {
        male = 0;
    }

    if ($('#ffemale').prop("checked") == true) {
        female = 1;
    }
    else if ($('#ffemale').prop("checked") == false) {
        female = 0;
    }

    if ($('#fothers').prop("checked") == true) {
        other = 1;
    }
    else if ($('#fothers').prop("checked") == false) {
        other = 0;
    }

    if ($('#fnone').prop("checked") == true) {
        None = 1;
    }
    else if ($('#fnone').prop("checked") == false) {
        None = 0;
    }

    var phone_no = $('#txtphone').val();
    var nextappointment = $('#nextDate').val();
    var appDate = $('#appDate').val();

    var PCondition = '';
    if (Mpatient_id != '') {
        PCondition = ' and (PA.patient_id like concat("%' + Mpatient_id + '%"))';
    }
    if (Name != '') {

        PCondition = PCondition + ' and (MI.first_name like concat("%' + Name + '%"))';
    }
    if (ageStart != '' && ageEnd != '') {

        PCondition = PCondition + ' and (MI.age between ' + ageStart + ' and ' + ageEnd + ')';
    }
    if (male != '' && female != '' && None != '') {
        PCondition = PCondition + ' and ((MI.gender=1) or (MI.gender=2) or (MI.gender=3) or (MI.gender is null))';
    }
    else if (male != '' && female != '') {
        PCondition = PCondition + ' and ((MI.gender=1) or (MI.gender=2))';
    }
    else if (male != '') {
        PCondition = PCondition + ' and ((MI.gender=1))';
    }
    else if (female != '') {
        PCondition = PCondition + ' and ((MI.gender=2))';
    }
    else if (None != '') {
        PCondition = PCondition + ' and ((MI.gender is null or MI.gender = 3))';
    }
    if (phone_no != '') {
        PCondition = PCondition + ' and (MI.phone_number_1 like concat("%' + phone_no + '%") or MI.phone_number_2 like concat("%' + phone_no + '%"))';
    }

    var d = new Date();

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

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

    if (nextappointment != '') {
        var nextappointment1 = nextappointment.split('-');
        var nextappointmentstart = $.trim(nextappointment1[0]);
        var nextappointmentend = $.trim(nextappointment1[1]);
        var nextappointmentstarts, nextappointmentends;
        if (output != nextappointmentstart && output != nextappointmentend) {
            nextappointmentstarts = nextappointmentstart.split('/');
            nextappointmentstart = nextappointmentstarts[2] + '-' + nextappointmentstarts[1] + '-' + nextappointmentstarts[0];
            nextappointmentends = nextappointmentend.split('/');
            nextappointmentend = nextappointmentends[2] + '-' + nextappointmentends[1] + '-' + nextappointmentends[0];
            PCondition = PCondition + ' and (date(vs.next_appointment_date) between "' + nextappointmentstart + '" and "' + nextappointmentend + '")';
        }
    }
    if (appDate != '') {
        var appDate1 = appDate.split('-');
        var appDatestart = $.trim(appDate1[0]);
        var appDateend = $.trim(appDate1[1]);
        var appDatestarts, appDateends;
        if (output != appDatestart && output != appDateend) {
            appDatestarts = appDatestart.split('/');
            appDatestart = appDatestarts[2] + '-' + appDatestarts[1] + '-' + appDatestarts[0];
            appDateends = appDateend.split('/');
            appDateend = appDateends[2] + '-' + appDateends[1] + '-' + appDateends[0];
            PCondition = PCondition + ' and (date(vs.created_on) between "' + appDatestart + '" and "' + appDateend + '")';
        }
    }


    var type_d_auto = "", type_d_pdr = "", type_d_npdr = "", diab_type_1 = "", diab_type_2 = "", diab_type_3 = "", diab_type_4 = "", diab_type_5 = "", diab_type_6 = "";
    if ($('#fatomic').prop("checked") == true) {
        type_d_auto = 1;
    }
    if ($('#fpdr').prop("checked") == true) {
        type_d_pdr = 1;
    }
    if ($('#fsNPDR').prop("checked") == true) {
        type_d_npdr = 1;
    }
    if ($('#ftdtype1').prop("checked") == true) {
        diab_type_1 = 1;
    }
    if ($('#ftdtype2').prop("checked") == true) {
        diab_type_2 = 1;
    }
    if ($('#ftdgdm').prop("checked") == true) {
        diab_type_3 = 1;
    }
    if ($('#ftdmody').prop("checked") == true) {
        diab_type_4 = 1;
    }
    if ($('#ftdtype').prop("checked") == true) {
        diab_type_5 = 1;
    }
    if ($('#ftdtypenone').prop("checked") == true) {
        diab_type_6 = 1;
    }

    var dia_year_start = $('#year-range-value1').html();
    var dia_year_end = $('#year-range-value2').html();

    if (dia_year_start != "1" && dia_year_end != "100") {
        if (dia_year_start != "" && dia_year_end != "") {
            PCondition = PCondition + ' and (plf.diabetes_of_year between ' + dia_year_start + ' and ' + dia_year_end + ')';
        }
    }
    if (type_d_auto != "" && type_d_pdr != "" && type_d_npdr != "") {
        PCondition = PCondition + ' and (plf.autonomic_neuropathy != 0 or plf.pdr != 0 or plf.npdr != 0)';
    }
    else if (type_d_auto != "" && type_d_pdr != "") {
        PCondition = PCondition + ' and (plf.autonomic_neuropathy != 0 or plf.pdr != 0)';
    }
    else if (type_d_auto != "" && type_d_npdr != "") {
        PCondition = PCondition + ' and (plf.autonomic_neuropathy != 0 or plf.npdr != 0)';
    }
    else if (type_d_pdr != "" && type_d_npdr != "") {
        PCondition = PCondition + ' and (plf.pdr != 0 or plf.npdr != 0)';
    }
    else if (type_d_auto != "") {
        PCondition = PCondition + ' and (plf.autonomic_neuropathy != 0)';
    }
    else if (type_d_pdr != "") {
        PCondition = PCondition + ' and (plf.pdr != 0)';
    }
    else if (type_d_npdr != "") {
        PCondition = PCondition + ' and (plf.npdr != 0)';
    }
    else {
    }

    if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 1 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_3 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 1 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 1 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4)';
    }
    else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3)';
    }
    else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4)';
    }
    else if (diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_1 != "" && diab_type_2 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 2)';
    }
    else if (diab_type_1 != "" && diab_type_3 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 3)';
    }
    else if (diab_type_1 != "" && diab_type_4 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 4)';
    }
    else if (diab_type_1 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_1 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 1 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_2 != "" && diab_type_3 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 3)';
    }
    else if (diab_type_2 != "" && diab_type_4 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 4)';
    }
    else if (diab_type_2 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_2 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 2 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_3 != "" && diab_type_4 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 3 or plf.type_of_diabetes = 4)';
    }
    else if (diab_type_3 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 3 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_3 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 3 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_4 != "" && diab_type_5 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 4 or plf.type_of_diabetes = 5)';
    }
    else if (diab_type_4 != "" && diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 4 or plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else if (diab_type_1 != "") {
        PCondition = PCondition + ' and plf.type_of_diabetes = 1';
    }
    else if (diab_type_2 != "") {
        PCondition = PCondition + ' and plf.type_of_diabetes = 2';
    }
    else if (diab_type_3 != "") {
        PCondition = PCondition + ' and plf.type_of_diabetes = 3';
    }
    else if (diab_type_4 != "") {
        PCondition = PCondition + ' and plf.type_of_diabetes = 4';
    }
    else if (diab_type_5 != "") {
        PCondition = PCondition + ' and plf.type_of_diabetes = 5';
    }
    else if (diab_type_6 != "") {
        PCondition = PCondition + ' and (plf.type_of_diabetes = 6 or plf.type_of_diabetes = NULL)';
    }
    else { }

    var last = ' group by PA.Patient_id order by PA.Patient_id asc';
    PCondition = PCondition + last;
    console.log(PCondition);

    var dml_indicator;
    if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
        dml_indicator = "filtercount_D";
    }
    else {
        dml_indicator = "filtercount_A";
    }

    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: PCondition,
        Dml_Indicator: 'filtercount',
        limitstart: $('#limitstart').val(),
        limitend: $('#limitend').val(),
        user_role: $('#hiddenRole_id').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            console.log("----------------------------");
            console.log(data);
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.length > 0) {
                        jsonLength = data1[0].count;

                        if (jsonLength > 0) {
                            $('.pagination').show();

                        }
                        else {
                            $('.pagination').hide();
                        }

                        var tot = parseInt(jsonLength) % 12;
                        var tots = parseInt(jsonLength) / 12;
                        if (tot > 0) {
                            tots = parseInt(tots) + parseInt(1);
                        }
                        jsonLength = tots;
                        $('.pagination').empty();
                        //pagenation
                        var firstli = $("<li>", { id: "pageFirst", "class": "disabled" });
                        var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
                        firsta.html("First")
                        firstli.append(firsta);
                        $('.pagination').append(firstli);

                        var prevli = $("<li>", { id: "pagePrev", "class": "disabled" });
                        var preva = $("<a>", { id: "0", "class": "prev", "onclick": "prevPagination()" });
                        preva.html("<<")
                        prevli.append(preva);
                        $('.pagination').append(prevli);


                        for (var i = 1; i < jsonLength + 1; i++) {
                            if (i == 1) {
                                li[i] = $("<li>", { id: "", "class": "active" });
                                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenationf($(this))" });
                                a[i].html(i)
                                li[i].append(a[i]);
                                $('.pagination').append(li[i]);
                            } else {
                                li[i] = $("<li>", { id: "" });
                                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenationf($(this))" });
                                a[i].html(i)
                                li[i].append(a[i]);
                                $('.pagination').append(li[i]);
                            }

                            if (i >= 10) {
                                break;
                            }
                        }

                        if (jsonLength <= 10) {
                            var nextli = $("<li>", { id: "pageNext", "class": "disabled" });
                            var nexta = $("<a>", { id: "", "class": "next", "onclick": "nextPagination()" });
                            nexta.html(">>")
                            nextli.append(nexta);
                            $('.pagination').append(nextli);

                            var lastli = $("<li>", { id: "pageLast", "class": "disabled" });
                            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
                            lasta.html("Last")
                            lastli.append(lasta);
                            $('.pagination').append(lastli);
                        } else {
                            var nextli = $("<li>", { id: "pageNext", "class": "" });
                            var nexta = $("<a>", { id: "10", "class": "next", "onclick": "nextPagination()" });
                            nexta.html(">>")
                            nextli.append(nexta);
                            $('.pagination').append(nextli);

                            var lastli = $("<li>", { id: "pageLast", "class": "" });
                            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
                            lasta.html("Last")
                            lastli.append(lasta);
                            $('.pagination').append(lastli);
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
            var val1 = 0;
            var val2 = 12;
            filter(val1, val2);
        }
    });
}

function pagenation(element) {
    debugger;
    $('.da-load-patsearch').removeClass('hide');
    var id = element.attr('id');
    var end = parseInt(id) * 12;
    var start = parseInt(end) - 12;
    start = parseInt(start) + (1);
    //alert('onclick' + element.attr('id'));
    $('.pagination li.active').removeClass('active');
    element.parent("li").addClass('active')
    loadPatient(start, end);
    end = 12;
}

function pagenationf(element) {
    debugger;
    var id = element.attr('id');
    var end = parseInt(id) * 12;
    var start = parseInt(end) - 12;
    start = parseInt(start) + (1);
    //alert('onclick' + element.attr('id'));
    $('.pagination li.active').removeClass('active');
    element.parent("li").addClass('active')
    end = 12;
    filter(start, end);
}



function filter() {
    debugger;
    var d = new Date();
    var month = d.getMonth() + 1;
    var day = d.getDate();
    var output = (month < 10 ? '0' : '') + month + '/' +
        (day < 10 ? '0' : '') + day + '/' +
        d.getFullYear();
    var PCondition = '';
    if ($('#tab_val').val() == "1") {
        var male = '', female = '', other = '', None = '';
        if ($('#fmale').prop("checked") == true) male = 1;
        else male = 0;
        if ($('#ffemale').prop("checked") == true) female = 1;
        else female = 0;
        if ($('#fnone').prop("checked") == true) None = 1;
        else if ($('#fnone').prop("checked") == false) None = 0;
        if ($('#Mtxtpatient_id').val().length > 0 || $('#txtname').val().length > 0 || $('#pat_sear_age').val().length > 0 || $('#txtphone').val().length > 0 || male == 1 || female == 1 || None == 1) {
            var Mpatient_id = $('#Mtxtpatient_id').val();
            var Name = $('#txtname').val();
            var phone_no = $('#txtphone').val();
            var ageStart = $('#pat_sear_age').val();

            if (Mpatient_id != '') {
                PCondition = " and (PA.patient_id like ('%" + Mpatient_id + "%'))";
            }
            if (Name != '') {

                PCondition = PCondition + " and (MI.first_name like ('%" + Name + "%'))";
            }
            if (ageStart != '') {

                PCondition = PCondition + ' and (MI.age = ' + ageStart + ')';
            }
            if (male != '' && female != '' && None != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(1 as nvarchar)) or (MI.gender=cast(2 as nvarchar)) or (MI.gender=cast(3 as nvarchar)) or (MI.gender is null))';
            }
            else if (male != '' && female != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(1 as nvarchar)) or (MI.gender=cast(2 as nvarchar)))';
            }
            else if (male != '' && None != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(1 as nvarchar)) or (MI.gender=cast(3 as nvarchar)))';
            }
            else if (female != '' && None != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(2 as nvarchar)) or (MI.gender=cast(3 as nvarchar)))';
            }
            else if (male != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(1 as nvarchar)))';
            }
            else if (female != '') {
                PCondition = PCondition + ' and ((MI.gender=cast(2 as nvarchar)))';
            }
            else if (None != '') {
                PCondition = PCondition + ' and ((MI.gender is null or MI.gender = cast(3 as nvarchar)))';
            }
            if (phone_no != '') {
                PCondition = PCondition + " and (MI.phone_number_1 like ('%" + phone_no + "%') or MI.phone_number_2 like ('%" + phone_no + "%'))";
            }
        }
        else {
            toastr.warning("Enter any one of the field");
        }
    }
    else if ($('#tab_val').val() == "2") {
        debugger;
        if ($('#nextDate').val() == '' || $('#nexttoDate').val() == '') {
            if ($('#nextDate').val() == '') {
                $('#PnextDate').show();
                $('#PnextDate').fadeOut(8000);
                $('#PnextDate').html('Select From Date');
                $('#nextDate').focus();
                $('#nextDate').val('');
                return false;
            }
            if ($('#nexttoDate').val() == '') {
                $('#PnexttoDate').show();
                $('#PnexttoDate').fadeOut(8000);
                $('#PnexttoDate').html('Select From Date');
                $('#nexttoDate').focus();
                $('#nexttoDate').val('');
                return false;
            }

        }
        else {
            var nextappointment = $('#nextDate').val();
            var appDate = $('#nexttoDate').val();
            nextappointment = nextappointment.split('/');
            nextappointment = nextappointment[2] + '-' + nextappointment[1] + '-' + nextappointment[0];
            appDate = appDate.split('/');
            appDate = appDate[2] + '-' + appDate[1] + '-' + appDate[0];

            if ($('#filter_visit').val() == 1) {
                PCondition = PCondition + " and (CONVERT(date,(vs.next_appointment_date)) between '" + nextappointment + "' and '" + appDate + "')";
            }
            else if ($('#filter_visit').val() == 2) {
                PCondition = PCondition + " and (CONVERT(date,(vs.created_on)) between '" + nextappointment + "' and '" + appDate + "')";
            }
            else {
                $('#Pfilter_visit').show();
                $('#Pfilter_visit').fadeOut(8000);
                $('#Pfilter_visit').html('Select Type');
                $('#filter_visit').focus();
                $('#filter_visit').val('');
                return false;
            }
        }
        //if ($('#nextDate').val().length > 0 && $('#nexttoDate').val().length > 0) {

        //if (nextappointment != '') {
        //    var nextappointment1 = nextappointment.split('-');
        //    var nextappointmentstart = $.trim(nextappointment1[0]);
        //    var nextappointmentend = $.trim(nextappointment1[1]);
        //    var nextappointmentstarts, nextappointmentends;
        //    if (output != nextappointmentstart && output != nextappointmentend) {
        //        nextappointmentstarts = nextappointmentstart.split('/');
        //        nextappointmentstart = nextappointmentstarts[2] + '-' + nextappointmentstarts[1] + '-' + nextappointmentstarts[0];
        //        nextappointmentends = nextappointmentend.split('/');
        //        nextappointmentend = nextappointmentends[2] + '-' + nextappointmentends[1] + '-' + nextappointmentends[0];
        //        PCondition = PCondition + " and (CONVERT(date,(vs.next_appointment_date)) between '" + nextappointmentstart + "' and '" + nextappointmentend + "')";
        //    }
        //}
        //if (appDate != '') {
        //    var appDate1 = appDate.split('-');
        //    var appDatestart = $.trim(appDate1[0]);
        //    var appDateend = $.trim(appDate1[1]);
        //    var appDatestarts, appDateends;
        //    if (output != appDatestart && output != appDateend) {
        //        appDatestarts = appDatestart.split('/');
        //        appDatestart = appDatestarts[2] + '-' + appDatestarts[1] + '-' + appDatestarts[0];
        //        appDateends = appDateend.split('/');
        //        appDateend = appDateends[2] + '-' + appDateends[1] + '-' + appDateends[0];
        //        PCondition = PCondition + " and (CONVERT(date,(vs.created_on)) between '" + appDatestart + "' and '" + appDateend + "')";
        //    }
        //}

        //}

    }
    else if ($('#tab_val').val() == "3") {
        var type_d_auto = "", type_d_pdr = "", type_d_npdr = "", diab_type_1 = "", diab_type_2 = "", diab_type_3 = "", diab_type_4 = "", diab_type_5 = "", diab_type_6 = "";
        if ($('#fatomic').prop("checked") == true) type_d_auto = 1;
        if ($('#fpdr').prop("checked") == true) type_d_pdr = 1;
        if ($('#fsNPDR').prop("checked") == true) type_d_npdr = 1;
        if ($('#ftdtype1').prop("checked") == true) diab_type_1 = 1;
        if ($('#ftdtype2').prop("checked") == true) diab_type_2 = 1;
        if ($('#ftdgdm').prop("checked") == true) diab_type_3 = 1;
        if ($('#ftdmody').prop("checked") == true) diab_type_4 = 1;
        if ($('#ftdtype').prop("checked") == true) diab_type_5 = 1;
        if ($('#ftdtypenone').prop("checked") == true) diab_type_6 = 1;
        if ($('#YearsOFdia').val().length > 0 || type_d_auto == 1 || type_d_pdr == 1 || type_d_npdr == 1 || diab_type_1 == 1 || diab_type_2 == 1 || diab_type_3 == 1 || diab_type_4 == 1 || diab_type_5 == 1 || diab_type_6 == 1) {
            var dia_year_start = $('#YearsOFdia').val();
            if (dia_year_start != '') {
                PCondition = PCondition + " and (plf.diabetes_of_year = " + dia_year_start + ")";
            }
            if (type_d_auto != "" && type_d_pdr != "" && type_d_npdr != "") {
                PCondition = PCondition + ' and (plf.autonomic_neuropathy != cast(0 as nvarchar) or plf.pdr != cast(0 as nvarchar) or plf.npdr != cast(0 as nvarchar))';
            }
            else if (type_d_auto != "" && type_d_pdr != "") {
                PCondition = PCondition + ' and (plf.autonomic_neuropathy != cast(0 as nvarchar) or plf.pdr != cast(0 as nvarchar))';
            }
            else if (type_d_auto != "" && type_d_npdr != "") {
                PCondition = PCondition + ' and (plf.autonomic_neuropathy != cast(0 as nvarchar) or plf.npdr != cast(0 as nvarchar))';
            }
            else if (type_d_pdr != "" && type_d_npdr != "") {
                PCondition = PCondition + ' and (plf.pdr != cast(0 as nvarchar) or plf.npdr != cast(0 as nvarchar))';
            }
            else if (type_d_auto != "") {
                PCondition = PCondition + ' and (plf.autonomic_neuropathy != cast(0 as nvarchar))';
            }
            else if (type_d_pdr != "") {
                PCondition = PCondition + ' and (plf.pdr != cast(0 as nvarchar))';
            }
            else if (type_d_npdr != "") {
                PCondition = PCondition + ' and (plf.npdr != cast(0 as nvarchar))';
            }
            else {
            }

            if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_3 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_2 != "" && diab_type_1 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes =  cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_1 != "" && diab_type_2 != "" && diab_type_3 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_3 != "" && diab_type_4 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar))';
            }
            else if (diab_type_3 != "" && diab_type_4 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_4 != "" && diab_type_5 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_1 != "" && diab_type_2 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(2 as nvarchar))';
            }
            else if (diab_type_1 != "" && diab_type_3 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(3 as nvarchar))';
            }
            else if (diab_type_1 != "" && diab_type_4 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar))';
            }
            else if (diab_type_1 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_1 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(1 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_2 != "" && diab_type_3 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 asn varchar) or plf.type_of_diabetes = cast(3 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_4 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_2 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(2 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_3 != "" && diab_type_4 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(4 as nvarchar))';
            }
            else if (diab_type_3 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_3 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(3 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_4 != "" && diab_type_5 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(5 as nvarchar))';
            }
            else if (diab_type_4 != "" && diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(4 as nvarchar) or plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else if (diab_type_1 != "") {
                PCondition = PCondition + ' and plf.type_of_diabetes = cast(1 as nvarchar)';
            }
            else if (diab_type_2 != "") {
                PCondition = PCondition + ' and plf.type_of_diabetes = cast(2 as nvarchar)';
            }
            else if (diab_type_3 != "") {
                PCondition = PCondition + ' and plf.type_of_diabetes = cast(3 as nvarchar)';
            }
            else if (diab_type_4 != "") {
                PCondition = PCondition + ' and plf.type_of_diabetes = cast(4 as nvarchar)';
            }
            else if (diab_type_5 != "") {
                PCondition = PCondition + ' and plf.type_of_diabetes = cast(5 as nvarchar)';
            }
            else if (diab_type_6 != "") {
                PCondition = PCondition + ' and (plf.type_of_diabetes = cast(6 as nvarchar) or plf.type_of_diabetes = NULL)';
            }
            else { }
        }
        else {
            toastr.warning("Enter any one of the field");
        }
    }
    else { }

    //var last = 'group by PA.Patient_id order by PA.Patient_id asc';
    var last = ' order by PA.Patient_id asc';
    PCondition = PCondition + last;

    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: PCondition,
        Dml_Indicator: 'filter',
        user_role: $('#hiddenRole_id').val(),
        branch_id: $("#SelBranchFilter").val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#tblPatientSearch').empty();
                $('#patientsearchtablebody').empty();
                $('#tblPatientSearch').html('<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>');
                $('.pagination').hide();
                //$('#appDate').val('');
                //$('#nextDate').val('');
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var j = 0;
                    var PatientSearch = '';
                    $('.pagination').hide();
                    $.each(data1, function (i, emp) {
                        var Pname = '', gender = '', dob = '', age = '', ages = '', bloodgroup = '', typediabetics = '', yeardiabetics = '', lastvisit = '', nextvisit = '', Phoneno = '',
                            coupon_id = '', visit_type_status = '', PtImage='';
                        var doctor_name = '';
                        var image = emp.photo
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        Pname = emp.first_name;
                        gender = emp.gender;

                        dob = emp.DOB;

                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;
                        lastvisit = emp.last_visit;
                        nextvisit = emp.next_visit;
                        Phoneno = emp.phone_number_1;
                        coupon_id = emp.coupon_id;
                        visit_type_status = emp.visit_type_status;

                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }
                        debugger;
                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }


                        if (nextvisit == '' || nextvisit == null) {
                            nextvisit = '-';
                        }
                        if (lastvisit == '' || lastvisit == null) {
                            lastvisit = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }

                        j++;
                        var doctor_patient_id = '-';
                        if (emp.doctor_patient_id != '' && emp.doctor_patient_id != null) {
                            doctor_patient_id = emp.doctor_patient_id;
                        }

                        var address_details = '-';

                        if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village;
                        else if (emp.town_village != null) address_details = emp.town_village;

                        var ipredirect = '', iptransfer = '', billingredirect = '', registerbranch = ''; primary_doctor = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';
                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;

                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><i class="fa fa-plus mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '">IP Admission</a></p>';
                            }
                            var createbill = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.branch_id + '">Create Bill</a></p>'
                        }
                        else {
                            if (visit_type_status == 1) {
                                ip_current_status = '<span class="label label-success">Admitted</span>';
                            }
                            else {
                                ip_current_status = ''
                            }
                            var iptransfer = '<p><i class="fa fa-bed mr-5" aria-hidden="true"></i><a style="cursor:pointer;color: black;" class="btn_r" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '">IP Transfer</a></p>';
                            var billingredirect = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer;color:black;" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '">View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            var Patienthistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Patient History</a></p>';
                            var InvestigationsHistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Investigations History</a></p>';
                        }
                        var couponid = '', packagecoupondetails = ''
                        if (coupon_id != null) {
                            couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
                            packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '")>Packag / Coupon Details</a></p>'
                        }
                        else {
                            couponid = ''
                            packagecoupondetails = ''
                        }

                        // patient history & Investigation history & package / coupon details



                        var printcard = '<p><a style="cursor:pointer"  data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);><i class="fa fa-print mr-5"  aria-hidden="true"></i>Print ID Card</a></p>';

                        //if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit" title="edit" data data-original-title="Edit"  href="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu  info-dropdown" id="ushelpMenu"><div class="text-left">'
                        //    + '<p href="#myPatientSearchModal" class="f14 UM_10 btn_r" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p href="#myPatientSearchModal" class="f14 UM_9 btn_r" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'

                        //     + ipredirect

                        //    + Patienthistory
                        //    + InvestigationsHistory
                        //    + packagecoupondetails
                        //    + iptransfer
                        //    + billingredirect
                        //     + printcard
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p><i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + doctor_name + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '" class="btn btn-block btn-flat btn-info btn-sm UM_8">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '") class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7">Book Now</a></div></div></div></div>';

                        //}
                        //else {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit" title="edit" data data-original-title="Edit" href="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu  info-dropdown" id="ushelpMenu"><div class="text-left">'
                        //    + '<p href="#myPatientSearchModal" hidden class="f14 UM_10 btn_r" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p href="#myPatientSearchModal" hidden class="f14 UM_9 btn_r" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'

                        //     + ipredirect
                        //    + Patienthistory
                        //    + InvestigationsHistory
                        //    + packagecoupondetails
                        //    + iptransfer
                        //    + billingredirect
                        //     + printcard
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + doctor_name + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '" class="btn btn-block btn-flat btn-info btn-sm UM_8">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '") class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7">Book Now</a></div></div></div></div>';

                        //}
                        debugger;
                        var watchviplist = ''
                        //if ($('#hiddenRole_id').val() != 2) {
                        watchviplist = watchviplist + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                            + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //}

                        if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                            PatientSearch = PatientSearch + '<div class=" col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'
                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                //+'<span class="sr-only">edit</span>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer
                                //patient history & Investigation history & package / coupon details
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                + printcard
                                + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                                + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                                + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar" > </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                // + '<p><span class="pat-heading">Doctor :  span> ' + primary_doctor + ' </p> </div>'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }
                        //{
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit btn_r" style="cursor:pointer" title="edit" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu support-menu" id="ushelpMenu"><div class="text-left">'
                        //    + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //   + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //     + ipredirect
                        //    + iptransfer
                        //    + billingredirect
                        //    + printcard
                        //    + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                        //+ '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                        //   + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //   + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + primary_doctor + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a  class="btn btn-block btn-flat btn-info btn-sm UM_8 btn_r" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '>Book Now</a></div></div></div></div>';
                        //}
                        //else {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit btn_r" title="edit" data data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu support-menu" id="ushelpMenu"><div class="text-left">'
                        //    + '<p  hidden class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p  hidden class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //    + ipredirect
                        //    + iptransfer
                        //    + billingredirect
                        //    + printcard
                        //    //+ '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                        //    //+ '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div> <div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + primary_doctor + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div> <div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a class="btn btn-block btn-flat btn-info btn-sm btn_r" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '>Book Now</a></div></div></div></div>';
                        //}
                        else {
                            PatientSearch = PatientSearch + '<div class="col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'
                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                //+'<span class="sr-only">edit</span>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer

                                //patient history & Investigation history & package / coupon details 
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                + printcard
                                //  + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                // + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                                + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                                + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar"> </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                //+ '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p> </div>'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }

                    });


                    var row_data = '';

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

                        var gender = '', dob = '', age = '', ages = '', bloodgroup = '', Phoneno = '', registerbranch = ''; primary_doctor = ''; ip_current_status = '', icon_details = '',PtImage='';
                        var doctor_name = '';
                        var last_name = ''
                        var sec_mobile_no = ''
                        var image = emp.photo
                        console.log(image);
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        console.log(PatientPhoto)
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        gender = emp.gender;
                        dob = emp.DOB;
                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;

                        last_name = emp.last_name;
                        //
                        Phoneno = emp.phone_number_1;
                        //
                        sec_mobile_no = emp.second_phone_number;

                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;
                        visit_type_status = emp.visit_type_status;

                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }
                        debugger;
                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }
                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (last_name == '' || last_name == null) {
                            last_name = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }
                        if (sec_mobile_no == '' || sec_mobile_no == null) {
                            sec_mobile_no = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }


                        if (emp.vip_description != null && emp.vip_status == "1")
                            icon_details = icon_details + '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>';

                        var watchlist_end_date = new Date(emp.watchlist_end_date);
                        var currentdate = new Date();

                        if (watchlist_end_date >= currentdate && emp.watchlist_status == "1")
                            icon_details = icon_details + '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:20px;" title="Watch List"></i>';

                        if (emp.is_app_installed == 1) {
                            icon_details = icon_details + '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="Patient App Installed"></i>'
                        }

                        var bookoption = '';
                        var bookoptionclass = '';
                        if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                            bookoption = 'disabled';
                            bookoptionclass = 'style="pointer-events: none;"';
                        }

                        var book_later = '<a class="btn btn-info btn-xs UM_8 btn_r" title="Book_Later" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar-plus-o" aria-hidden="true"></i></a>'

                        var book_now = '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-edit btn-xs UM_7" title="Book_Now"  class="btn btn-block btn-flat btn-edit btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '><i class="fa fa-calendar-check-o" aria-hidden="true"></i></a>'

                        var editpatient = '<p><i class="fa fa-edit mr-5"></i><a style="cursor:pointer"  class="btn_r" data-id="UM_6" data-type="role_rights_edit" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '" data-nav="redirect" >Patient Edit</a></p>';

                        var watchviplist = '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';>Vip List</a></p>'
                            + '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';>Watch List</a></p>'

                        var ipredirect = '', iptransfer = '', billingredirect = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><i class="fa fa-plus mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '">IP Admission</a></p>';
                            }
                            var createbill = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.branch_id + '">Create Bill</a></p>'
                        }
                        else {
                            ip_current_status = '<span class="label label-success">Admitted</span>';
                            var iptransfer = '<p><i class="fa fa-bed mr-5" aria-hidden="true"></i><a style="cursor:pointer" class="btn_r" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '">IP Transfer</a></p>';
                            var billingredirect = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '">View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            var Patienthistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Patient History</a></p>';
                            var InvestigationsHistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Investigations History</a></p>';
                        }
                        // patient history & Investigation history & package / coupon details

                        var packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '")>Packag / Coupon Details</a></p>'

                        var printcard = '<p><i class="fa fa-print mr-5"  aria-hidden="true"></i><a style="cursor:pointer"  data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);>Print ID Card</a></p>';

                        var trB = '<div class="col-md-12 padding0"><div class="disp_if">' + book_later + book_now + ' <a href="#" class="dropdown-toggle pull-left btn-info-dots" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu support-menu-btns" id=""> <div class="text-left">' + createbill + editpatient + billingredirect + ipredirect + iptransfer + Patienthistory + InvestigationsHistory + packagecoupondetails + watchviplist + printcard + '</div></div></div></div>';

                        //row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + Phoneno + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        if (visit_type_status == 1) {
                            $('#c_ip_status').removeClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        else {
                            $('#c_ip_status').addClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td class='hidden'>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        //row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                    });

                    $('#patientsearchtablebody').empty();
                    $('#patientsearchtable').dataTable().fnClearTable();
                    $('#patientsearchtable').dataTable().fnDestroy();
                    debugger;
                    $('#patientsearchtablebody').append(row_data);
                    //datatable('patientsearchtable', 'Patient List', 'A4');


                    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();

                    var downloadfilename = "PatientList" + output;

                    //$('#patientsearchtable').DataTable({


                    //    "fnInitComplete": function () {
                    //        // Disable TBODY scoll bars
                    //        $('.dataTables_scrollBody').css({
                    //            'overflow': 'hidden',
                    //            'border': '0'
                    //        });

                    //        // Enable TFOOT scoll bars
                    //        $('.dataTables_scrollFoot').css('overflow', 'auto');

                    //        $('.dataTables_scrollHead').css('overflow', 'auto');

                    //        // Sync TFOOT scrolling with TBODY
                    //        $('.dataTables_scrollFoot').on('scroll', function () {
                    //            $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                    //        });

                    //        $('.dataTables_scrollHead').on('scroll', function () {
                    //            $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                    //        });
                    //    },
                    //    dom: "lBfrtip",
                    //    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    //    buttons: [
                    //    {
                    //        extend: 'copyHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'excelHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'csvHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'pdfHtml5', footer: true, title: 'PatientList', footer: true,
                    //        stripHtml: false,
                    //        decodeEntities: true,
                    //        orientation: 'landscape',
                    //        filename: downloadfilename,
                    //        pageSize: 'LEGAL',
                    //        paging: true,
                    //        exportOptions: {

                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                    //            sumGrouping: true
                    //        }

                    //    }
                    //    ]


                    //});

                    if (PatientSearch != '') {
                        $('#tblPatientSearch').html(PatientSearch);
                        check_priviliges();
                    }
                    datatable('patientsearchtable', 'Patient List', 'A4');
                }
                else {
                    console.log(data);
                }

            }
            $('.da-load-patsearch').addClass('hide');
        }
    });
}

function Diabetes_filter() {
    debugger;

    var PCondition = '';
    var nextappointment = '', filter_visit = '';
    var appDate = '';
    var diab_year = '', type_d_auto = "", type_d_pdr = "", type_d_npdr = "", diab_type_1 = "", diab_type_2 = "", diab_type_3 = "", diab_type_4 = "", diab_type_5 = "", diab_type_6 = "";

    if ($('#tab_val').val() == "2") {
        debugger;
        if ($('#filter_visit').val() == '' || $('#filter_visit').val() == null) {
            $('#Pfilter_visit').show();
            $('#Pfilter_visit').fadeOut(8000);
            $('#Pfilter_visit').html('Select Type');
            $('#filter_visit').focus();
            $('#filter_visit').val('');
            return false;
        }
        if ($('#nextDate').val() == '' || $('#nexttoDate').val() == '') {
            if ($('#nextDate').val() == '') {
                $('#PnextDate').show();
                $('#PnextDate').fadeOut(8000);
                $('#PnextDate').html('Select From Date');
                //$('#nextDate').focus();
                $('#nextDate').val('');
                return false;
            }
            if ($('#nexttoDate').val() == '') {
                $('#PnexttoDate').show();
                $('#PnexttoDate').fadeOut(8000);
                $('#PnexttoDate').html('Select To Date');
                //$('#nexttoDate').focus();
                $('#nexttoDate').val('');
                return false;
            }


        }
        else {
            nextappointment = $('#nextDate').val();
            appDate = $('#nexttoDate').val();
            nextappointment = nextappointment.split('/');
            nextappointment = nextappointment[2] + '-' + nextappointment[1] + '-' + nextappointment[0];
            appDate = appDate.split('/');
            appDate = appDate[2] + '-' + appDate[1] + '-' + appDate[0];
            filter_visit = $('#filter_visit').val();
            //if ($('#filter_visit').val() == 1) {
            //    PCondition = PCondition + " and (CONVERT(date,(vs.next_appointment_date)) between '" + nextappointment + "' and '" + appDate + "')";
            //}
            //else if ($('#filter_visit').val() == 2) {
            //    PCondition = PCondition + " and (CONVERT(date,(vs.created_on)) between '" + nextappointment + "' and '" + appDate + "')";
            //}
            //else {
            //    $('#Pfilter_visit').show();
            //    $('#Pfilter_visit').fadeOut(8000);
            //    $('#Pfilter_visit').html('Select Type');
            //    $('#filter_visit').focus();
            //    $('#filter_visit').val('');
            //    return false;
            //}
        }


    }
    else if ($('#tab_val').val() == "3") {
        diab_year = $("#YearsOFdia").val();
        if ($('#fatomic').prop("checked") == true) type_d_auto = 1;
        if ($('#fpdr').prop("checked") == true) type_d_pdr = 1;
        if ($('#fsNPDR').prop("checked") == true) type_d_npdr = 1;
        if ($('#ftdtype1').prop("checked") == true) diab_type_1 = 1;
        if ($('#ftdtype2').prop("checked") == true) diab_type_2 = 1;
        if ($('#ftdgdm').prop("checked") == true) diab_type_3 = 1;
        if ($('#ftdmody').prop("checked") == true) diab_type_4 = 1;
        if ($('#ftdtype').prop("checked") == true) diab_type_5 = 1;
        if ($('#ftdtypenone').prop("checked") == true) diab_type_6 = 1;
        //if ($('#YearsOFdia').val().length > 0 || type_d_auto == 1 || type_d_pdr == 1 || type_d_npdr == 1 || diab_type_1 == 1 || diab_type_2 == 1 || diab_type_3 == 1 || diab_type_4 == 1 || diab_type_5 == 1 || diab_type_6 == 1) {

        //}
        //else {
        //    toastr.warning("Enter any one of the field");
        //}
    }




    var last = ' order by PA.Patient_id asc';
    PCondition = PCondition + last;

    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: filter_visit,
        Dml_Indicator: 'Diafilter',
        user_role: $('#hiddenRole_id').val(),
        branch_id: $("#SelBranchFilter").val(),
        Diabetes_Years: diab_year,
        AutonomicNeuropathy: type_d_auto,
        PDR: type_d_pdr,
        NPDR: type_d_npdr,
        Diabetes_Type1: diab_type_1,
        Diabetes_Type2: diab_type_2,
        MODY: diab_type_4,
        LADA: diab_type_5,
        GDM: diab_type_3,
        Diabetes_None: diab_type_6,
        from_date: nextappointment,
        to_date: appDate
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#tblPatientSearch').empty();
                $('#patientsearchtablebody').empty();
                $('#tblPatientSearch').html('<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>');
                $('.pagination').hide();
                //$('#appDate').val('');
                //$('#nextDate').val('');
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var j = 0;
                    var PatientSearch = '';
                    $('.pagination').hide();
                    $.each(data1, function (i, emp) {
                        var Pname = '', gender = '', dob = '', age = '', ages = '', bloodgroup = '', typediabetics = '', yeardiabetics = '', lastvisit = '', nextvisit = '', Phoneno = '',
                            coupon_id = '', visit_type_status = '', PtImage='';
                        var doctor_name = '';
                        var image = emp.photo
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        Pname = emp.first_name;
                        gender = emp.gender;

                        dob = emp.DOB;

                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;
                        lastvisit = emp.last_visit;
                        nextvisit = emp.next_visit;
                        Phoneno = emp.phone_number_1;
                        coupon_id = emp.coupon_id;
                        visit_type_status = emp.visit_type_status;

                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }
                        debugger;
                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }


                        if (nextvisit == '' || nextvisit == null) {
                            nextvisit = '-';
                        }
                        if (lastvisit == '' || lastvisit == null) {
                            lastvisit = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }

                        j++;
                        var doctor_patient_id = '-';
                        if (emp.doctor_patient_id != '' && emp.doctor_patient_id != null) {
                            doctor_patient_id = emp.doctor_patient_id;
                        }

                        var address_details = '-';

                        if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.town_village + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "-" + emp.pincode;
                        else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village;
                        else if (emp.town_village != null) address_details = emp.town_village;

                        var ipredirect = '', iptransfer = '', billingredirect = '', registerbranch = ''; primary_doctor = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';
                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;

                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><i class="fa fa-plus mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '">IP Admission</a></p>';
                            }
                            var createbill = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.branch_id + '">Create Bill</a></p>'
                        }
                        else {
                            if (visit_type_status == 1) {
                                ip_current_status = '<span class="label label-success">Admitted</span>';
                            }
                            else {
                                ip_current_status = ''
                            }
                            var iptransfer = '<p><i class="fa fa-bed mr-5" aria-hidden="true"></i><a style="cursor:pointer;color: black;" class="btn_r" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '">IP Transfer</a></p>';
                            var billingredirect = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer;color:black;" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '">View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            var Patienthistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Patient History</a></p>';
                            var InvestigationsHistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Investigations History</a></p>';
                        }
                        var couponid = '', packagecoupondetails = ''
                        if (coupon_id != null) {
                            couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
                            packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '")>Packag / Coupon Details</a></p>'
                        }
                        else {
                            couponid = ''
                            packagecoupondetails = ''
                        }

                        // patient history & Investigation history & package / coupon details



                        var printcard = '<p><a style="cursor:pointer"  data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);><i class="fa fa-print mr-5"  aria-hidden="true"></i>Print ID Card</a></p>';

                        //if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit" title="edit" data data-original-title="Edit"  href="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu  info-dropdown" id="ushelpMenu"><div class="text-left">'
                        //    + '<p href="#myPatientSearchModal" class="f14 UM_10 btn_r" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p href="#myPatientSearchModal" class="f14 UM_9 btn_r" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'

                        //     + ipredirect

                        //    + Patienthistory
                        //    + InvestigationsHistory
                        //    + packagecoupondetails
                        //    + iptransfer
                        //    + billingredirect
                        //     + printcard
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p><i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + doctor_name + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '" class="btn btn-block btn-flat btn-info btn-sm UM_8">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '") class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7">Book Now</a></div></div></div></div>';

                        //}
                        //else {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit" title="edit" data data-original-title="Edit" href="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu  info-dropdown" id="ushelpMenu"><div class="text-left">'
                        //    + '<p href="#myPatientSearchModal" hidden class="f14 UM_10 btn_r" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p href="#myPatientSearchModal" hidden class="f14 UM_9 btn_r" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'

                        //     + ipredirect
                        //    + Patienthistory
                        //    + InvestigationsHistory
                        //    + packagecoupondetails
                        //    + iptransfer
                        //    + billingredirect
                        //     + printcard
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + doctor_name + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a href="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '" class="btn btn-block btn-flat btn-info btn-sm UM_8">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '") class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7">Book Now</a></div></div></div></div>';

                        //}

                        if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                            PatientSearch = PatientSearch + '<div class=" col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'
                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                //+'<span class="sr-only">edit</span>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer
                                //patient history & Investigation history & package / coupon details
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                + printcard
                                + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                                + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                                + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar"> </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                // + '<p><span class="pat-heading">Doctor :  span> ' + primary_doctor + ' </p> </div>'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }
                        //{
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit btn_r" style="cursor:pointer" title="edit" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu support-menu" id="ushelpMenu"><div class="text-left">'
                        //    + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //   + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //     + ipredirect
                        //    + iptransfer
                        //    + billingredirect
                        //    + printcard
                        //    + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                        //+ '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                        //   + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //   + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div><div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + primary_doctor + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div><div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a  class="btn btn-block btn-flat btn-info btn-sm UM_8 btn_r" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '>Book Now</a></div></div></div></div>';
                        //}
                        //else {
                        //    PatientSearch = PatientSearch + '<div class="col-lg-4 col-md-4 col-sm-6 col-xs-12 padding0"><div class="box box-without-mar box-widget widget-user-2"><div class="widget-user-header bg-default"><div class="row"><div class="col-sm-3 col-xs-3"><div class="widget-user-image"> <img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></div>'
                        //    + '<div class="col-sm-7 col-xs-7"> <h6>' + emp.patient_id + ' | ' + doctor_patient_id + '</h6><h5><a href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '"><span class="f16 sname" title="' + Pname + '">' + Pname + '</span></a></h5><h6>' + ages + ' | ' + gender + '</h6><h6><i class="fa fa-phone" aria-hidden="true">&nbsp;</i>+91 ' + Phoneno + ' | <span><i class="fa fa-tint" style="color:#EF5261;" aria-hidden="true">&nbsp;</i>' + bloodgroup + '</span></h6></div>'
                        //    + '<div class="col-sm-2 col-xs-2"><ul style="display:inline-flex" class="pull-right"><li style="list-style-type:none;margin-right:20px;"><a class="fa fa-edit btn_r" title="edit" data data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a></li><li class="dropdown" style="list-style-type:none;"><a href="#" class="dropdown-toggle pull-left" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data data-original-title="Options" style="color:black;"></span></a><div class="dropdown-menu support-menu" id="ushelpMenu"><div class="text-left">'
                        //    + '<p  hidden class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                        //    + '<p  hidden class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                        //    + ipredirect
                        //    + iptransfer
                        //    + billingredirect
                        //    + printcard
                        //    //+ '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                        //    //+ '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                        //    + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                        //    + '<div class="row"><div class="col-xs-12 address"><p> <i class="fa fa-address-card" aria-hidden="true">&nbsp;&nbsp;</i>' + address_details + '</p></div> <div class="col-xs-4"><p class="f11"> <i class="fa fa-user-md" aria-hidden="true">&nbsp;&nbsp;</i> ' + primary_doctor + ' </p></div><div class="col-xs-4"><p class="f11 text-center"> <i class="fa fa-flag" aria-hidden="true">&nbsp;&nbsp;</i> ' + ip_current_status + ' </p></div><div class="col-xs-4"><p class="pull-right f11"> <i class="fa fa-location-arrow" aria-hidden="true">&nbsp;&nbsp;</i> ' + registerbranch + ' </p></div> <div class="col-xs-12"><div class="lastvisit"><p>Last Visit : ' + lastvisit + ' </p></div><div class="nextvisit pull-right"><p>Next Visit : ' + nextvisit + ' </p></div></div></div></div><div class="row"><div class="col-md-6 pr-0"><a class="btn btn-block btn-flat btn-info btn-sm btn_r" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + Pname + '">Book later</a></div><div class="col-md-6 pl-0"><a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-block btn-flat btn-primaryuse btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '>Book Now</a></div></div></div></div>';
                        //}
                        else {
                            PatientSearch = PatientSearch + '<div class="col-md-3 col-sm-4 col-xs-6 pat-card mb-20">'
                                + '<div class="pat-box">'
                                + '<div class="row">'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6">'
                                + '<ul style="display:inline-flex" class="pull-right mr-5">'
                                + '<li class="" style="list-style-type:none;">'
                                + couponid
                                + '</li>'
                                + '<li class="mr-10" style="list-style-type:none;">'
                                + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                                //+'<span class="sr-only">edit</span>'
                                + '</li>'
                                + '<li class="dropdown" style="list-style-type:none;">'
                                + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                                + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                                + '<div class="text-left">'
                                + createbill
                                + billingredirect
                                + iptransfer

                                //patient history & Investigation history & package / coupon details 
                                + Patienthistory
                                + InvestigationsHistory
                                + packagecoupondetails
                                + ipredirect
                                + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                                + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                                + printcard
                                //  + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                                // + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                                + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 patient-name">'
                                + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                                + '<div class="col-sm-8 col-xs-8 pr-0">'
                                + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                                + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                                + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                                + '<p class="pbranch"><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                                + '<div class="col-sm-4 col-xs-3 patient-img">'
                                + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar"> </div> </div>'
                                + '<div class="row">'
                                + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                                //+ '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p> </div>'
                                + doctor_name + '</div>'
                                + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                                + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                                + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                                + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                                + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                                + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                        }

                    });


                    var row_data = '';

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

                        var gender = '', dob = '', age = '', ages = '', bloodgroup = '', Phoneno = '', registerbranch = ''; primary_doctor = ''; ip_current_status = '', icon_details = '', PtImage='';
                        var doctor_name = '';
                        var last_name = ''
                        var sec_mobile_no = ''
                        var image = emp.photo
                        console.log(image);
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        console.log(PatientPhoto)
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        gender = emp.gender;
                        dob = emp.DOB;
                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;

                        last_name = emp.last_name;
                        //
                        Phoneno = emp.phone_number_1;
                        //
                        sec_mobile_no = emp.second_phone_number;

                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;
                        visit_type_status = emp.visit_type_status;

                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }
                        debugger;
                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }
                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (last_name == '' || last_name == null) {
                            last_name = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }
                        if (sec_mobile_no == '' || sec_mobile_no == null) {
                            sec_mobile_no = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }


                        if (emp.vip_description != null && emp.vip_status == "1")
                            icon_details = icon_details + '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>';

                        var watchlist_end_date = new Date(emp.watchlist_end_date);
                        var currentdate = new Date();

                        if (watchlist_end_date >= currentdate && emp.watchlist_status == "1")
                            icon_details = icon_details + '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:20px;" title="Watch List"></i>';

                        if (emp.is_app_installed == 1) {
                            icon_details = icon_details + '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="Patient App Installed"></i>'
                        }

                        var bookoption = '';
                        var bookoptionclass = '';
                        if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                            bookoption = 'disabled';
                            bookoptionclass = 'style="pointer-events: none;"';
                        }

                        var book_later = '<a class="btn btn-info btn-xs UM_8 btn_r" title="Book_Later" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar-plus-o" aria-hidden="true"></i></a>'

                        var book_now = '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-edit btn-xs UM_7" title="Book_Now"  class="btn btn-block btn-flat btn-edit btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '><i class="fa fa-calendar-check-o" aria-hidden="true"></i></a>'

                        var editpatient = '<p><i class="fa fa-edit mr-5"></i><a style="cursor:pointer"  class="btn_r" data-id="UM_6" data-type="role_rights_edit" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '" data-nav="redirect" >Patient Edit</a></p>';

                        var watchviplist = ''
                        //if ($('#hiddenRole_id').val() != 2) {
                        var watchviplist = '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';>Vip List</a></p>'
                            + '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';>Watch List</a></p>'
                        //}
                        //var watchviplist = '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';>Vip List</a></p>'
                        //    + '<p><i class="fa fa-plus mr-5"></i><a style="cursor:pointer" class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';>Watch List</a></p>'

                        var ipredirect = '', iptransfer = '', billingredirect = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><i class="fa fa-plus mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '">IP Admission</a></p>';
                            }
                            var createbill = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.branch_id + '">Create Bill</a></p>'
                        }
                        else {
                            ip_current_status = '<span class="label label-success">Admitted</span>';
                            var iptransfer = '<p><i class="fa fa-bed mr-5" aria-hidden="true"></i><a style="cursor:pointer" class="btn_r" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '">IP Transfer</a></p>';
                            var billingredirect = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '">View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            var Patienthistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Patient History</a></p>';
                            var InvestigationsHistory = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '">Investigations History</a></p>';
                        }
                        // patient history & Investigation history & package / coupon details

                        var packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '")>Packag / Coupon Details</a></p>'

                        var printcard = '<p><i class="fa fa-print mr-5"  aria-hidden="true"></i><a style="cursor:pointer"  data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);>Print ID Card</a></p>';

                        var trB = '<div class="col-md-12 padding0"><div class="disp_if">' + book_later + book_now + ' <a href="#" class="dropdown-toggle pull-left btn-info-dots" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu support-menu-btns" id=""> <div class="text-left">' + createbill + editpatient + billingredirect + ipredirect + iptransfer + Patienthistory + InvestigationsHistory + packagecoupondetails + watchviplist + printcard + '</div></div></div></div>';

                        //row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + Phoneno + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        if (visit_type_status == 1) {
                            $('#c_ip_status').removeClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        else {
                            $('#c_ip_status').addClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td class='hidden'>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        //row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                    });

                    $('#patientsearchtablebody').empty();
                    $('#patientsearchtable').dataTable().fnClearTable();
                    $('#patientsearchtable').dataTable().fnDestroy();
                    debugger;
                    $('#patientsearchtablebody').append(row_data);
                    //datatable('patientsearchtable', 'Patient List', 'A4');


                    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();

                    var downloadfilename = "PatientList" + output;

                    //$('#patientsearchtable').DataTable({


                    //    "fnInitComplete": function () {
                    //        // Disable TBODY scoll bars
                    //        $('.dataTables_scrollBody').css({
                    //            'overflow': 'hidden',
                    //            'border': '0'
                    //        });

                    //        // Enable TFOOT scoll bars
                    //        $('.dataTables_scrollFoot').css('overflow', 'auto');

                    //        $('.dataTables_scrollHead').css('overflow', 'auto');

                    //        // Sync TFOOT scrolling with TBODY
                    //        $('.dataTables_scrollFoot').on('scroll', function () {
                    //            $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                    //        });

                    //        $('.dataTables_scrollHead').on('scroll', function () {
                    //            $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                    //        });
                    //    },
                    //    dom: "lBfrtip",
                    //    "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                    //    buttons: [
                    //    {
                    //        extend: 'copyHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'excelHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'csvHtml5', footer: true, filename: downloadfilename, title: 'PatientList', exportOptions: {
                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
                    //        }
                    //    },
                    //    {
                    //        extend: 'pdfHtml5', footer: true, title: 'PatientList', footer: true,
                    //        stripHtml: false,
                    //        decodeEntities: true,
                    //        orientation: 'landscape',
                    //        filename: downloadfilename,
                    //        pageSize: 'LEGAL',
                    //        paging: true,
                    //        exportOptions: {

                    //            columns: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
                    //            sumGrouping: true
                    //        }

                    //    }
                    //    ]


                    //});

                    if (PatientSearch != '') {
                        $('#tblPatientSearch').html(PatientSearch);
                        check_priviliges();
                    }
                    datatable('patientsearchtable', 'Patient List', 'A4');
                }
                else {
                    console.log(data);
                }

            }
            $('.da-load-patsearch').addClass('hide');
        }
    });
}




function prevPagination() {
    if ($('#pagePrev').attr('class') == 'disabled') {
        return
    } else {
        var prevJump = $('.prev').attr('id');
        var nextJump = $('.next').attr('id');
        $('.pagination').empty();
        var id = parseInt(prevJump);
        if (id > 10) {
            id = parseInt(prevJump) - 10;
            nextJump = parseInt(nextJump) - 10;
            var firstli = $("<li>", { id: "pageFirst", "class": "" });
            var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
            firsta.html("First")
            firstli.append(firsta);
            $('.pagination').append(firstli);
            var prevli = $("<li>", { id: "pagePrev", "class": "" });
            var preva = $("<a>", { id: id, "class": "prev", "onclick": "prevPagination()" });
            var nextli = $("<li>", { id: "pageNext", "class": "" });
            var nexta = $("<a>", { id: nextJump, "class": "next", "onclick": "nextPagination()" });
            preva.html("<<");
            prevli.append(preva);
            $('.pagination').append(prevli);
            for (var i = prevJump; i <= parseInt(prevJump) + 9; i++) {
                if (i == jsonLength) {
                    break;
                }
                if (i == prevJump) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
            nexta.html(">>");
            nextli.append(nexta);
            $('.pagination').append(nextli);
            var lastli = $("<li>", { id: "pageLast", "class": "" });
            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
            lasta.html("Last")
            lastli.append(lasta);
            $('.pagination').append(lastli);
        } else {
            nextJump = parseInt(nextJump) - 10;
            var firstli = $("<li>", { id: "pageFirst", "class": "disabled" });
            var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
            firsta.html("First")
            firstli.append(firsta);
            $('.pagination').append(firstli);
            var prevli = $("<li>", { id: "pagePrev", "class": "disabled" });
            var preva = $("<a>", { id: '0', "class": "prev", "onclick": "prevPagination()" });
            var nextli = $("<li>", { id: "pageNext", "class": "" });
            var nexta = $("<a>", { id: nextJump, "class": "next", "onclick": "nextPagination()" });
            preva.html("<<");
            prevli.append(preva);
            $('.pagination').append(prevli);
            for (var i = prevJump; i <= parseInt(prevJump) + 9; i++) {
                if (i == jsonLength) {
                    break;
                }
                if (i == prevJump) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
            nexta.html(">>");
            nextli.append(nexta);
            $('.pagination').append(nextli);
            var lastli = $("<li>", { id: "pageLast", "class": "" });
            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
            lasta.html("Last")
            lastli.append(lasta);
            $('.pagination').append(lastli);
        }
    }

}

function nextPagination() {
    if ($('#pageNext').attr('class') == 'disabled') {
        return
    } else {
        var nextJump = $('.next').prop('id');
        var prevJump = $('.prev').attr('id');
        $('.pagination').empty();

        var id = parseInt(nextJump) + 10;

        if (id < (Math.floor(jsonLength / 10) * 10)) {
            if (prevJump == 0) {
                prevJump = 1;
            } else {
                prevJump = parseInt(prevJump) + 10;
            }
            var firstli = $("<li>", { id: "pageFirst", "class": "" });
            var firsta = $("<a>", { id: '', "class": "first", "onclick": "firstPagination()" });
            var prevli = $("<li>", { id: "pagePrev", "class": "", "onclick": "prevPagination()" });
            var preva = $("<a>", { id: prevJump, "class": "prev" });
            var nextli = $("<li>", { id: "pageNext", "class": "" });
            var nexta = $("<a>", { id: id, "class": "next", "onclick": "nextPagination()" });
            firsta.html("First");
            firstli.append(firsta)
            $('.pagination').append(firstli);
            preva.html("<<");
            prevli.append(preva);
            $('.pagination').append(prevli);
            for (var i = parseInt(nextJump) + 1; i <= parseInt(nextJump) + 10; i++) {
                console.log(i);
                if (i == jsonLength + 1) {
                    break;
                }
                if (i == parseInt(nextJump) + 1) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
            nexta.html(">>");
            nextli.append(nexta);
            $('.pagination').append(nextli);
            var lastli = $("<li>", { id: "pageLast", "class": "" });
            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
            lasta.html("Last")
            lastli.append(lasta);
            $('.pagination').append(lastli);
        } else {
            if (prevJump == 0) {
                prevJump = 1;
            } else {
                prevJump = parseInt(prevJump) + 10;
            }
            id = Math.floor(jsonLength / 10) * 10 + 10;
            var firstli = $("<li>", { id: "pageFirst", "class": "" });
            var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
            firsta.html("First")
            firstli.append(firsta);
            $('.pagination').append(firstli);
            var prevli = $("<li>", { id: "pagePrev", "class": "", "onclick": "prevPagination()" });
            var preva = $("<a>", { id: prevJump, "class": "prev" });
            var nextli = $("<li>", { id: "pageNext", "class": "disabled" });
            var nexta = $("<a>", { id: id, "class": "next", "onclick": "nextPagination()" });
            preva.html("<<");
            prevli.append(preva);
            $('.pagination').append(prevli);
            for (var i = parseInt(nextJump) + 1; i <= parseInt(nextJump) + 10; i++) {
                console.log(i);
                if (i == jsonLength + 1) {
                    break;
                }
                if (i == parseInt(nextJump) + 1) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
            nexta.html(">>");
            nextli.append(nexta);
            $('.pagination').append(nextli);
            var lastli = $("<li>", { id: "pageLast", "class": "disabled" });
            var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
            lasta.html("Last")
            lastli.append(lasta);
            $('.pagination').append(lastli);
        }
    }
}

function firstPagination() {
    if ($('#pageFirst').attr('class') == 'disabled') {
        return
    } else {
        $('.pagination').empty();
        var firstli = $("<li>", { id: "pageFirst", "class": "disabled" });
        var firsta = $("<a>", { id: "", "class": "first", "onclick": "firstPagination()" });
        firsta.html("First")
        firstli.append(firsta);
        $('.pagination').append(firstli);
        var prevli = $("<li>", { id: "pagePrev", "class": "disabled" });
        var preva = $("<a>", { id: '0', "class": "prev", "onclick": "prevPagination()" });
        var nextli = $("<li>", { id: "pageNext", "class": "" });
        var nexta = $("<a>", { id: "10", "class": "next", "onclick": "nextPagination()" });
        preva.html("<<");
        prevli.append(preva);
        $('.pagination').append(prevli);
        for (var i = 1; i <= 9; i++) {
            if (i == 1) {
                li[i] = $("<li>", { id: "", "class": "active" });
                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                a[i].html(i)
                li[i].append(a[i]);
                $('.pagination').append(li[i]);
                a[i].trigger('click');
            } else {
                li[i] = $("<li>", { id: "", "class": "" });
                a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                a[i].html(i)
                li[i].append(a[i]);
                $('.pagination').append(li[i]);
            }
        }
        nexta.html(">>");
        nextli.append(nexta);
        $('.pagination').append(nextli);
        var lastli = $("<li>", { id: "pageLast", "class": "" });
        var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
        lasta.html("Last")
        lastli.append(lasta);
        $('.pagination').append(lastli);
    }
}

function lastPagination() {
    if ($('#pageLast').attr('class') == 'disabled') {
        return
    } else {
        var nextJump = $('.next').prop('id');
        var prevJump = $('.prev').attr('id');
        $('.pagination').empty();

        var id = parseInt(nextJump) + 10;
        var firstli = $("<li>", { id: "pageFirst", "class": "" });
        var firsta = $("<a>", { id: '', "class": "first", "onclick": "firstPagination()" });
        var prevli = $("<li>", { id: "pagePrev", "class": "", "onclick": "prevPagination()" });
        var preva;
        if (jsonLength <= 30 && jsonLength > 20) {
            preva = $("<a>", { id: "11", "class": "prev" });
        } else if (jsonLength <= 20 && jsonLength > 10) {
            preva = $("<a>", { id: "1", "class": "prev" });
        } else {
            preva = $("<a>", { id: (Math.floor(jsonLength / 10) * 10) - 20, "class": "prev" });
        }
        var nextli = $("<li>", { id: "pageNext", "class": "disabled" });
        var nexta;
        firsta.html("First");
        firstli.append(firsta)
        $('.pagination').append(firstli);
        preva.html("<<");
        prevli.append(preva);
        $('.pagination').append(prevli);
        if (jsonLength % 10 == 0) {
            nexta = $("<a>", { id: Math.floor(jsonLength / 10) * 10, "class": "next", "onclick": "nextPagination()" });
            for (var i = (Math.floor(jsonLength / 10) * 10) - 10; i <= jsonLength + 11; i++) {
                console.log(i);
                if (i == jsonLength + 1) {
                    break;
                }
                if (i == jsonLength) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
        } else {
            nexta = $("<a>", { id: Math.floor(jsonLength / 10) * 10 + 10, "class": "next", "onclick": "nextPagination()" });
            for (var i = (Math.floor(jsonLength / 10) * 10) + 1; i <= jsonLength + 11; i++) {
                console.log(i);
                if (i == jsonLength + 1) {
                    break;
                }
                if (i == jsonLength) {
                    li[i] = $("<li>", { id: "", "class": "active" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                    a[i].trigger('click');
                } else {
                    li[i] = $("<li>", { id: "", "class": "" });
                    a[i] = $("<a>", { id: i, "class": "", "onclick": "pagenation($(this))" });
                    a[i].html(i)
                    li[i].append(a[i]);
                    $('.pagination').append(li[i]);
                }
            }
        }
        nexta.html(">>");
        nextli.append(nexta);
        $('.pagination').append(nextli);
        var lastli = $("<li>", { id: "pageLast", "class": "disabled" });
        var lasta = $("<a>", { id: "", "class": "last", "onclick": "lastPagination()" });
        lasta.html("Last")
        lastli.append(lasta);
        $('.pagination').append(lastli);
    }
}



function popclear() {
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle="SelPriority"]').not('[data-title="' + 3 + '"]').removeClass('active').addClass('not-active');
    $('#WatchTable tbody').empty();
    $('#endDate').val('');
    $('#SelParameter').empty();
    $('#SelFrequency').empty();
    $('#txttarget1').val('');
    $('#txttarget2').val('');
    $('#txtVipDetails').val('');
    watchvipclear();
}

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

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


//direct appointment booking - Manthira Parthiban

function direct_appointment_booking(id, elem) {
    debugger;
    claimreload();
    var did = $(elem).data('id');
    var navigation = $(elem).data('nav')
    var name = $(elem).data('name')
    var columntype = $(elem).data('type')
    //alert(navigation)
    //alert(name)

    var RightData = {
        doctor_user_module_id: did,
        Stringtype: columntype,
        Dml_Indicator: "RB"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/UserRight/User_rights_privileges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(RightData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    var j = 0;


                    var status = data1.Table[0].role_rights_add
                    if (status == 0) {
                        toastr.warning("you have no rights to access this page");
                        return;
                    }
                    else {
                        $('#hdnpatientapp').val(id);
                        //if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                        //    directappointment();
                        //}
                        //else {
                        //loadhospitaldoctor();
                        LoadBranch();
                        //}
                    }

                }
            }
        }
    });
}

function LoadBranch() {
    debugger;
    $('#SelBranch').empty();

    var dml = ''
    if (parseInt($('#hiddenRole_id').val()) == 1) {
        dml = 'DLBRAN'
    }
    else {
        dml = 'LBRAN'
    }

    var subdepartment = {
        //Dml_Indicator: "LBRAN",
        Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranch').append(SubDepartment);
                        $('#SelBranch').change();
                    }
                    else {
                        $('#SelBranch').append(default_opt + SubDepartment);
                    }

                    if ($('#hiddenRole_id').val() == 1) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelDoctor').val(data1.Table1[0].doctorname);
                        $('#Hdndoctor_id').val($('#HiddenDoctorID').val());
                        //$('#SelBranch').attr('disabled', true);
                        //  loadhospitaldoctor();
                    }
                    else if ($('#hiddenRole_id').val() == 6) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        //  loadhospitaldoctor();
                    }
                    else if ($('#hiddenRole_id').val() != 6 && $('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        //  loadhospitaldoctor();
                    }

                    $('#directappointment').modal('toggle');
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

//$('#SelBranch').change(function () {
//    $('#SelDoctor').empty();
//  //  loadhospitaldoctor();
//});

function loadhospitaldoctor() {
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            //$('#directappointment').modal('toggle');
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();
                    debugger;
                    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').append(default_opt + SelRole);

                        if ($('#hiddenRole_id').val() == 1) {
                            //  $('#SelDoctor').val(doctor);
                            $('#SelDoctor').val($('#HiddenDoctorID').val());
                            $('#SelDoctor').attr('disabled', true);
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

$('#direct_app_book').click(function () {
    debugger;
    if ($.trim($('#SelBranch').val()).length == "" || $.trim($('#SelBranch').val()) == "0") {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Select Branch');
        $('#SelBranch').focus();
        $('#SelBranch').val('0');
        return false;
    }

    if ($.trim($('#SelDoctor').val()).length == "" || $.trim($('#SelDoctor').val()) == "0") {
        $('#PSelDoctor').show();
        $('#PSelDoctor').fadeOut(8000);
        $('#PSelDoctor').html('Select Doctor');
        $('#SelDoctor').focus();
        $('#SelDoctor').val('0');
        return false;
    }

    if ($.trim($('#Entity').val()) == 1) {
        if ($.trim($('#EntityType').val()) == '') {
            $('#PEntityType').show();
            $('#PEntityType').fadeOut(8000);
            $('#PEntityType').html('Select Claim Type');
            $('#ddInsuranceName').focus();
            return false;
        }
    }

    if ($.trim($('#EntityType').val()) != '') {
        if ($.trim($('#HdnEntityid').val()) == '') {
            $('#PddInsuranceName').show();
            $('#PddInsuranceName').fadeOut(8000);
            $('#PddInsuranceName').html('Select Entity Name');
            $('#ddInsuranceName').focus();
            return false;
        }
        if ($('#CMultiPay').prop('checked') == true) {
            if ($.trim($('#MPCIName').val()) == '') {
                $('#PMPCIName').show();
                $('#PMPCIName').fadeOut(8000);
                $('#PMPCIName').html('Select the field');
                $('#PMPCIName').focus();
                return false;
            }
        }
        //if ($.trim($('#txt_emp_name').val()) == '') {
        //    $('#Ptxt_emp_name').show();
        //    $('#Ptxt_emp_name').fadeOut(8000);
        //    $('#Ptxt_emp_name').html('Enter Employee Name');
        //    $('#txt_emp_name').focus();
        //    return false;
        //}
        //if ($.trim($('#txt_emp_code').val()) == '') {
        //    $('#Ptxt_emp_code').show();
        //    $('#Ptxt_emp_code').fadeOut(8000);
        //    $('#Ptxt_emp_code').html('Enter Employee Code');
        //    $('#txt_emp_code').focus();
        //    return false;
        //}
    }

    directappointment();
});

function directappointment(id) {
    debugger;
    $('#directappointment').modal('toggle');
    var docid;
    if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
        docid = $('#HiddenDoctorID').val();
        //branch_id = $('#HospitalBranchID').val()
        branch_id = $('#SelBranch').val()
    }
    else {

        docid = $('#Hdndoctor_id').val();
        branch_id = $('#SelBranch').val()
    }
    var DoctorData = {
        Dml_Indicator: "DAPPB",
        Patient_id: $('#hdnpatientapp').val(),
        doctor_id: docid,
        appointment_type: 1,
        created_by: $('#HiddenDoctorID').val(),
        source_booking: "1",
        payment_mode: "4",
        hospital_id: $('#HospitalId').val(),
        branch_id: branch_id,
        is_entity: $('#Entity').val(),
        is_insurance: $('#EntityType').val(),
        insurance_id: $('#HdnEntityid').val(),
        is_pay: $('#CMultiPay').val(),
        corporate_insuranceid: $('#MPCIName').val(),
        employee_name: $('#txt_emp_name').val(),
        employee_code: $('#txt_emp_code').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            console.log(data);
            var data2 = JSON.parse(data);
                $('#SelBranch').val(branch_id);
                $('#SelDoctor').val(docid);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                SubmitArr = data1
              
               
                if (data1[0].StringMsg == 'already') {
                    toastr.warning('Already you have Appointment on' + ' ' + data1[0].Slotdate);
                    setTimeout(function () {
                        location.reload();
                    }, 2000);
                    //window.location.href = "/Dashboard";
                }
                else if (data1[0].StringMsg == 'already in ip') {
                    toastr.warning('Already you have admitted as IP patient');
                    setTimeout(function () {
                        location.reload();
                    }, 2000);
                    // window.location.href = "/Dashboard";
                }
                else if (data1[0].coupon_status == 'coupon') {
                    $('#shade_slot').hide();
                    $('#app_package_coupon_table').empty();
                    $('#appurpkgeView').modal('toggle');
                    if (jQuery.isEmptyObject((data1)) || data1.length == 0) {
                        tr = $('<table class="table table-responsive dataTable no-footer" id="apppkgecouTable" />');
                        tr.append("<thead><tr><th>S No</th><th>Coupon Status</th><th>Issued Date</th><th>Expiry Date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                        tr.append("</tbody>");
                    }
                    else {
                        var image = '', j = 0;

                        if (data1[0].photo != null) {
                            image = $('#patphotop').val() + data1[0].photo;
                        }
                        else {
                            image = "/Content/img/profile_icon.png";
                        }
                        $('#casePhoto1').attr('src', "" + image + "");
                        $('#patname').html(data1[0].first_name);
                        $('#patnum').html(data1[0].phone_number_1);
                        $('#Hdnpatient_id_coupon').val(data1[0].patient_id);
                        tr = $('<table  class="table dataTable no-footer" id="apppkgecouTable" />');
                        tr.append("<thead><tr><th>S No</th><th>Coupon Status</th><th>Issued Date</th><th>Expiry Date</th><th>Actions</th></tr></thead><tbody>");
                        $.each(data1, function (i, emp) {
                            j++;
                            var expire_date = (emp.coupon_expire_date).split('T');
                            var issued_date = (emp.created_on).split('T');
                            row_data = "<tr><td>" + j + "</td><td>" + 'Active' + "</td><td>" + issued_date[0] + "</td><td>" + expire_date[0] + "</td><td><button><span class='ur-pkge-view1' data-toggle='popover' title='Select Coupon' data-target='#appurpkgeView' onclick=buy_coupon('" + emp.coupon_id + "')>select</span></button></tr>";
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#app_package_coupon_table').append(tr)).then($('#apppkgecouTable').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                    }
                }
                else {
                    var ChkForm = CheckConsulationRights($('#hdnpatientapp').val(), 33, 5, docid, data1[0].doctor_appointment_slot_id, 0, branch_id);
                    $.when(ChkForm)
              .then(function (data3) {
                  var data2 = JSON.parse(data3);

                  if (jQuery.isEmptyObject((data2.data))) {
                      booknow()
                  }
                  else {
                      debugger;
                      if (data2.data.Table[0].StringMsg != "Rights") {
                          booknow()
                      }
                  }
              });
                   
                }
            }
            //var data2 = JSON.parse(data);
            //console.log(data2);
            //if (jQuery.isEmptyObject((data2.data))) {
            //}
            //else {
            //    $('#SelBranch').val(branch_id);
            //    $('#SelDoctor').val(docid);
            //    if (data2.msg == "Success") {
            //        var data1 = data2.data;
            //        SubmitArr = data1
            //        var ChkForm = CheckFormRights($('#hdnpatientapp').val(), 33, 3, 2, docid);
            //        $.when(ChkForm)
            //  .then(function (data3) {
            //      var data2 = JSON.parse(data3);

            //      if (jQuery.isEmptyObject((data2.data))) {
            //          booknow()
            //      }
            //      else {
            //          debugger;
            //          if (data2.data.Table[0].StringMsg != "Rights") {
            //              booknow()
            //          }
            //      }
            //  });
                }
                //else {
                //    console.log(data);
                //}

        //    }
        //}
    });
}




$('#formClose').click(function () {
    debugger;
    if ($("#hFormCloseCheck").val() != 1 && $("#hFormCloseCheck1").val() != 1) {
        booknow()
    } 
})
function booknow() {
    toastr.success("Appointment Booked");
    setTimeout(function () {
        location.reload();
    }, 1000);
}

function buy_coupon(id) {
    $('#appurpkgeView').modal('toggle');
    var docid;
    if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
        docid = $('#HiddenDoctorID').val();
        branch_id = $('#HospitalBranchID').val()
    }
    else {
        docid = $('#SelDoctor').val();
        branch_id = $('#SelBranch').val()
    }
    var package_data = {
        indicator_id: "ACID",
        coupon_id: id,
        patient_id: $('#Hdnpatient_id_coupon').val(),
        source_booking: "1",
        payment_mode: "1",
        doctor_id: docid,
        branch_id: branch_id
    }
    $.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 data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;
                var b = data1.Table;
                if (b[0].msg == "Success") {
                    
                    var ChkForm = CheckConsulationRights($('#hdnpatientapp').val(), 33, 5, docid, b[0].doctor_appointment_slot_id, 0, branch_id);
                    $.when(ChkForm)
              .then(function (data3) {
                  var data2 = JSON.parse(data3);

                  if (jQuery.isEmptyObject((data2.data))) {
                      toastr.success("Appointment Booked Successfully using Package Coupon");
                      setTimeout(function () {
                          location.reload();
                      }, 1000);
                  }
                  else {
                      debugger;
                      if (data2.data.Table[0].StringMsg != "Rights") {
                          toastr.success("Appointment Booked Successfully using Package Coupon");
                          setTimeout(function () {
                              location.reload();
                          }, 1000);
                      }
                  }
              });
                }
                else {
                    toastr.warning("Something went wrong");
                }
            }
            else {
                console.log(data);
            }

        }
    });
}


//payment start
function collectpayment(patient_id, patient_first_name, patient_phone_number, photoSrc, visit_report_id, doctor_id, slottime) {
    debugger;
    $('#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);
    $('#pop_doctor_id').val(doctor_id);
    payment_val();
}
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 InvoiceId = {
        Patient_id: $('.PatientId').html(),
        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 data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    if (data.length > 0) {
                        $('#InvoiceId').val(data[0].InvoiceId);
                        $('#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 {
                    console.log(data);
                }

            }
            ActiveInvoice();
            invoice_quickSelect();
        }
    });
}



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 data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    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;
    debugger;
    var invoice = {}
    invoice.invoice_id = $('#InvoiceId').val(),
        invoice.Patient_id = $('.PatientId').html(),
        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) {
                if (jQuery.isEmptyObject((data))) {

                }
                else {

                }
                collectpayment_afterinsert($('#Hdnpatient_id').val());
            }
        });
}



$('#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: $('.PatientId').html(),
        doctor_id: $('#HiddenDoctorID').val(),
        invoice_description: $('#InvoiceName').val(),
        invoice_date: InvoiceDate,
        invoice_amount: $('#InvoiceAmount').val(),
        invoice_status: 1,
        balance_amount: $('#InvoiceAmount').val(),
        Dml_Indicator: 'I',
        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) {
            if (jQuery.isEmptyObject((data))) {

            }
            else {

            }
            $('#InvoiceDate').val('');
            $('#InvoiceName').val('');
            $('#InvoiceAmount').val('');
            collectpayment_afterinsert($('#Hdnpatient_id').val());
        }
    });
});


function collectpayment_afterinsert(patient_id) {
    var InvoiceId = {
        Patient_id: $('.PatientId').html(),
        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 data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    if (data.length > 0) {
                        $('#InvoiceId').val(data[0].InvoiceId);
                    }
                }
                else {
                    console.log(data);
                }

            }
            ActiveInvoice();
        }
    });
}

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

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

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


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

                        for (var i = 0; i < data.length; i++) {
                            if (data[i].invoice_status == 5) {
                                tr = tr + '<tr data-invoice="' + data[i].invoice_id + "," + data[i].invoice_amount + '"><td></td><td>' + data[i].invoice_id + '</td><td>' + data[i].invoice_date + '</td><td><span class="print btn addicon-btn  btn-sm"><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\",\"' + data[i].invoice_description + '\")\'; ></i></span>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td>SMS payment initiated</td><td>-</td></tr>';
                            }
                            else {
                                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>' + data[i].invoice_description + '</td><td>' + data[i].invoice_amount + '</td><td>' + data[i].balance_amount + '</td><td><a class="payment btn addicon-btn  btn-sm mr-20" href="javascript:void(0);"  data-backdrop="static" title="CASH" data-keyboard="true" onclick =\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 1 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-money" area-hidden="true"></i></a><a class="payment btn addicon-btn  btn-sm mr-20" href="javascript:void(0);" data-backdrop="static" title="CARD" data-keyboard="true" onclick=\'fullpayment(\"' + data[i].balance_amount + '\",\"' + 2 + '\",\"' + data[i].invoice_id + '\", \"' + data[i].lab_order_id + '\")\';><i class="fa fa-credit-card" area-hidden="true"></i><a class="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><a class="print btn addicon-btn  btn-sm"><i class="fa fa-print" onclick=\'Invoice_lab_print(\"' + data[i].lab_order_id + '\",\"' + data[i].visit_report_id + '\",\"' + data[i].invoice_id + '\", \"' + data[i].invoice_description + '\")\'; ></i></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 {
                    }
                }
                else {
                    console.log(data);
                }

            }
            $('#cpi_activeInvoice_table').removeClass('us-db-loader-active-inv');
        }
    });
}

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

$('#lookup').click(function () {
    var smspayment = {
        email_id: $('#paymailid').val(),
        phone_number: $('#payphonenumber').val(),
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/lookup',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
            }
        }
    })
});

$('#btnsmspayment').click(function () {
    if ($('#totpopup_amout >i').html() == '' || $('#totpopup_amout >i').html() == 0) {
        toastr.warning('invoice cannot be empty.Please select atleast one invoice');
        return false;
    }
    if ($('#payphonenumber').val() == '' || $('#payphonenumber').val() == null) {
        $('#Ppayphonenumber').show();
        $('#Ppayphonenumber').fadeOut(8000);
        $('#Ppayphonenumber').html('Enter phone number');
        $('#payphonenumber').focus();
        $('#payphonenumber').val('');
        return false;
    }

    if ($('#paymailid').val() == '' || $('#paymailid').val() == null) {
        $('#P_paymailid').show();
        $('#P_paymailid').fadeOut(8000);
        $('#P_paymailid').html('Enter mail id');
        $('#paymailid').focus();
        $('#paymailid').val('');
        return false;
    }


    var invoice_no_temp = "";
    var Amount_temp = "";
    $('#cpi_activeInvoice_body').find('tr').each(function () {
        var row = $(this);
        if (row.find('input[type="checkbox"]').is(':checked')) {
            var $row = jQuery(this).closest('tr');
            var $columns = $row.find('td');
            var values = "";
            jQuery.each($columns, function (i, item) {
                invoice_no = $(this).parent("tr").find("td:eq(1)").text();
                Amount = $(this).parent("tr").find("td:eq(4)").text();
            });
            console.log(invoice_no);
            invoice_no_temp = invoice_no_temp + ',' + invoice_no;
            Amount_temp = Amount_temp + ',' + Amount;
        }
    });

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

    var smspayment = {
        email_id: $('#paymailid').val(),
        phone_number: $('#payphonenumber').val(),
        created_by: $('#hiddenUserId').val(),
        valid_for: '7',
        valid_type: 'days',
        valid_date: '',
        currency: 'INR',
        amount: $('#totpopup_amout >i').html(),
        due_date: '',
        invoice_no: '',
        Dml_Indicator: 'I',
        patient_id: $('.PatientId').html(),
        customer_name: $('#PatientName').html(),
        invoice_no_temp: invoice_no_temp,
        Amount_temp: Amount_temp,
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    if (data.length > 0) {
                        var sms_invoice_no = data[0].sms_invoice_no;
                        var email_id = data[0].email_id;
                        var phone_number = data[0].phone_number;
                        var amount = data[0].amount;
                        var invoice_no = "";
                        var Amount = "";
                        var invoice_no_temp = "";
                        var Amount_temp = "";

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

                                }
                                else {
                                    toastr.success('Payment link sent');
                                    ActiveInvoice();
                                    $('#totpopup_amout>i').html('');
                                    $('#payphonenumber').val('');
                                    $('#paymailid').val('');
                                }
                            }
                        });
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});


function checkval(val, id) {
    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 smslinkfun(value, name) {
    if (value == "" || value == "-") {
        toastr.warning('Please Check the Patient Phone Number');
        return false;
    }
    var smspayment = {
        phonenumber: value,
        msg: "Dear " + name + ", . Doctor is held up with an emergency and will call you as soon as possible. Thank you for your patience. By Mocero",
        temp_id: "1607100000000093962"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/sms_link',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(smspayment),
        success: function (data) {

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

                if (data == true) {
                    toastr.success('SMS sent to patient');
                }
                else {
                    toastr.success('SMS sent to patient');
                }
            }
            else {
                console.log(data);
            }

        }
    });
}




function add_payment1(labid) {
    $('#add_cpi_invoice').prop('disabled', false);
    $('#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 to 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) {
    var invoice_status = 3;
    var patient_id, doc_id;
    if (lab_order_id.length > 3) {
        patient_id = $('.PatientId').html();
        doc_id = lab_order_id.split('-')[0];
        if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == $('#HospitalId').val()) {
            get_package_details(lab_order_id, invoice_id, patient_id);
        }
    }
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('.PatientId').html(),
        payment_amount: balance_amount,
        payment_type: payment_type,
        invoice_id: invoice_id,
        invoice_status: invoice_status,
        balance_amount: 0,
        Dml_Indicator: 'PI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data = JSON.parse(data);
            }
            $('#paymentamount').val('');
            doc_id = lab_order_id.split('-')[0];
            if (doc_id == ($('#HiddenDoctorID').val()) || doc_id == ($('#HospitalId').val())) {
                get_package_details(lab_order_id, invoice_id, $('#Hdnpatient_id').val());
            }
            ActiveInvoice();
            HistroyInvoice();
            toastr.success("Full Payment added Successfully");
            $('.paymentclose').click();
        }
    });
}

$('#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) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Entered MPIN is wrong');
            }
            var data = JSON.parse(data2.data);
            if (data.length == 0) {
                toastr.warning("Entered MPIN is wrong");
            }
            else {
                if (data.length > 0) {
                    if (data[0].StringMsg == 'Success') {
                        ActiveInvoice();
                    }
                    else if (data[0].StringMsg == 'Cannot able to delete') {
                        toastr.warning('Payment Received - cannot delete Invoice');
                    }
                    else {
                        toastr.warning('Entered MPIN is wrong !!!');
                    }
                }
            }
        }
    });
});

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


function ActiveInvoiceDetails(id, amount) {
    $('#curinvoiceid').val(id);
    $('#curamount').val(amount);
    var invoice = {
        invoice_id: $('#curinvoiceid').val(),
        Patient_id: $('.PatientId').html(),
        doctor_id: $('#HiddenDoctorID').val(),
        Dml_Indicator: 'PD',
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(invoice),
        success: function (data) {
            $('#tblinvoiceamtdetails_body').empty();
            var tr = '';
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                $('#totamt').html(amount);
                $('#paidamt').html('0');
                $('#balanceamt').html('0');
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    $('#totamt').html('0');
                    $('#paidamt').html('0');
                    $('#balanceamt').html('0');
                    if (data.length > 0) {
                        for (var i = 0; i < data.length; i++) {
                            var paymenttype = '';
                            if (data[i].payment_type == 1) {
                                paymenttype = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                paymenttype = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                paymenttype = 'Payment Gateway';
                            }
                            else {
                                paymenttype = '-';
                            }
                            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 () {
    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;
    }
    $('#add_cpi_invoice').prop('disabled', true);
    var previousval = 0;
    $('#tblinvoiceamtdetails > tbody  > tr').each(function () {
        $(this).find("td:gt(1)").each(function () {
            var temp = $(this).html();
            previousval = parseFloat(previousval) + parseFloat(temp);
        });
    });
    previousval = parseFloat(previousval) + parseFloat($('#paymentamount').val());
    var invoice_status = '', balance_amount = '', patient_id = '', invoice_id = '', doc_id = '', package_id = '';
    if (previousval > parseFloat($('#curamount').val())) {
        $('#Ppaymentamount').show();
        $('#Ppaymentamount').fadeOut(8000);
        $('#Ppaymentamount').html('Check amount');
        $('#paymentamount').focus();
        $('#paymentamount').val('');
        $('#add_cpi_invoice').prop('disabled', false);
        return false;
    }
    else if (previousval < parseFloat($('#curamount').val())) {
        invoice_status = 2;
        balance_amount = parseFloat($('#curamount').val()) - parseFloat(previousval);
    }
    else {
        patient_id = $('#Hdnpatient_id').val();
        invoice_id = $('#curinvoiceid').val();
        package_id = $('#pack_id').val();
        if (package_id != null || package_id != "") {
            if (package_id.length > 3) {
                doc_id = $('#pack_id').val().split('-')[0];
                if (doc_id == ($('#HospitalId').val()) || doc_id == ($('#HiddenDoctorID').val())) {
                    get_package_details(package_id, invoice_id, patient_id);
                }
            }
        }
        invoice_status = 3;
        balance_amount = 0;
    }
    var InvoiceId = {
        doctor_id: $('#HiddenDoctorID').val(),
        patient_id: $('.PatientId').html(),
        payment_amount: $('#paymentamount').val(),
        payment_type: $('#Selpaymenttype').val(),
        invoice_id: $('#curinvoiceid').val(),
        invoice_status: invoice_status,
        balance_amount: balance_amount,
        transaction_id: $("#transaction_id").val(),
        Dml_Indicator: 'PI'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                var data = JSON.parse(data);
            }
            $('#paymentamount').val('');
            $('#transaction_id').val('');
            $('#transaction').hide();
            ActiveInvoice();
            HistroyInvoice();
            ActiveInvoiceDetails($('#curinvoiceid').val(), $('#curamount').val());
            $('#add_cpi_invoice').prop('disabled', false);
            $('#Selpaymenttype').val('1');
        }
    });
});

$('#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: $('.PatientId').html()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/caseStudy/invoice_payment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(InvoiceId),
        success: function (data) {
            var tr = '';
            $('#cpi_historyInvoice_body').empty();
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data = data2.data;
                    if (data.length > 0) {
                        var tr1 = '', tr2 = '', tr3 = '', j = 1;
                        var invoice_id = '';
                        var a = data.length;
                        for (var i = 0; i < data.length; i++) {
                            var payment_type = '';
                            if (data[i].payment_type == 1) {
                                payment_type = 'Cash';
                            }
                            else if (data[i].payment_type == 2) {
                                payment_type = 'Card';
                            }
                            else if (data[i].payment_type == 3) {
                                payment_type = 'Payment Gateway';
                            }
                            else {
                                payment_type = 'Online';
                            }
                            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 + '\", \"' + data[i].invoice_description + '\")\'; ></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 + '\", \"' + data[i].invoice_description + '\") \';></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
                        $('#cpi_historyInvoice_body').html(tr);
                        $("[data-toggle=popover]").popover();
                    }
                }
                else {
                    console.log(data);
                }
            }
            $('.cpi_historyInvoice_table').removeClass('us-db-loader-history-inv');
        }
    });
}


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

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

});

$('#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 data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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


            }
        }
    });
});


$('#us-chat-send-btn').click(function () {
    if ($.trim($('#supportmsg').val()).length > 0) {
        var val = "1";
        doctor_support(val);
    }
    else {
        $('#errormsg').fadeOut(8000);
        $('#errormsg').html('enter the message');
    }
});

$('#us-chat-st-btn').click(function () {
    $('#us-chat-st-btn').hide();
    var val = "2";
    doctor_support(val);
});

$('#helpSeeQui').click(function () {
    doctor_support_list();
});

function doctor_support(val) {
    if (val == "1") {
        var doctor_support = {
            doctor_id: $('#HiddenDoctorID').val(),
            message: $('#supportmsg').val(),
            sms_group: "5",
            indicator_id: "I"
        }
    }
    else {
        var doctor_support = {
            doctor_id: $('#HiddenDoctorID').val(),
            message: "Request A Call back",
            sms_group: "5",
            indicator_id: "I"
        }
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_support',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctor_support),
        success: function (data) {
            if (val == "1") {
                $('#supportmsg').val('');
                $('.us-chat-callbackform').show();
            }
            else {
                $('.us-chat-callbackbtn').show();
            }
        }
    });
}

function doctor_support_list() {
    var doctor_support = {
        doctor_id: $('#HiddenDoctorID').val(),
        sms_group: "5",
        indicator_id: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Dashboard/doctor_support',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctor_support),
        success: function (data) {
            $('#support_list').empty();
            var data2 = JSON.parse(data);
            var data1 = JSON.parse(data2.data);
            var d = new Date();
            var month = d.getMonth() + 1;
            var day = d.getDate();
            var output = d.getFullYear() + '-' + (month < 10 ? '0' : '') + month + '-' + (day < 10 ? '0' : '') + day;
            if (jQuery.isEmptyObject((data2.data))) {
                $('#support_list').toggleClass('empty-enq-list');
            }
            else if (data1['support_list'].length == 0) {
                $('#support_list').toggleClass('empty-enq-list');
            }
            else {
                $.each(data1['support_list'], function (i, emp) {
                    if (output == emp.sent_on.split('T')[0]) {
                        var html = '<a href="#" class="urs-ques-link" data-toggle="popoverques" data-placement="left" title= "' + emp.date + '" data-content="' + emp.message + '"><li><span class="us-ques-date"> ' + emp.date + '</span><span class="us-ques-abt">' + emp.message + '</span><span class="us-ques-type"><strong>New</strong></span></li></a>';
                        $('#support_list').append(html);

                    }
                    else {
                        var html = '<a href="#" class="urs-ques-link" data-toggle="popoverques" data-placement="left" title= "' + emp.date + '" data-content="' + emp.message + '"><li><span class="us-ques-date"> ' + emp.date + '</span><span class="us-ques-abt">' + emp.message + '</span><span i class="fa fa-clock-o"></i></span></li></a>';
                        $('#support_list').append(html);
                    }
                });
            }
        }
    });
}


//patient advanced filter search

$('#id_personal').click(function () {
    $('#tab_val').val("1");
});

$('#id_app').click(function () {
    $('#tab_val').val("2");
});

$('#id_diab').click(function () {
    $('#tab_val').val("3");
});
//paymenttype if value=4 transaction id will enable
$("#Selpaymenttype").change(function () {
    var value = $("#Selpaymenttype").val();
    if (value == 4) {
        $("#transaction").show();
    }
    else {
        $("#transaction").hide();
    }
})
//filter clear 
$('#pat_clear').click(function () {
    debugger;
    $('#Mtxtpatient_id').val('');
    $('#txtname').val('');
    $('#pat_sear_age').val('');
    $('#txtphone').val('');
    // $('#ftdtype1').prop('checked', false);
    //  $('#ffemale').prop('checked', false);
    //  $('#fnone').prop('checked', false);
    $('#appDate').val('');
    $('#nextDate').val('');
    $('#YearsOFdia').val('');
    // $('input:checkbox').prop('checked', false);
    $('#FddGender').val('').change();
    $('#ftdtype1').prop('checked', false);
    $('#ftdtype2').prop('checked', false);
    $('#ftdmody').prop('checked', false);
    $('#ftdtype').prop('checked', false);
    $('#ftdgdm').prop('checked', false);
    $('#ftdtypenone').prop('checked', false);

    var date2 = new Date();
    date2.setDate(date2.getDate());
    console.log(date2);
    $('#appDate').daterangepicker({
        showDropdowns: false,
        format: 'MM/DD/YYYY',
        maxDate: date2,
        showButtonPanel: false,
        autoUpdateInput: false

    });
    //$('#nextDate').daterangepicker({
    //    showDropdowns: false,
    //    format: 'MM/DD/YYYY',
    //    minDate: date2,
    //    showButtonPanel: false,
    //    autoUpdateInput: false

    //});
    $('#appDate,#nextDate').val('');
    $('.ranges').hide();

    loadpatientcount();

    //  NewPatient_listTbl()
})


//$('#urpkgeView').modal('show');
function package_view(patientid, branch_id) {
    debugger;
    var package_data = {
        indicator_id: "PK_CN_VIEW",
        patient_id: patientid,
    }
    $.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) {
            debugger;
            $('#package_coupon_table').empty();
            //$('#urpkgeView').modal('toggle');
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = $('<table class="table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>S No</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;
                    if (patientid != '' && branch_id != '') {
                        PatientGeneralDetails(patientid, branch_id)

                        $('#model_popup').removeClass('hidden')
                        $('#txtPSearch').addClass('disabled')
                    }
                    tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>S No</th><th>Coupon Type</th><th>Service Name</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(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 (emp.type == "1") type = "Consulting";
                        else if (emp.type == "2") type = "Hospital Care";
                        else if (emp.type == "3") type = "Home Care";
                        if (emp.coupon_useby_date == "" || emp.coupon_useby_date == null) {
                            emp.coupon_useby_date = '-';
                        }
                        debugger;
                        if (emp.expire_status == 1) {
                            if (emp.coupon_status == 1) {
                                row_data = "<tr><td>" + j + "</td><td>" + type + "</td><td>" + emp.service_name + "</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-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>";
                                //  <td><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>
                            }
                            else {
                                row_data = "<tr><td>" + j + "</td><td>" + type + "</td><td>" + emp.service_name + "</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>-</td></tr>";
                            }
                        }
                        else {
                            if (emp.coupon_status != 2 && emp.coupon_status != 4) {
                                coupon = 'Expired';
                            }
                            if (coupon_consumed_by == '-') {
                                row_data = "<tr><td>" + j + "</td><td>" + type + "</td><td>" + emp.service_name + "</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>-</td></tr>";
                            }
                            else {
                                row_data = "<tr><td>" + j + "</td><td>" + type + "</td><td>" + emp.service_name + "</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>-</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) {
    debugger;
    $('#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) {
            debugger;
            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) {
                //$('#pkgecouTable').DataTable.Destroy();
                $('#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("Ivalid 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";
                            else if (emp.coupon_status == 5) coupon = "Unused";
                            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.coupon_status != 4) {
                                //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>";
                                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-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><td>-</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);
                }
            }
        });
    }
}

// Claim Start //

$("#Entity_yes").click(function () {
    $('#div_EntityType').removeClass('hide');
    $('.divEmp').removeClass('hide');
    $('#divEmpName').addClass('hide');
    $('#divEmpCode').addClass('hide');
});
$("#Entity_no").click(function () {
    $('#div_EntityType').addClass('hide');
    $('.divEmp').addClass('hide');
    $('#txt_emp_name,#txt_emp_code').val('');
    $('#divInsuranceName').addClass('hide');
    $('#EntityType_Insurance').removeClass('active');
    $('#EntityType_Corporate').removeClass('active');
    $('#EntityType_Insurance').addClass('not-active');
    $('#EntityType_Corporate').addClass('not-active');
    $('#EntityType').val('');
    $('#HdnEntityid').val('');
    $('#CMultiPay').prop('checked', false);
    $('#divMultiPay').addClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').val(0);
});

function claimreload() {
    $('#div_EntityType').addClass('hide');
    $('#divInsuranceName').addClass('hide');
    $('#EntityType_Insurance').removeClass('active');
    $('#EntityType_Corporate').removeClass('active');
    $('#EntityType_Insurance').addClass('not-active');
    $('#EntityType_Corporate').addClass('not-active');
    $('#Entity_yes').removeClass('active');
    $('#Entity_yes').addClass('not-active');
    $('#Entity_no').removeClass('not-active');
    $('#Entity_no').addClass('active');
    $('#EntityType').val('');
    $('#HdnEntityid').val('');
}

$('#EntityType').change(function () {
    var entity_type = $('#EntityType').val();
    $('#ddInsuranceName').val('');
    $('#divInsuranceName').removeClass('hide');
    $('#divMultiPay').removeClass('hide');
    $('#divTPA').addClass('hide');
    $('#MPCIName').empty();
    $('#CMultiPay').prop('checked', false);
    $('#CMultiPay').val(0);
    $('#txt_emp_name').val('')
    $('#txt_emp_code').val('')
    if (entity_type == 1) {
        $('#ins_chk_lbl').html('Indirect');
        $('#ins_sel_lbl').html('TPA<span class="red">*</span>');
        $('#divEmpName').addClass('hide');
        $('#divEmpCode').addClass('hide');
    }
    else {
        $('#ins_chk_lbl').html('MultiPay');
        $('#ins_sel_lbl').html('Insurance Name<span class="red">*</span>');
        $('#divEmpName').removeClass('hide');
        $('#divEmpCode').removeClass('hide');
    }
});
//Indirect or Multipay onchange
$('#CMultiPay').change(function () {
    debugger;
    this.value = this.checked ? 1 : 0;
    if (this.value == '1') {
        $('#divTPA').removeClass('hide');
    }
    else {
        $('#divTPA').addClass('hide');
        $('#MPCIName').val('');
    }
})

$('#ddInsuranceName').autocomplete({

    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Ipmanagement/AutoEntity',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, is_insurance: $('#EntityType').val(), entity_name: $('#ddInsuranceName').val(), branchid: $('#SelBranch').val() },
            success: function (data) {

                console.log(data);
                var data2 = JSON.parse(data);
                var data = data2.data;
                response($.map(data, function (item) {
                    return { label: item.entity_name, value: item.entity_name, id: item.master_entity_id };
                }))

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnEntityid').val(ui.item.id);
        Corporate_Insurance($('#HdnEntityid').val(), 0);
        $('#MPCIName').val(0);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

});
//Load Insurance Name when corporate is choosed
function Corporate_Insurance(Corporateid, CIid) {
    debugger
    var dml = '', EntityType = $('#EntityType').val();

    if (EntityType == 1) {
        dml = 'PITPA'
    }
    else if (EntityType == 2) {
        dml = 'PCIN'
    }

    var Billingata = {
        Dml_Indicator: dml,
        insurance_id: Corporateid

    }

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

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

            }
            else {

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

                    var CInsurance;

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

                        CInsurance = CInsurance + '<option value="' + emp.master_entity_billing_id + '">' + emp.entity_name + '</option>';

                    });
                    $('#MPCIName').append(default_opt + CInsurance);

                    if (CIid != '' || CIid != 0) {
                        $('#MPCIName').val(CIid);
                    }

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

}

// Claim End //


//function check_priviliges()
//{
//    var userdata = {
//        Dml_Indicator: "GRR",
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/UserCreate/UserRoleRights_Ins_Upd_Del',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(userdata),
//        success: function (data) {
//            if (jQuery.isEmptyObject((data))) {
//            }
//            else {
//                if (data.length > 0) {
//                    var data = JSON.parse(data);
//                    if (data.msg == "Success") {
//                        if (data["data"].length > 0) {
//                            var j = 1, key = "", c_key = "";
//                            for (var i = 0; i < data["data"].length; i++) {
//                                if (data["data"][i].doctor_user_role_rights == 1) {
//                                    key = "#" + j + " a"; c_key = "." + j + " a";
//                                    $(key).attr('href', data["data"][i].module_path);
//                                    $(c_key).attr('href', data["data"][i].module_path);
//                                    $("#" + j).show();
//                                    $("." + j).show();
//                                }
//                                else {
//                                    $("#" + j).hide();
//                                }
//                                j = j + 1;
//                                key = "";
//                            }
//                        }
//                    }
//                    else {
//                    }
//                }
//                else {
//                }
//            }
//        }
//    });
//}
// Function to handle page changes
function handlePageChange(pageNum) {
    currentPage = pageNum;

    // NewPatient_listTbl(); // Call your function to fetch data
}
$('#patientsearchtable').on('page.dt', function () {
    var pageInfo = $('#patientsearchtable').DataTable().page.info();
    handlePageChange(pageInfo.page + 1);
});


function NewPatient_listTbl() {
    debugger;
    //$('#tblPatientSearch').empty();
    $('#patientsearchtablebody').empty();
    var patientID = $('#Patient_Id').val();
    var SeletedValue = $('#SelFilter').val();
    var DML;
    if (patientID != "") {
        DML = 'PN';
        //$('#btnloadmore').hide();
        $('#patientsearchtablebody').empty();
    }
    else {

        DML = 'PLN';
    }
    var patientIDs = patientID.split('/');
    patientID = patientIDs[patientIDs.length - 1];
    var PatientSearchData = {
        Doctor_Id: $('#HiddenDoctorID').val(),
        Condition: patientID,
        Dml_Indicator: DML,
        user_role: $('#hiddenRole_id').val(),
        branch_id: $("#SelBranchFilter").val() == null || $("#SelBranchFilter").val() == '' ? $('#HospitalBranchID').val() : $("#SelBranchFilter").val(),
        FPatient_id: $("#Mtxtpatient_id").val(),
        patient_first_name: $("#txtname").val(),
        age: $("#pat_sear_age").val(),
        mobile_no: $("#txtphone").val(),
        gender: $("#FddGender").val().join(",")
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientSearch/PatientSearch_Select',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),

        success: function (data) {
            debugger;

            if (jQuery.isEmptyObject((data))) {
                //$('#tblPatientSearch').empty();
                $('#patientsearchtablebody').empty();
                $('#patientsearchtable').dataTable().fnClearTable();
                //$('#patientsearchtable').dataTable().fnDestroy();               
                //$('#tblPatientSearch').html('<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>');
            }
            else {
                var data2 = JSON.parse(data);
                console.log(data2);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var j = 0;
                    var PatientSearch = '';
                    console.log(data1);
                    if (data1.length > 2) {
                        $('#btnloadmore').show();
                        var start = $('#limitstart').val();
                        var end = $('#limitend').val();
                        $('#limitstart').val(end);
                        $('#limitend').val(parseInt(end) + parseInt(21));
                    }
                    else {
                        $('#btnloadmore').hide();
                    }

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

                    //         var Pname = '', gender = '', dob = '', age = '', ages = '', bloodgroup = '', typediabetics = '', yeardiabetics = '', lastvisit = '', nextvisit = '', Phoneno = '', coupon_id = '';
                    //         var image = emp.photo
                    //         var doctor_name = '';
                    //         console.log(image);
                    //         var photoSrc;
                    //         var PatientPhoto = $('#hdnPatientPhoto').val();
                    //         console.log(PatientPhoto)
                    //         if ($.trim(image) == "" || image == null) {
                    //             photoSrc = "/Content/img/profile_icon.png";
                    //         }
                    //         else {
                    //             photoSrc = PatientPhoto + image;
                    //         }

                    //         Pname = emp.first_name;
                    //         gender = emp.gender;
                    //         dob = emp.DOB;
                    //         age = emp.age;
                    //         bloodgroup = emp.patient_blood_group;
                    //         lastvisit = emp.last_visit;
                    //         nextvisit = emp.next_visit;
                    //         Phoneno = emp.phone_number_1;
                    //         coupon_id = emp.coupon_id;
                    //         if (gender == 1) {
                    //             gender = 'Male';
                    //         }
                    //         else if (gender == 2) {
                    //             gender = 'Female';
                    //         }
                    //         else if (gender == 3) {
                    //             gender = 'Others';
                    //         }
                    //         else {
                    //             gender = '-';
                    //         }

                    //         if (dob == "" || dob == null) {
                    //             if (age == "" || age == null) {
                    //                 age = '-'
                    //                 ages = age + ' years';
                    //             }
                    //             else {
                    //                 ages = age;
                    //                 ages = age + ' years';
                    //             }
                    //         }
                    //         else {
                    //             dob = new Date(dob);
                    //             var today = new Date();
                    //             var ageval = '';
                    //             ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                    //             age = ageval + ' Years';
                    //             ages = age;
                    //         }
                    //         if (bloodgroup == '' || bloodgroup == null) {
                    //             bloodgroup = '-';
                    //         }
                    //         if (nextvisit == '' || nextvisit == null) {
                    //             nextvisit = '-';
                    //         }
                    //         if (lastvisit == '' || lastvisit == null) {
                    //             lastvisit = '-';
                    //         }
                    //         if (Phoneno == '' || Phoneno == null) {
                    //             Phoneno = '-';
                    //         }
                    //         j++;
                    //         var doctor_patient_id = '-';
                    //         if (emp.doctor_patient_id != '' && emp.doctor_patient_id != null) {
                    //             doctor_patient_id = emp.doctor_patient_id;
                    //         }

                    //         var address_details = '-';

                    //         if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "-" + emp.pincode;
                    //         else if (emp.address_line_1 != null && emp.town_village != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.town_village + "-" + emp.pincode;
                    //         else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.pincode != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "-" + emp.pincode;
                    //         else if (emp.address_line_1 != null && emp.address_line_2 != null && emp.town_village != null) address_details = emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village;
                    //         else if (emp.town_village != null) address_details = emp.town_village;

                    //         var bookoption = '';
                    //         var bookoptionclass = '';
                    //         if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                    //             bookoption = 'disabled';
                    //             bookoptionclass = 'style="pointer-events: none;"';
                    //         }
                    //         var ipredirect = '', iptransfer = '', billingredirect = '', registerbranch = ''; primary_doctor = '', Patienthistory = '', InvestigationsHistory = '';
                    //         registerbranch = emp.register_branch_name;
                    //         primary_doctor = emp.primary_doctor;
                    //         ip_current_status = emp.ip_current_status;

                    //         if (registerbranch == '' || registerbranch == null) {
                    //             registerbranch = '-';
                    //         }
                    //         if (primary_doctor == '' || primary_doctor == null) {
                    //             primary_doctor = '-';
                    //         }

                    //         if (ip_current_status == '' || ip_current_status == null) {
                    //             ip_current_status = ''
                    //             var ipredirect = '<p><i class="fa fa-plus mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '">IP Admission</a></p>';
                    //         }
                    //         else {
                    //             ip_current_status = '<span class="label label-success">Admitted</span>';
                    //             var iptransfer = '<p><i class="fa fa-bed mr-5" aria-hidden="true"></i><a style="cursor:pointer;color: black;" class="btn_r" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '">IP Transfer</a></p>';
                    //             var billingredirect = '<p><i class="fa fa-file-text mr-5" aria-hidden="true"></i><a class="btn_r" style="cursor:pointer;color: black;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer;color:black;" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + '">View Receipt</a></p>';
                    //             doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                    //             Patienthistory = '<p class="btn_r" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Patient History</p>';
                    //             InvestigationsHistory = '<p class="btn_r" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Investigations History</p>';
                    //         }
                    //         var couponid = ''
                    //         if (coupon_id != null) {
                    //             couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
                    //         }
                    //         else {
                    //             couponid = ''
                    //         }
                    //         // patient history & Investigation history & package / coupn details

                    //         var packagecoupondetails = '<p class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Package / Coupon Details</p>'

                    //         var printcard = '<p><i class="fa fa-print mr-5"  aria-hidden="true"></i><a style="cursor:pointer"  data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);>Print ID Card</a></p>';

                    //         if ($('#hiddenRole_id').val() == "1" || $('#hiddenRole_id').val() == "5") {
                    //             PatientSearch = PatientSearch + '<div class=" col-md-3 col-sm-6 col-xs-12 pat-card mb-20">'
                    //+ '<div class="pat-box">'
                    //   + '<div class="row">'
                    //      + '<div class="col-sm-6 col-xs-6">'
                    //            + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6">'
                    //            + '<ul style="display:inline-flex" class="pull-right mr-5">'
                    //            + '<li class="" style="list-style-type:none;">'
                    //            + couponid
                    //             + '</li>'
                    //             + '<li class="" style="list-style-type:none;">'
                    //                     + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                    //                     //+'<span class="sr-only">edit</span>'
                    //                     + '</li>'
                    //                 + '<li class="dropdown" style="list-style-type:none;">'
                    //                     + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                    //                     + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                    //                         + '<div class="text-left">'
                    //                              + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                    //            + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                    //              + ipredirect
                    //             //patient history & Investigation history & package / coupon details
                    //             + Patienthistory
                    //             + InvestigationsHistory
                    //             + packagecoupondetails
                    //             + iptransfer
                    //             + billingredirect
                    //             + printcard
                    //             + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                    //         + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                    //            + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                    //     + '<div class="row">'
                    //         + '<div class="col-sm-12 patient-name">'
                    //            + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                    //        + '<div class="col-sm-8 col-xs-8 pr-0">'
                    //             + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                    //                 + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                    //            + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                    //                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                    //             + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                    //               + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                    //           + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                    //                 + '<p><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                    //         + '<div class="col-sm-4 col-xs-3 patient-img">'
                    //             + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"> </div> </div>'
                    //     + '<div class="row">'
                    //         + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                    //            // + '<p><span class="pat-heading">Doctor :  span> ' + primary_doctor + ' </p> </div>'
                    //             + doctor_name + '</div>'
                    //         + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                    //             + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                    //             + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                    //            + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                    //             + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                    //         }

                    //         else {
                    //             PatientSearch = PatientSearch + '<div class="col-md-3 col-sm-6 col-xs-12 pat-card mb-20">'
                    //+ '<div class="pat-box">'
                    //   + '<div class="row">'
                    //      + '<div class="col-sm-6 col-xs-6">'
                    //            + '<p class="label label-success admit">' + ip_current_status + '</p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6">'
                    //            + '<ul style="display:inline-flex" class="pull-right mr-5">'
                    //             + '<li class="" style="list-style-type:none;">'
                    //            + couponid
                    //             + '</li>'
                    //               + '<li class="" style="list-style-type:none;">'
                    //                     + '<a class="fa fa-edit btn_r mr-5" title="edit" data="" data-original-title="Edit" style="cursor:pointer" data-id="UM_6" data data-original-title="Edit"  data-id="UM_6" data-type="role_rights_edit" data-nav="redirect" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '"></a>'
                    //                     //+'<span class="sr-only">edit</span>'
                    //                     + '</li>'
                    //                 + '<li class="dropdown" style="list-style-type:none;">'
                    //                     + '<a href="#" class="dropdown-toggle" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-v" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a>'
                    //                     + '<div class="dropdown-menu support-menu" id="ushelpMenu">'
                    //                         + '<div class="text-left">'
                    //                              + '<p class="f14 UM_10 btn_r" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Vip List</p>'
                    //            + '<p class="f14 UM_9 btn_r" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Watch List</p>'
                    //              + ipredirect
                    //             //patient history & Investigation history & package / coupon details 
                    //             + Patienthistory
                    //             + InvestigationsHistory
                    //             + packagecoupondetails
                    //             + iptransfer
                    //             + billingredirect
                    //             + printcard
                    //           //  + '<p href="#" class="f14 UM_116 btn_r" data-btn="PaymentDetails-section" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Payment</p>'
                    //        // + '<p href="#" class="text-white f14" role="button" data-toggle="modal" onclick=\'collectpayment(\"' + emp.patient_id + '\",\"' + Pname + '\",\"' + Phoneno + '\",\"' + photoSrc + '\",\"' + gender + '\",\"' + ages + '\",\"' + ages + '\")\';><i class="fa fa-plus"></i>Payment</p></div></div><div class="col-md-12" style="color:#aaa;z-index: 0;"><div class="col-md-12 text-left mbot0 padding0">'
                    //            + '<p hidden><i class="fa fa-video-camera" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Video Call</p><p hidden><i class="fa fa-comment-o" style="color:#006400;" aria-hidden="true">&nbsp;&nbsp;</i>Chat</p></div></div></li></ul></div></div>'
                    //     + '<div class="row">'
                    //         + '<div class="col-sm-12 patient-name">'
                    //            + ' <h5>  <a  href="/casestudy/CaseStudyView?patient_id=' + emp.patient_id + '">' + Pname + '</a> </h5>  </div>'
                    //        + '<div class="col-sm-8 col-xs-8 pr-0">'
                    //             + '<div class="col-sm-12 col-xs-12 pl-0 patient-idnumber">'
                    //                 + '<h5> ' + emp.patient_id + ' | ' + doctor_patient_id + ' </h5> </div>'
                    //            + '<div class="col-sm-12 col-xs-12 pl-0 pr-0 pat-content">'
                    //                + '<p>  ' + ages + ' | ' + gender + ' | <i class="fa fa-tint" style="color:red;"></i> ' + bloodgroup + '</p> </div>'
                    //             + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                    //               + '<p><i class="fa fa-phone mr-5"></i>+91 ' + Phoneno + '</p></div>'
                    //           + '<div class="col-sm-12 col-xs-12 pl-0 pat-content">'
                    //                 + '<p><span class="pat-heading"> Branch : </span>' + registerbranch + '</p> </div> </div>'
                    //         + '<div class="col-sm-4 col-xs-3 patient-img">'
                    //             + '<img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"> </div> </div>'
                    //     + '<div class="row">'
                    //         + '<div class="col-sm-12 col-xs-12 pat-content pr-0 pat-list-doctor">'
                    //             //+ '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p> </div>'
                    //             + doctor_name + '</div>'
                    //         + '<div class="col-sm-6 col-xs-6 pr-0 pat-visit">'
                    //             + '<p class="pat-heading">Last VIsit : <br>' + lastvisit + '</p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-0 next-visit">'
                    //             + '<p><span class="pat-heading">Next VIsit :<br> </span><sapn class="green-color">' + nextvisit + '</sapn></p> </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-5 pr-0">'
                    //            + '<a class="btn pat-book-later btn_r" data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar mr-10"></i>Book later</a>  </div>'
                    //         + '<div class="col-sm-6 col-xs-6 pl-0 pr-5">'
                    //             + '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn pat-book-now UM_7" data-id="UM_7" data-type="role_rights_function" data-nav="" data-name=""><i class="fa fa-calendar mr-10"></i>Book Now</a> </div> </div> </div> </div>'

                    //         }
                    //     });


                    var row_data = '';

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

                        var gender = '', dob = '', age = '', ages = '', bloodgroup = '', Phoneno = '', registerbranch = ''; primary_doctor = ''; ip_current_status = '', icon_details = '', coupon_id = '', visit_type_status = '';
                        var doctor_name = '',PtImage=''
                        var last_name = ''
                        var sec_mobile_no = ''
                        var image = emp.photo
                        console.log(image);
                        var photoSrc;
                        var PatientPhoto = $('#hdnPatientPhoto').val();
                        console.log(PatientPhoto)
                        if ($.trim(emp.PatientImage) == "" || emp.PatientImage == null) {
                            photoSrc = "/Content/img/profile_icon.png";
                        }
                        else {
                            //photoSrc = PatientPhoto + image;
                            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage;
                            photoSrc = PtImage;
                        }

                        gender = emp.gender;
                        dob = emp.DOB;
                        age = emp.age;
                        bloodgroup = emp.patient_blood_group;
                        last_name = emp.last_name;
                        Phoneno = emp.phone_number_1;
                        sec_mobile_no = emp.second_phone_number;
                        registerbranch = emp.register_branch_name;
                        primary_doctor = emp.primary_doctor;
                        ip_current_status = emp.ip_current_status;
                        coupon_id = emp.coupon_id;
                        visit_type_status = emp.visit_type_status;


                        if (gender == 1) {
                            gender = 'Male';
                        }
                        else if (gender == 2) {
                            gender = 'Female';
                        }
                        else if (gender == 3) {
                            gender = 'Others';
                        }
                        else {
                            gender = '-';
                        }

                        if (dob == "" || dob == null) {
                            if (age == "" || age == null) {
                                age = '-'
                                ages = age + ' years';
                            }
                            else {
                                ages = age;
                                ages = age + ' years';
                            }
                        }
                        else {
                            dob = new Date(dob);
                            var today = new Date();
                            var ageval = '';
                            ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                            age = ageval + ' Years';
                            ages = age;
                        }
                        if (bloodgroup == '' || bloodgroup == null) {
                            bloodgroup = '-';
                        }
                        if (registerbranch == '' || registerbranch == null) {
                            registerbranch = '-';
                        }
                        if (last_name == '' || last_name == null) {
                            last_name = '-';
                        }
                        if (Phoneno == '' || Phoneno == null) {
                            Phoneno = '-';
                        }
                        if (sec_mobile_no == '' || sec_mobile_no == null) {
                            sec_mobile_no = '-';
                        }
                        if (primary_doctor == '' || primary_doctor == null) {
                            primary_doctor = '-';
                        }


                        if (emp.vip_description != null && emp.vip_status == "1")
                            icon_details = icon_details + '<span class="waitlist-icon"><i class="fa fa-star" style="color:#3276b1;font-size:13px;" title="VIP"></i></span>';

                        var watchlist_end_date = new Date(emp.watchlist_end_date);
                        var currentdate = new Date();

                        if (watchlist_end_date >= currentdate && emp.watchlist_status == "1")
                            icon_details = icon_details + '<i class="fa fa-eye mr-20" style="color:#00a65a;font-size:20px;" title="Watch List"></i>';

                        if (emp.is_app_installed == 1) {
                            icon_details = icon_details + '<i class="fa fa-mobile icon-design ml-10 mr-10" style="color:blue;font-size:20px;" title="Patient App Installed"></i>'
                        }

                        var bookoption = '';
                        var bookoptionclass = '';
                        if (emp.is_deleted == "1" || emp.is_deleted == "1") {
                            bookoption = 'disabled';
                            bookoptionclass = 'style="pointer-events: none;"';
                        }

                        var book_later = '<a class="btn btn-info btn-xs UM_8 btn_r" title="Book_Later" ' + bookoptionclass + bookoption + ' data-id="UM_8" data-type="role_rights_function" data-nav="redirect" data-name="/DirectPatientEnroll/AppointmentSlot?patient_id=' + emp.patient_id + "&PName=" + emp.first_name + '"><i class="fa fa-calendar-plus-o" aria-hidden="true"></i></a>'

                        var book_now = '<a onclick=direct_appointment_booking("' + emp.patient_id + '",this) class="btn btn-edit btn-xs UM_7" title="Book_Now"  class="btn btn-block btn-flat btn-edit btn-sm UM_7"  data-id="UM_7" data-type="role_rights_function" data-nav="" data-name="" ' + bookoptionclass + bookoption + '><i class="fa fa-calendar-check-o" aria-hidden="true"></i></a>'

                        var editpatient = '<p><a style="cursor:pointer"  class="btn_r btn-blue" data-id="UM_6" data-type="role_rights_edit" data-name="/DirectPatientEnroll?patient_id=' + emp.patient_id + '" data-nav="redirect" ><i class="fa fa-edit mr-5"></i>Patient Edit</a></p>';

                        var watchviplist = ''
                        //if ($('#hiddenRole_id').val() != 2) {
                        var watchviplist = '<p><a style="cursor:pointer" class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus mr-5"></i>Vip List</a></p>'
                            + '<p><a style="cursor:pointer" class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus mr-5"></i>Watch List</a></p>'
                        //}
                        //var watchviplist = '<p><a style="cursor:pointer" class="f14 UM_10 btn_r btn-blue" data-id="UM_10" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="VIPDetails-section" role="button" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"1")\';><i class="fa fa-plus mr-5"></i>Vip List</a></p>'
                        //    + '<p><a style="cursor:pointer" class="f14 UM_9 btn_r btn-blue" data-id="UM_9" data-type="role_rights_function" data-nav="popup" data-name="myPatientSearchModal" data-btn="WatchDetails-section" role="butt  on" data-toggle="modal" onclick= \'watchviplist(\"' + emp.patient_id + '\",\"' + Phoneno + '\",\"' + ages + '\",\"' + gender + '\",\"' + emp.first_name + '\",this,"2")\';><i class="fa fa-plus mr-5"></i>Watch List</a></p>'

                        var ipredirect = '', iptransfer = '', billingredirect = '', Patienthistory = '', InvestigationsHistory = '', createbill = '';

                        if (ip_current_status == '' || ip_current_status == null) {
                            ip_current_status = ''
                            if (visit_type_status == 1) {
                                var ipredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer" data-id="IP_AA1" data-type="role_rights_add" data-nav="redirect" data-name="/Ipmanagement/admitpatient?PatientId=' + emp.patient_id + '&branchId=' + emp.branch_id + '"><i class="fa fa-plus mr-5" aria-hidden="true"></i>IP Admission</a></p>';
                            }
                            var createbill = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/index?FPId=' + emp.patientid + '&FBId=' + emp.rbranch_id + '"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>Create Bill</a></p>'
                        }
                        else {
                            if (visit_type_status == 1) {
                                ip_current_status = '<span class="label label-success">Admitted</span>';
                            }
                            else {
                                ip_current_status = ''
                            }
                            var iptransfer = '<p></i><a style="cursor:pointer" class="btn_r btn-blue" data-id="IP_TOF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/transferorder?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=0&branch_id=' + emp.register_branch_id + '"><i class="fa fa-bed mr-5" aria-hidden="true">IP Transfer</a></p>';
                            var billingredirect = '<p><a class="btn_r btn-blue" style="cursor:pointer" data-id="RPT_A1" data-type="role_rights_add" data-nav="redirect" data-name="/BillingMaster/billing_receipt?FPId=' + emp.patient_id + '&FBId=' + emp.register_branch_id + '">Add Receipt</a></p><p><i class="fa fa-file-text mr-5"></i><a class="btn_r" style="cursor:pointer" data-id="RPT_V1" data-type="role_rights_view" data-nav="redirect" data-name="/BillingMaster/billing_receipt_view?FPId=' + emp.patient_id + ' &visit_type=' + visit_type_status + '"><i class="fa fa-file-text mr-5" aria-hidden="true"></i>View Receipt</a></p>';
                            doctor_name = '<p><span class="pat-heading">Doctor : </span> ' + primary_doctor + ' </p>'
                            var Patienthistory = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_PHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/patienthistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Patient History</a></p>';
                            var InvestigationsHistory = '<p><a class="btn_r btn-blue" style="cursor:pointer;" data-id="IP_IHF1" data-type="role_rights_function" data-nav="redirect" data-name="/Ipmanagement/InvestigationsHistory?Patient_Id=' + emp.patient_id + '&IPVisitReport_Id=' + emp.ip_visit_report_id + '&IPDischarge_Id=' + emp.ip_nursing_discharge + '&branch_id=' + emp.branch_id + '"><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Investigations History</a></p>';
                        }

                        // patient history & Investigation history & package / coupon details
                        var couponid = '', packagecoupondetails = ''
                        if (coupon_id != null) {
                            couponid = '<i class="fa fa-shield" style="color:#00a65a;width:20px;" title="Package available" aria-hidden="true"></i>'
                            packagecoupondetails = '<p class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i>Package / Coupon Details</p>'
                        }
                        else {
                            couponid = ''
                            packagecoupondetails = ''
                        }
                        // var packagecoupondetails = '<p><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;</i><a class="btn_r" style="cursor:pointer;" data-toggle="modal" data-target="#urpkgeView" onclick=package_view("' + emp.patient_id + '","' + emp.branch_id + '")>Package/Coupon Details</a></p>'

                        var printcard = '<p><a style="cursor:pointer" class="btn-blue" data-id="ID_F1" data-type="role_rights_function" data-name="" data-nav="" onclick=PrintCard("' + emp.patientid + '","' + emp.hospitalid + '","' + emp.branch_id + '",this);><i class="fa fa-print mr-5"  aria-hidden="true"></i>Print ID Card</a></p>';

                        var trB = '<div class="col-md-12 padding0"><div class="disp_if">' + book_later + book_now + ' <a href="#" class="dropdown-toggle pull-left btn-info-dots" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" title="Options" data="" data-original-title="Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu  info-dropdown" id=""> <div class="text-left">' + createbill + editpatient + billingredirect + ipredirect + iptransfer + Patienthistory + InvestigationsHistory + packagecoupondetails + watchviplist + printcard + '</div></div></div></div>';

                        if (visit_type_status == 1) {
                            $('#c_ip_status').removeClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        else {
                            $('#c_ip_status').addClass('hidden')
                            row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td class='hidden'>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                        }
                        // row_data = row_data + '<tr><td><div class="widget-user-image"><img class="img-circle" src="' + photoSrc + '" alt="User Avatar" onerror="changedefault(this)"></div></td><td>' + emp.patient_id + "</td><td class='table_name_space'>" + emp.first_name + icon_details + "</td><td>" + last_name + "</td><td>" + Phoneno + "</td><td>" + sec_mobile_no + "</td><td>" + ages + "</td><td>" + gender + "</td><td>" + bloodgroup + "</td><td>" + registerbranch + "</td><td>" + ip_current_status + "</td><td>" + doctor_name + "</td><td>" + trB + "</td></tr>";
                    });

                    $('#patientsearchtablebody').empty();
                    $('#patientsearchtable').dataTable().fnClearTable();
                    $('#patientsearchtable').dataTable().fnDestroy();
                    debugger;
                    $('#patientsearchtablebody').append(row_data);


                    datatable('patientsearchtable', 'Patient List', 'A4');
                    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();
                    var downloadfilename = "PatientList" + output;

                }
                else {
                    console.log(data);
                }
            }
            $('.da-load-patsearch').addClass('hide');
        }
    });
}


$('#SelDoctor').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "HDL", branch_id: $('#SelBranch').val() },
            success: function (data) {
                debugger;
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#Hdndoctor_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});


