
$(document).ready(function () {
    debugger;
    Hideshow();
    LoadBranch();
    if ($('#R_Type').val() != '' && $('#R_Type').val() != null && $('#R_Type').val() != 0) {
        if ($('#R_Type').val() == 1) {
            $('a[data-toggle=AppointmentType][data-title="WalkIn"]').addClass('active').removeClass('not-active');
            $('a[data-toggle=AppointmentType][data-title="Video"]').addClass('not-active').removeClass('active');
        }
        else {
            $('a[data-toggle=AppointmentType][data-title="Video"]').addClass('active').removeClass('not-active');
            $('a[data-toggle=AppointmentType][data-title="WalkIn"]').addClass('not-active').removeClass('active');
        }
        $('#AppointmentType').val(($('#R_Type').val() == '1') ? 'WalkIn' : 'Video');
    }
    var s = $('#AppointmentType').val();

});

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

function LoadBranch() {
    $('#SelBranch').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) {
            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());
                    //    if ($('#RBranchID').val() != '') {
                    //        $('#SelBranch').val($('#RBranchID').val())
                    //    }
                    //    LoadDoctor();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        if ($('#RBranchID').val() != '') {
                            $('#SelBranch').val($('#RBranchID').val())
                        }
                        $('#SelBranch').attr('disabled', true);
                        LoadDoctor();
                    }
                    else {
                        if ($('#RBranchID').val() != null && $('#RBranchID').val() != "") {
                            if ($('#RBranchID').val() != '') {
                                $('#SelBranch').val($('#RBranchID').val())
                            } 
                            LoadDoctor();
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

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

function LoadDoctor() {
    debugger;
    var hospitalId = $('#HospitalId').val();
    var DoctorId = $('#HiddenDoctorID').val();
    if ($('#hiddenRole_id').val() != "1" && $('#hiddenRole_id').val() != "5") {
        if (hospitalId != "" && hospitalId != "0") {
            var DoctorData = {
                Dml_Indicator: "HDS",
                hospital_id: hospitalId,
                branch_id: $('#SelBranch').val()
            }
        }
    }
    else {
        var DoctorData = {
            Dml_Indicator: "DO",
            doctor_id: DoctorId,
        }
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].doctor_name + '</option>';
                        }
                        $('#SelDoctor').append(default_opt + SelRole);
                        if (data1.length == 1) {
                            $('#SelDoctor').val(data1[0].doctor_name);
                            $('#Hdndoc_id').val(data1[0].doctor_id);
                            $("#SelDoctor").prop('disabled', true);
                           // AddAppiontment();
                        }
                        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();
                        $('#start_date').val(output);
                       AddAppiontment();

                        if ($('#HDid').val() != null && $('#HDid').val() != "") {
                            $("#SelDoctor").val($('#HDid').val());
                            $('#start_date').val($('#Happdate').val())
                            $("#SelDoctor").change();
                            $("#SelDoctor").prop('disabled', true);
                            $("#start_date").prop('disabled', true);
                        }
                    }
                }
                SelectHospital();
            }
            else {
                console.log(data1);
            }
        }
    });
}
$("#start_date").change(function () {
    $('#tblPatientAppiontment').empty();
    if ($.trim($('#start_date').val()).length > 0 && ($.trim($('#SelDoctor').val()) != "0")) {
        AddAppiontment();
    }
    else {
        var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
        $('#tblPatientAppiontment').append(values);
    }
});
$("#SelDoctor").change(function () {
    $('#tblPatientAppiontment').empty();
    if ($.trim($('#SelDoctor').val()) != "0" && $.trim($('#start_date').val()).length > 0) {
        AddAppiontment();
    }
    else {
        var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
        $('#tblPatientAppiontment').append(values);
    }
});


$('#btnSubmit').click(function () {
});
function AddAppiontment() {
    debugger;
    var Dml_Indicator;
    var d = new Date();
    var strDate = (d.getDate() < 10 ? "0" + d.getDate() : d.getDate()) + "/" + ('0' + (d.getMonth() + 1)).slice(-2) + "/" + d.getFullYear();
    console.log('--------------->firstdate' + strDate);

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

    if ($.trim($('#start_date').val()) == "") {
        $('#Pstart_date').show();
        $('#Pstart_date').fadeOut(8000);
        $('#Pstart_date').html('Select date');
        $('#start_date').focus();
        $('#start_date').val('');
        return false;
    }
    if (strDate == $('#start_date').val()) {

        Dml_Indicator = 'TAS';
    }
    else {
        Dml_Indicator = 'AS';
    }
    var start_date = $('#start_date').val();
    var FDate1 = start_date.split('/');
    start_date = FDate1[2] + "-" + FDate1[1] + "-" + FDate1[0]
    var start_date_check = new Date(start_date);
    var today_date = new Date();
    var AppointmentType = $.trim($('#AppointmentType').val());
    if (AppointmentType == 'Walk In' || AppointmentType == 'WalkIn') {
        AppointmentType = 1;
    }
    else if (AppointmentType == 'Video') {
        AppointmentType = 2;
    }
    else {
        AppointmentType = 3;
    }
    var AppiontmentData = {
        Schedule_date: start_date,
        doctor_id: $('#Hdndoc_id').val(),
        Dml_Indicator: Dml_Indicator,
        appointment_type: AppointmentType,
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(AppiontmentData),
        success: function (data) {
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                $('#tblPatientAppiontment').empty();
                if (jQuery.isEmptyObject((data1))) {
                    //alert(' Sorry, The values you entered are invalid.\n Please try again. ');
                }
                if (data1.length > 0) {
                    var PatientAppiontment = '';
                    var hospital_id = '';
                    var branch_id = '';
                    var j = 1;
                    for (var i = 0; i < data1.length; i++) {
                        debugger;
                        if (i == 0) {
                            //PatientAppiontment = PatientAppiontment + '<div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                            PatientAppiontment = PatientAppiontment + '<div class="col-md-12"><h3>' + data1[i].branch_name + '</h3></div><div class="clearfix"></div>';
                        }
                        else if (data1[i].hospital_id != hospital_id && data1[i].branch_id != branch_id) {
                            //PatientAppiontment = PatientAppiontment + '<div class="clearfix"></div><div class="col-md-12"><h3>' + data1[i].hospital_name + ' | ' + data1[i].town_village + '</h3></div><div class="clearfix"></div>';
                            PatientAppiontment = PatientAppiontment + '<div class="clearfix"></div><div class="col-md-12"><h3>' + data1[i].branch_name + '</h3></div><div class="clearfix"></div>';
                        }
                        else {
                        }
                        if ((data1[i].doctor_schedule_type == 1 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 7) && AppointmentType == 1) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1 "><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        else if ((data1[i].doctor_schedule_type == 2 || data1[i].doctor_schedule_type == 4 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6) && AppointmentType == 2) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        else if ((data1[i].doctor_schedule_type == 3 || data1[i].doctor_schedule_type == 5 || data1[i].doctor_schedule_type == 6 || data1[i].doctor_schedule_type == 7) && AppointmentType == 3) {
                            PatientAppiontment = PatientAppiontment + '<div class="col-xs-6 col-sm-2 col-md-1"><button type="button" class="btn btn-primary btn-xs" id=' + data1[i].doctor_appointment_slot_id + ' onclick="insert(' + data1[i].doctor_appointment_slot_id + ')"><i class="fa fa-clock-o" aria-hidden="true"> ' + data1[i].start_time + '</i></button></div>';
                        }
                        hospital_id = data1[i].hospital_id;
                        branch_id = data1[i].branch_id;
                        j++;
                    }
                    if (PatientAppiontment == '' || PatientAppiontment == null) {
                        var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                        $('#tblPatientAppiontment').append(values);
                    }
                    else {
                        var values = '<div class="NA" style="text-align:center;"><br/></div>';
                        $('#tblPatientAppiontment').append(PatientAppiontment + '</br>' + values);
                    }
                }
                else {
                    var values = '<div class="NA" style="text-align:center;"><h1 style="text-align:center;">No Slot Available</h1><br/></div>';
                    $('#tblPatientAppiontment').append(values);
                }
                $('#datePickToggle').css('display', 'block');
            }
            else {
                console.log(data1);
            }
        }
    });
}


function insert(id) {
    debugger;

    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 claim 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;
        //}
    }


    var AppointmentType = $.trim($('#AppointmentType').val());
    if (AppointmentType == 'Walk In' || AppointmentType == 'WalkIn') {
        AppointmentType = 1;
    }
    else if (AppointmentType == 'Video') {
        AppointmentType = 2;
    }
    else {
        AppointmentType = 3;
    }
    var Dml_indicator = 'FSC'
    if ($('#slotId').val() != '' && $('#slotId').val() != null) {
        Dml_indicator = 'FSR'
    }
    //Check Future Slot-Added by tharuni
    var doctor_data = {
        Patient_id: $('#Patient_Id').val(),
        doctor_id: $('#Hdndoc_id').val(),
        appointment_type: AppointmentType,
        Dml_Indicator: Dml_indicator
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(doctor_data),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                $('#tbl_apt_list tbody').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data1.length > 0) {
                        console.log(data1);
                        $('#appointment_list').modal('show');
                        $('#lst_pat_name').html($('#PName').html() + '/' + $('#Patient_Id').val());
                        $('#lst_pat_id').html($('#Patient_Id').val());
                        $('#lst_apt_type').html($.trim($('#AppointmentType').val()) == 'WalkIn'?'Walk-In':'Video');
                        $('#lst_slt_date').html($('#start_date').val());
                        $('#lst_slt_time').html($('#' + id).text());
                        $('#hdn_appointment_slt_id').val(id);
                        $('#hdn_appointment_type').val(AppointmentType);
                        var row = ''
                        $.each(data1, function (i, emp) {
                            row = row + '<tr id="tr_apt_' + i + '"><td>' + (i + 1) + '</td><td id="td_slt_date_' + (i + 1) + '">' + emp.slot_date + '</td><td id="td_slt_time_' + (i + 1) + '">' + emp.slot_time + '</td><td id="td_slt_act_' + (i + 1) + '"><a href="javascript:void(0);" onclick=Decline("' + $.trim($('#Patient_Id').val()) + '",' + emp.doctor_appointment_slot_id + ',' + emp.coupon_id + ',' + (i + 1) + ') class="mr-5 btn-sm btn-danger" title="Decline Appointment" data-trigger="hover" data-toggle="tooltip" data-original-title="Decline Appointment"><i class="fa fa-ban fa-sm" aria-hidden="true"></i></a></td><td class="hide" id="td_apt_id_' + (i + 1) + '">' + emp.doctor_appointment_slot_id + '</td><td class="hide" id="td_coupon_id_' + (i + 1) + '">' + emp.coupon_id + '</td></tr>'
                        });
                        $('#tbl_apt_list tbody').append(row);
                    }
                    else {
                        book_slot(id, AppointmentType);
                    }
                }
               
            }
        }
    })

}
//Decline Appointment 
function Decline(patient, slotId, couponid, id) {

    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", 'You Need to decline the appointment ?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 20000000,

          onShown: function (toast) {
              $("#confirmationRevertYes").click(function () {
                  var checkindata = {
                      coupon_id: couponid,
                      patient_id: patient,
                      doctor_appointment_slot_id: slotId,
                      Dml_Indicator: 'D'
                  }
                  $.ajax({
                      async: true,
                      type: 'POST',
                      url: '/Dashboard/Patient_checkin',
                      contentType: 'application/json; charset=UTF-8',
                      data: JSON.stringify(checkindata),
                      success: function (data) {
                          var data = JSON.parse(data);
                          if (data.msg == "Success") {
                              var data = data.data;
                              if (jQuery.isEmptyObject((data))) {

                              }
                              else {
                                  console.log(data);
                                  if (data[0].msg == "failure") {
                                      toastr.warning("Patient already visited");
                                  }
                                  else {

                                      toastr.success("Appointment decline Successfully");
                                      $('#td_slt_act_' + id).html('<span class="label-warning btn" style="padding:3px;font-size:10px;">Declained</span>')
                                  }

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

}
//Book button click function
$('#appointment_book').click(function () {
    book_slot($('#hdn_appointment_slt_id').val(), $('#hdn_appointment_type').val())
})


//Book Slot
function book_slot(id, AppointmentType) {
    var Dml_Indicator = "APP", Bookingtype = "DIAP";
    if ($('#slotId').val() != '' && $('#slotId').val() != null) {
        Dml_Indicator = "DAPP";
        Bookingtype = "REAP"
    }
    $('#shade_slot').show();

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

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


    $('#AppointmentID').val(id);
    var Patient_id = $('#Patient_Id').val();

    var doctor_referal_to_id = $('#HRefered_to_doctorid').val()
    var doctor_referal_id = $('#Hreferal_id').val()


    var DoctorData = {
        Dml_Indicator: Dml_Indicator,
        Patient_id: $('#Patient_Id').val(),
        doctor_name: $("#SelDoctor option:selected").html(),
        doctor_id: $('#Hdndoc_id').val(),
        doctor_appointment_slot_id: id,
        appointment_type: AppointmentType,
        slotId: $('#slotId').val(),
        Pname: $('#PName').html(),
        appointment_date: $('#start_date').val(),
        appointment_time: $('#txtAppointmentTiming').val(),
        created_by: $('#HiddenDoctorID').val(),
        source_booking: "1",
        payment_mode: "4",
        //hospital_id: $('#hospital_id').val()
        hospital_id: $('#HospitalId').val(),
        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(),
        Booking_type: Bookingtype,
        referal_to_doctorid: doctor_referal_to_id,
        referal_id: doctor_referal_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    console.log(data1);
                    if (data1[0].StringMsg == "0") {
                        toastr.warning(" Selected Slot is already booked for this Patient(Walk-in or Video)");
                        $('#shade_slot').hide();
                    }
                    else if (data1[0].StringMsg == 'already in ip') {
                        toastr.warning('Patient Already Admitted in IP');
                        setTimeout(function () {
                            window.location.href = "/Dashboard";
                        }, 3000);
                    }
                    else if (data1[0].StringMsg == 'already') {
                        toastr.warning('Already you have Appointment on ' + data1[0].Slotdate);
                        setTimeout(function () {
                            window.location.href = "/Dashboard";
                        }, 3000);


                    }
                    else if (data1[0].StringMsg == 'already payment exits') {
                        toastr.warning('Payment already exists for the ' + (data1[0].old_appointment_type == "1" ? "Walkin" : "Video") + ' appointment. Please Cancel and then Rebook appointment.');
                        setTimeout(function () {
                            window.location.href = "/Dashboard";
                        }, 3000);
                    }
                    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 = $('#patphotopath').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);
                            $('#packname').html(data1[0].package_name);
                            $('#packcost').html(data1[0].price);
                            $('#Hdnpatient_id').val(data1[0].patient_id);
                            $('#appointment_id').val(data1[0].V_appointmentID);
                            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 {

                        if (Dml_Indicator == "DAPP") {
                            toastr.success("Appointment Rescheduled");
                            //setTimeout(function () {
                            //    location.reload();
                            //}, 3000);
                        }
                        else {
                            toastr.success("Appointment Booked");
                            //setTimeout(function () {
                            //    location.reload();
                            //}, 3000);
                        }


                        $('#appointment_id').val(data1[0].V_appointmentID);
                        //appiontmentsms(data1[0].phone_number_1);
                        DoctorMapping();
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}



function buy_coupon(id) {
    $('#appurpkgeView').modal('toggle');
    var package_data = {
        indicator_id: "ACI",
        coupon_id: id,
        patient_id: $('#Hdnpatient_id').val(),
        type_id: $('#appointment_id').val(),
        source_booking: "1",
        payment_mode: "1"
    }
    $.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 data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                var b = data1.Table;
                if (b[0].msg == "Success") {
                    toastr.success("Appointment Booked Successfully using Package Coupon");
                    DoctorMapping();
                }
                else {
                    toastr.warning("Something went wrong!");
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


function DoctorMapping() {
    debugger;
    $('#shade_slot').show();
    var Bookingtype = "DIAP";
    if ($('#slotId').val() != '' && $('#slotId').val() != null) {
        Bookingtype = "REAP"
    }

    var Patient_id = $('#Patient_Id').val();
    var DoctorData = {
        Dml_Indicator: "MP",
        Patient_id: $('#Patient_Id').val(),
        doctor_id: $('#Hdndoc_id').val(),
        doctor_appointment_slot_id: $('#AppointmentID').val(),
        Booking_type: Bookingtype
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientMapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                debugger;
                var phone_number_1 = '';
                var hospitalName = '';
                var doctorID = '';
                var doctorQualification = '';
                if (jQuery.isEmptyObject((data))) {

                }
                else {
                    for (var i = 0; i < data.length; i++) {
                        phone_number_1 = data[0].phone_number_1;
                        $('#txtDusername1').val(data[0].doctor_name);
                        hospitalName = data[0].hospital_name;
                        doctorID = data[0].doctor_id;
                        doctorQualification = data[0].qualification_name;
                    }
                }
                debugger
                var ChkForm = CheckConsulationRights($('#Patient_Id').val(), 34, 5, $('#Hdndoc_id').val(), $('#AppointmentID').val(), 0, $('#SelBranch').val());
                $.when(ChkForm)
          .then(function (data3) {
              var data2 = JSON.parse(data3);

              if (jQuery.isEmptyObject((data2.data))) {
                  window.location.href = "/Dashboard";
              }
              else {
                  debugger;
                  if (data2.data.Table[0].StringMsg != "Rights") {
                      window.location.href = "/Dashboard";
                  }
              }
          });
                
                //appiontmentsms(phone_number_1, hospitalName, doctorID, doctorQualification);
            }
            else {
                console.log(data);
            }
        }
    });
}
//Form Close Funtion-Added by Tharuni
$('#formClose').click(function () {
    window.location.href = "/Dashboard";
})

$('#iframeFormpopup').on('hidden.bs.modal', function () {
    debugger
    window.location.href = "/Dashboard";
});

function appiontmentsms(phone_number_1, hospitalName, doctorID, doctorQualification) {
    var hospital_name = hospitalName;
    var doctor_id = doctorID;
    var doctor_qualification = doctorQualification;
    var doctorName = $('#txtDusername1').val();
    var patientName = $('#PName').html();
    var date = $('#start_date').val();
    var message = '';
    var app_url = "https://goo.gl/RWDUwi";
    if ($('#HProductCode').val() == "2") {
        app_url = "https://tinyurl.com/6jq3qe4o";
    }
    if (doctor_id == "USD00047") {
        message = "Hi " + patientName + ". Your appointment with " + doctorName + " " + doctor_qualification + " " + hospital_name + " has been scheduled on " + date + ". Download application from " + app_url + " to manage your diabetes";

    }
    else {
        message = "Hi " + patientName + ", Your appointment with " + doctorName + " has been scheduled for " + date + ". Download application from " + app_url + " to manage your diabetes"

    }
    var sms = {
        phone: phone_number_1,
        message: message
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/sms',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sms),
        success: function (data) {
            window.location.href = "/Dashboard";
        }
    })
}

function SelectHospital() {
    var HospitalData = {
        Dml_Indicator: "HS",
        doctor_id: $('#HiddenDoctorID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HospitalData),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                var data = data.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    //var default_opt = '<option value="0">All</option>';
                    var SelHospital = '';
                    if (data.length > 0) {
                        var SelRole = '';
                        $('#hospital_id').empty();
                        for (var i = 0; i < data.length; i++) {
                            //$('#hospital_id').val(data[i].hospital_id);
                            SelRole = SelRole + '<option value="' + data[i].hospital_id + '">' + data[i].hospital_name + '</option>';
                        }

                        $('#hospital_id').append(SelRole);
                    }
                }
            }
            else {
                console.log(data);
            }
        }

    });


}
function timeToMins(time) {

    var b = time.split(':');
    return b[0] * 60 + +b[1];
}
function timeFromMins(mins) {
    function z(n) { return (n < 10 ? '0' : '') + n; }
    var h = (mins / 60 | 0) % 24;
    var m = mins % 60;
    return z(h) + ':' + z(m);
}

// Add two times in hh:mm format
function addTimes(t0, t1) {

    return timeFromMins(timeToMins(t0) + timeToMins(t1));
}

function converthourstoseconds(hms) {
    var hms = hms;   // your input string
    var a = hms.split(':'); // split it at the colons

    // minutes are worth 60 seconds. Hours are worth 60 minutes.
    var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
    //console.log('sec----' + seconds);
    hms = seconds;
    return hms;
}


function btnaddslot(str_time) {
    debugger;
    if ($.trim($('#SelDoctor').val()) == "0") {
        $('#PSelDoctor').show();
        $('#PSelDoctor').fadeOut(8000);
        $('#PSelDoctor').html('Select Doctor');
        $('#SelDoctor').focus();
        $('#SelDoctor').val('');
        return false;
    }
    if ($.trim($('#start_date').val()) == "") {
        $('#Pstart_date').show();
        $('#Pstart_date').fadeOut(8000);
        $('#Pstart_date').html('Select Date');
        $('#start_date').focus();
        $('#start_date').val('');
        return false;
    }



    var AppointmentType = $.trim($('#AppointmentType').val());

    if (AppointmentType == 'Walk In' || AppointmentType == 'WalkIn') {
        AppointmentType = 1;
    }
    else if (AppointmentType == 'Video') {
        AppointmentType = 2;
    }
    else {
        AppointmentType = 3;
    }

    $('#btnaddslot').hide();
    var times = '';
    if (str_time == 1) {
        let today = new Date();
        let today_date = today.toISOString().split('T')[0];
        var todaydate = today_date.split("-").reverse().join("/");
        let appointment_date = ($.trim($('#start_date').val()));
        if (todaydate != appointment_date) {
            toastr.warning("Add Next One hour slot is Avalaible only for the Current Date.");
            $('#btnaddslot').show();
            return false;

        }
        var dt = new Date();
        var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
        times = time.split(':');
        if (times[1] >= 0 && times[1] < 15) {
            times[1] = 15;
        }
        else if (times[1] >= 15 && times[1] < 30) {
            times[1] = 30;
        }
        else if (times[1] >= 30 && times[1] < 45) {
            times[1] = 45;
        }
        else {
            times[1] = '00';
            times[0] = parseInt(times[0]) + parseInt(1);
        }
        var to_time = '';
        if (times[0] != 23) {
            to_time = (parseInt(times[0]) + parseInt(1)) + ':' + times[1];
        }
        else {
            to_time = 00 + ':' + times[1];
        }

        times = times[0] + ':' + times[1] + ':00';
    }
    else {
        times = str_time + ':00';
        to_time = '00:00';
    }

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

    $('#tblPatientAppiontment').addClass('us-db-loader-history-inv');
    var HospitalData = {
        Dml_Indicator: "I",
        doctor_id: $('#Hdndoc_id').val(),
        //hospital_id: $('#hospital_id').val(),
        hospital_id: $('#HospitalId').val(),
        schedule_date: date,
        from_time: date + " " + from_time,
        to_time: date + " " + to_time + ":00",
        per_patient_time: '15',
        schedule_status: 1,
        doctor_schedule_type: AppointmentType,
        branch_id: $('#SelBranch').val(),
        doctoruserid: $('#Hdndoc_id_userid').val()
    }
    //var doctorScheduleId = 1;
    //Slotinsert(doctorScheduleId, from_time, to_time, date);

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

                }
                else {
                    if (data.length > 0) {
                        var doctorScheduleId = data[0].StringMsg;
                        Slotinsert(doctorScheduleId, from_time, to_time, date);
                    }

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

}
function Slotinsert(doctorScheduleId, from_time, to_time, date) {
    for (var i = 0; i < 4; i++) {
        var indiSlotSTime = from_time;
        var indiSlotETime = addTimes(from_time, '00:15:00');
        from_time = indiSlotETime;
        var to_time = indiSlotSTime.split(':');
        indiSlotSTime = to_time[0] + ':' + to_time[1];
        var SlotData = {
            doctor_schedule_id: doctorScheduleId,
            slot_start_time: date + " " + indiSlotSTime + ":00",
            slot_end_time: date + " " + indiSlotETime + ":00",
            doctor_appointment_slot_status: "3",
            Dml_Indicator: "I",
            doctor_id: $('#Hdndoc_id').val(),
            schedule_type: ($.trim($('#AppointmentType').val()) == 'WalkIn') ? 1 : 2,
            doctoruserid: $('#Hdndoc_id_userid').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/CalendarConfiguration/DoctorAppointmentSlot',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(SlotData),
            success: function (data) {
                AddAppiontment();
            }

        });
        indiSlotSTime = indiSlotETime;

    }
    $('#btnaddslot').show();
    $('#tblPatientAppiontment').removeClass('us-db-loader-history-inv');
}



$('#btnpick').click(function () {
    var str_time = $('#Ptime').val();
    //str_time = str_time.split('AM');
    //str_time = str_time[0].split('PM');
    //  btnaddslot(str_time[0]);


    var time = $("#Ptime").val();
    var hours = Number(time.match(/^(\d+)/)[1]);
    var minutes = Number(time.match(/:(\d+)/)[1]);
    var AMPM = time.match(/\s(.*)$/)[1];
    if (AMPM == "PM" && hours < 12) hours = hours + 12;
    if (AMPM == "AM" && hours == 12) hours = hours - 12;
    var sHours = hours.toString();
    var sMinutes = minutes.toString();
    if (hours < 10) sHours = "0" + sHours;
    if (minutes < 10) sMinutes = "0" + sMinutes;
    btnaddslot(sHours + ":" + sMinutes);
    $('#ba-btn-cancel').click();
});

//coupon popup close
$('.pack_close').click(function () {
    debugger;
    var DoctorData = {
        doctor_appointment_slot_id: $('#AppointmentID').val(),
        Dml_Indicator: 'PC'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DirectPatientEnroll/DirectPatientAppointment',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data1[0].msg == 'Success') {
                        toastr.success("Appointment Booked Successfully");
                        window.location.href = "/Dashboard";
                    }
                }
            }
        }
    })
})

// Claim Start //

$("#Entity_yes").click(function () {
    debugger
    $('#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);
});

$('#EntityType').change(function () {
    debugger
    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 --Added by tharuni
function Corporate_Insurance(Corporateid, CIid) {
    var dml = '', EntityType = $('#EntityType').val();

    if (EntityType == 1) {
        //dml = 'ITPA'    //commented by nandhini and new indicator from book now functionality
        dml = 'PITPA'
    }
    else if (EntityType == 2) {
        //dml = 'CIN'
        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 Hideshow() {
    debugger;
    var show = {
        dml_indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(show),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            $('#hclaimstatus').empty();
            $('#hclaimvisit').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;
                var claimvisit = data.data.Table[27].master_vist_type_id;
                var claimstatus = data.data.Table[27].status;
                $('#hclaimstatus').val(claimstatus);
                $('#hclaimvisit').val(claimvisit);
                if ($('#hclaimstatus').val() == 0 && $('#hclaimvisit').val() == 28) {
                    debugger;
                    $('#patient_claim').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;
                $('#Hdndoc_id').val('');
                $('#Hdndoc_id_userid').val('');
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid, doctor_user_id: item.doctor_user_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Hdndoc_id').val(ui.item.id);
        $('#Hdndoc_id_userid').val(ui.item.doctor_user_id);
        AddAppiontment();
       // 
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
