$(document).ready(function () {
    debugger;
    if ($('#ReferralCodeID').val().length == "")
    {
        //toastr.warning("Kindly contact support team");
        alert("Kindly contact support team");
        window.location.href = '/Dashboard';
    }
    else
    {
        LoadDepartment();
        LoadDoctor();
        var cname = 'logindetails';
        var doctor_details = getCookie(cname);
        debugger;
        var logindetails = doctor_details.split('=');
        logindetails = logindetails[1];
        logindetails = logindetails.split('$');
        console.log("---------------------------------------------------");
        console.log(logindetails);
        for (var i = 0; i < logindetails.length; i++) {
            if (logindetails[5] == "null") {
                logindetails[5] = null;
            }
            $("#txtOfficerID").val(logindetails[5]);
        }
    }
});


function getCookie(cname) {
    debugger;
    console.log(cname);
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function LoadDepartment() {
    var DoctorData = {
        Dml_Indicator: 'S',
        referral_hospital_code_id: $('#ReferralCodeID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/DepartmentList',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data)
                var tr = '';
                var SelDepartment = '';
                $('#txtDepartment').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++;
                        SelDepartment = SelDepartment + '<option value="' + data1[i].department_id + '">' + data1[i].department_name + '</option>';
                    }
                    $('#txtDepartment').append(default_opt + SelDepartment);
                }
            }

            LoadClassification();

        }
    });
}

function LoadDoctor() {
    var DoctorData = {
        Dml_Indicator: "DLAS",
        doctor_id: $('#HDoctorID').val(),
        user_created_by: $('#hiddenrole_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var tr = '';
                    var SelRole = '';
                    $('#doc_list').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';
                        }
                        $('#doc_list').html(default_opt + SelRole);
                        if (j == 1) {
                            $('#doc_list').val(data1[0].doctor_id);
                            $("#txtPaitentSearch").attr("disabled", false);
                            load_doctordetails();
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#doc_list').change(function () {
    load_doctordetails();
})
function load_doctordetails(){
    $("#txtPaitentSearch").attr("disabled", false);
    var DoctorData = {
        Dml_Indicator: "DLASS",
        doctor_id: $('#doc_list').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            $('#txtDoctorName').val(data1[0].doctor_name);
                            $('#txtDoctorPhoneNumber').val(data1[0].doctor_phone_number);
                            $('#txtHospitalName').val(data1[0].hospital_name);
                            $('#txtdoctor_emailid').val(data1[0].email_id);
                            $('#txtdoctor_webtoken').val(data1[0].web_token);
                            $('#txtdoctor_appoken').val(data1[0].app_token);
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#txtDepartment').change(function () {
    if ($('#txtDepartment').val() != "" && $('#txtDepartment').val() != null && $('#txtDepartment').val() != 0) {
        LoadReferralDoctorUsers();
    }
    else {
        $('#SelDoctor').empty();
    }
});

function LoadReferralDoctorUsers() {
    var DoctorData = {
        Dml_Indicator: 'DUL',
        referral_hospital_code_id: $('#ReferralCodeID').val(),
        department: $('#txtDepartment').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralDoctorUsers',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data)
                var tr = '';
                var SelDoctor = '';
                $('#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++;
                        SelDoctor = SelDoctor + '<option value="' + data1[i].user_id + '">' + data1[i].doctor_name + '</option>';
                    }
                    $('#SelDoctor').append(default_opt + SelDoctor);
                }
            }


        }
    });
}

function LoadClassification() {
    var classificationData = {
        Dml_Indicator: 'S',
        referral_hospital_code_id: $('#ReferralCodeID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralClassification',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(classificationData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                debugger;
                var data1 = JSON.parse(data)
                var tr = '';
                var SelClassification = '';
                $('#txtClassification').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++;
                        SelClassification = SelClassification + '<option value="' + data1[i].id + '">' + data1[i].classification_description + '</option>';
                    }
                    $('#txtClassification').append(default_opt + SelClassification);


                    var cname = 'logindetails';
                    var doctor_details = getCookie(cname);
                    debugger;
                    var logindetails = doctor_details.split('=');
                    logindetails = logindetails[1];
                    logindetails = logindetails.split('$');
                    console.log("---------------------------------------------------");
                    console.log(logindetails);
                    for (var i = 0; i < logindetails.length; i++) {
                        $("#txtClassification").val(logindetails[4]);
                    }
                }
            }

            LoadHospitalName();

        }
    });
}

function LoadHospitalName() {
    var hospitalData = {
        Dml_Indicator: 'HS',
        referral_hospital_code_id: $('#ReferralCodeID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralClassification',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(hospitalData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                debugger;
                var data1 = JSON.parse(data);               
                if (data1.length > 0) {
                    var hospital_name = data1[0].referral_hospital;
                    $('#txtReferredHospital').val(hospital_name);
                    
                }
            }

        }
    });
}

//$('#SelDoctor').change(function () {
//    if ($('#SelDoctor').val() == null || $('#SelDoctor').val() == "" || $('#SelDoctor').val() == 0) {
//        $('#txtReferredHospital').val('');
//        return false;
//    }

//    $('#txtReferredHospital').val($('#SelDoctor').val());
//});


$('#btnSubmit').click(function () {
    //$('#btnSubmit').prop('disabled', true);
    if (($('#val_checknewpatient').prop("checked") == true))
    {
        patient_creation();
    }
    else
    {
        insert_referral();
    }
});
function insert_referral()
    {
    debugger;
    if ($.trim($('#doc_list').val()) == "" || $.trim($('#doc_list').val()) == 0) {
        $('#Pdoc_list').show();
        $('#Pdoc_list').fadeOut(8000);
        $('#Pdoc_list').html('Select Doctor Name');
        $('#doc_list').focus();
        $('#doc_list').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }
    if ($.trim($('#txtPatientID').val()) == "") {
        $('#PtxtPatientID').show();
        $('#PtxtPatientID').fadeOut(8000);
        $('#PtxtPatientID').html('Select Patient ID');
        $('#txtPatientID').focus();
        $('#txtPatientID').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }
    if ($.trim($('#txtDepartment').val()) == "" || $('#txtDepartment').val() == 0) {
        $('#PtxtDepartment').show();
        $('#PtxtDepartment').fadeOut(8000);
        $('#PtxtDepartment').html('Select Department');
        $('#txtDepartment').focus();
        $('#txtDepartment').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }

    if ($.trim($('#SelDoctor').val()) == "" || $('#SelDoctor').val() == 0) {
        $('#PSelDoctor').show();
        $('#PSelDoctor').fadeOut(8000);
        $('#PSelDoctor').html('Select Referred To');
        $('#SelDoctor').focus();
        $('#SelDoctor').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }

    


    if ($.trim($('#txtReferredReason').val()) == "") {
        $('#PtxtReferredReason').show();
        $('#PtxtReferredReason').fadeOut(8000);
        $('#PtxtReferredReason').html('Enter Referred Reason');
        $('#txtReferredReason').focus();
        $('#txtReferredReason').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }

    var CaseDetailsData = {
        dml_indicator: "I",
        patient_id: $('#txtPatientID').val(),
        individual_id: $('#txtIndividualID').val(),
        patient_name: $('#txtPatientName').val(),
        age: $('#txtAge').val(),
        dob: $('#txtDOB').val(),
        gender: $('#txtGender').val(),
        blood_group: $('#txtBloodGroup').val(),
        phone_number_1: $('#txtPhoneNo1').val(),
        phone_number_2: $('#txtPhoneNo2').val(),
        address_line_1: $('#txtAddressLine1').val(),
        address_line_2: $('#txtAddressLine2').val(),
        town_village: $('#txtTown').val(),
        city: $('#txtCity').val(),
        state: $('#txtState').val(),
        country: $('#txtCountry').val(),
        doctor_id: $('#doc_list').val(),
        doctor_name: $('#txtDoctorName').val(),
        doctor_phone_number: $('#txtDoctorPhoneNumber').val(),
        hospital_name: $('#txtHospitalName').val(),
        referred_reason: $('#txtReferredReason').val(),
        refered_to: $("#SelDoctor option:selected").text(),
        department: $('#txtDepartment option:selected').val(),
        case_report_filepath: "",
        classification: $('#txtClassification option:selected').text(),
        referred_hospital: $('#txtReferredHospital').val(),
        created_by: $('#HDoctorID').val(),
        referral_code_id: $('#ReferralCodeID').val(),
        referred_to_id: $('#SelDoctor').val(),
        officer_id: $("#txtOfficerID").val(),
        doctor_email_id: $("#txtdoctor_emailid").val(),
        mobile_fcm_token: $("#txtdoctor_appoken").val(),
        web_fcm_token: $("#txtdoctor_webtoken").val(),
        summary_treatment: $('#txtReferredsummarytreatment').val(),
        patient_response_trtment: $('#txtpatientresponse').val(),
        further_treatment: $('#txtplantrtment').val(),
        recommendations: $('#txtRecommendations').val(),
        next_contact: $('#txtnextcontact').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/CaseDetailsIns_Upd',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(CaseDetailsData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
                $('#btnSubmit').prop('disabled', false);
                //toastr.warning('Something went wrong. Please try after sometime');
                alert('Something went wrong. Please try after sometime');
            }
            else {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var case_date = {
                        dml_indicator: "I",
                        patient_id: data1.data[0].patient_id,
                        individual_id: data1.data[0].individual_id,
                        patient_name: data1.data[0].patient_name,
                        age: data1.data[0].age,
                        dob: data1.data[0].dob,
                        gender: data1.data[0].gender,
                        blood_group: data1.data[0].blood_group,
                        phone_number_1: data1.data[0].phone_number_1,
                        phone_number_2: data1.data[0].phone_number_2,
                        address_line_1: data1.data[0].address_line_1,
                        address_line_2: data1.data[0].address_line_2,
                        town_village: data1.data[0].town_village,
                        city: data1.data[0].city,
                        state: data1.data[0].state,
                        country: data1.data[0].country,
                        doctor_id: data1.data[0].doctor_id,
                        doctor_name: data1.data[0].doctor_name,
                        doctor_phone_number: data1.data[0].doctor_phone_number,
                        hospital_name: data1.data[0].hospital_name,
                        referred_reason: data1.data[0].referred_reason,
                        refered_to: data1.data[0].refered_to,
                        department: data1.data[0].department,
                        classification: data1.data[0].classification,
                        referred_hospital: data1.data[0].referred_hospital,
                        created_by: data1.data[0].created_by,
                        referral_code_id: data1.data[0].referral_code_id,
                        referred_to_id: data1.data[0].referred_to_id,
                        officer_id: data1.data[0].officer_id,
                        doctor_email_id: data1.data[0].doctor_email_id,
                        mobile_fcm_token: data1.data[0].mobile_fcm_token,
                        web_fcm_token: data1.data[0].web_fcm_token,
                        summary_treatment: data1.data[0].summary_treatment,
                        patient_response_trtment: data1.data[0].patient_response_trtment,
                        further_treatment: data1.data[0].further_treatment,
                        recommendations: data1.data[0].recommendations,
                        next_contact: data1.data[0].next_contact,
                        case_id: data1.data[0].case_id
                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/ReferralManagement/DetailsIns_Upd',
                        contentType: 'application/json; charset=UTF-8',
                        data: JSON.stringify(case_date),
                        success: function (data) {
                            var data=JSON.parse(data);
                            if (data.msg == "Success") {
                                if (jQuery.isEmptyObject((data))) {
                                    $('#btnSubmit').prop('disabled', false);
                                    //toastr.warning('Something went wrong. Please try after sometime');
                                    alert('Something went wrong. Please try after sometime');
                                }
                                else {
                                    //toastr.success("Referred Successfully - Referral ID:" + data1.case_id);
                                    alert("Referred Successfully - Referral ID:" + data1.case_id);
                                    $('#txtPaitentSearch,#txtPatientID,#txtPatientName,#txtPhoneNo1,#txtBloodGroup,#txtReferredHospital,#txtReferredReason,#txtReferredsummarytreatment,#txtpatientresponse,#txtplantrtment,#txtRecommendations,#txtnextcontact,#txtDOB,#txtAge,#txtGender,#txtPhoneNo2,#txtDoctorName,#txtDoctorPhoneNumber,#txtHospitalName,#txtIndividualID,#txtAddressLine1,#txtAddressLine2,#txtTown,#txtCity,#txtState,txtCountry,#txtOfficerID').val('');
                                    $('#txtClassification,#txtDepartment,#SelDoctor').val('0');
                                    $("input[name='optradio1']:checked").prop("checked", false);
                                    $('.close').click();
                                    window.open('/ReferralManagement/ReferralPrint?CaseID=' + data1.case_id);
                                }
                            }
                            else {
                                console.log(data);
                            }
                        }
                        });
                }
                else {
                    //toastr.warning("Try again after some time");
                    alert("Try again after some time");
                }
             }
         }
    });
}
$("#referclose").click(function () {
    $('#txtPaitentSearch,#txtPatientID,#txtPatientName,#txtPhoneNo1,#txtBloodGroup,#txtReferredHospital,#txtReferredReason,#txtReferredsummarytreatment,#txtpatientresponse,#txtplantrtment,#txtRecommendations,#txtnextcontact,#txtDOB,#txtAge,#txtGender,#txtPhoneNo2,#txtDoctorName,#txtDoctorPhoneNumber,#txtHospitalName,#txtIndividualID,#txtAddressLine1,#txtAddressLine2,#txtTown,#txtCity,#txtState,#txtCountry,#txtOfficerID').val('');
    $('#txtpDOB').val('');
    $('#txtPAge').val('');
    $("#txtPatientName,#txtPhoneNo1,#txtBloodGroup,#txtpDOB,#txtPAge").attr('readonly', true); $("input[name='optradio1']").prop("disabled", true); $("input[name='optradio1']").prop("checked", false); $('#div_patsearch').show(); $('#txtBloodGroup').prop("disabled", true)
    $('#txtClassification,#txtDepartment,#SelDoctor').val('0');
    $("input[name='optradio1']:checked").prop("checked", false);
    $('#val_checknewpatient').prop("checked", false);
})

//referral history api
$('#UM_109').click(function () {
    debugger;
    get_history_data();
});

function get_history_data()
{
    debugger;
    $('#patient_list_table_body').empty();
    var CaseDetailsData = {
        dml_indicator: "RH"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralHistory',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(CaseDetailsData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    history_data_binding(data);
                }
            }
        },
    });
}

//biding the history data
function history_data_binding(data)
{
    $('#patient_list_table_body').empty();
    var j = 0;
    var data1 = JSON.parse(data);
    var b = data1.details, row_data = '';
    $.each(b, function (i, emp) {
        j++;
        var case_status = "";
        if (emp.case_status == "1") case_status = "Referred";
        else if (emp.case_status == "2") case_status = "Communication Inprogress";
        else if (emp.case_status == "3") case_status = "Admitted";
        else if (emp.case_status == "4") case_status = "Discharged";
        else if (emp.case_status == "5") case_status = "Lost";
        else case_status = "Withdrawal";
        if (emp.case_status == "1") {
            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.case_id + "</td><td>" + emp.patient_id + "/" + emp.patient_name + "/" + emp.phone_number_1 + "</td><td>" + emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "," + emp.city + "</td><td>" + emp.refered_to + "/" + emp.referred_hospital + "</td><td>" + emp.department + "/" + emp.classification + "</td><td> " + case_status + "</td><td><button class='fa fa-print' aria-hidden='true' onclick=casedetails_print('" + emp.case_id + "')></button>&nbsp;&nbsp;<button class='edit btn btn-default  btn-sm btn-add' onclick=WidthdrawReferralCase('" + emp.case_id + "')>Withdraw</button></td></tr>";
        }
        else {
            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.case_id + "</td><td>" + emp.patient_id + "/" + emp.patient_name + "/" + emp.phone_number_1 + "</td><td>" + emp.address_line_1 + "," + emp.address_line_2 + "," + emp.town_village + "," + emp.city + "</td><td>" + emp.refered_to + "/" + emp.referred_hospital + "</td><td>" + emp.department + "/" + emp.classification + "</td><td> " + case_status + "</td><td><button class='fa fa-print' aria-hidden='true' onclick=casedetails_print('" + emp.case_id + "')></button>&nbsp;&nbsp;<button class='edit btn btn-default  btn-sm btn-add' onclick=\"case_full_details(\'" + emp.case_id + "\')\"; data-toggle='modal' data-target='#moreinfomodal'>More Details</button></td></tr>";
        }
    });
    $('#patient_list_table_body').html(row_data)
}

//case full details modal
function case_full_details(id)
{
    var discharge_lost_casedetails_data = {
        dml_indicator: "MCD",
        case_id: id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralFullDetails',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(discharge_lost_casedetails_data),
        success: function (data) {
            $('#M_activity_table_data_body,#M_log_table_data_body,#morecase_iamge_view,#a_admit_iamge_view,#a_dis_iamge_view').empty();
            $('#m_case_id,#m_pat_name,#m_ph_no,#m_age,#a_notes,#m_dis_date,#m_f_advice,#m_dis_created_on,#m_notes,#m_diagnosis,#a_created_on,#a_dr_name,#m_gender,#m_bld_grp,#m_created_on,#a_type_admission,#a_date_admission,#a_con_dr_id,#a_con_dr_id,#m_dob,#m_d_name,#m_d_name,#m_d_ph_no,#m_hos_name,#m_classification,#m_department,#m_ref_to,#m_ref_reason').html('');
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data);
                if(data1.Table.length > 0)
                {
                    var gender = '', type_of_admission= '';
                    $.each(data1.Table, function (i, emp) {
                        $('#m_case_id').html(emp.case_id);
                        $('#m_pat_name').html(emp.patient_name);
                        $('#m_ph_no').html(emp.phone_number_1);
                        $('#m_age').html(emp.age);
                        if (emp.gender == "1") gender = "Male";
                        else if (emp.gender == "2") gender = "Female";
                        else gender = '-';
                        $('#m_gender').html(gender);
                        $('#m_dob').html(emp.dob);
                        $('#m_d_name').html(emp.doctor_name);
                        $('#m_d_ph_no').html(emp.doctor_phone_number);
                        $('#m_hos_name').html(emp.hospital_name);
                        $('#m_classification').html(emp.classification);
                        $('#m_department').html(emp.department);
                        $('#m_ref_to').html(emp.refered_to);
                        $('#m_ref_reason').html(emp.referred_reason);
                        var d, n, drloimage;
                        if (emp.case_report_filepath != null)
                        {
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnreferralfileviewpath').val() + $('#ReferralCodeID').val() + "/" + emp.case_report_filepath + '?' + n;
                            $('#morecase_iamge_view').append('<a href=" ' + drloimage + '" target="_blank">File</a>');
                        }
                        $('#m_bld_grp').html(emp.blood_group);
                        $('#m_created_on').html(emp.created_on);
                    });
                }
                if(data1.Table1.length > 0)
                {
                    var j = 0, row_data = '';
                    $.each(data1.Table1, function (i, emp) {
                        j++;
                        row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.log_notes + "</td><td>" + emp.created_on + "</td></tr>";
                    });
                    $('#M_log_table_data_body').html(row_data);
                }
                if (data1.Table2.length > 0) {
                    var j = 0, row_data = '', d, n, drloimage;;
                    $.each(data1.Table2, function (i, emp) {
                        j++;
                        if (emp.attachment_file != null) {
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnfileviewpath').val() + $('#HiddenReferralCodeID').val() + "/" + emp.attachment_file + '?' + n;
                            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.activity_type + "</td><td>" + emp.summary + "</td><td><a href=" + drloimage + " target='_blank'>File</a></td><td>" + emp.due_date + "</td><td>" + emp.assigned_to + "</td><td>" + emp.notes + "</td><td>" + emp.activity_status + "</td><td>" + emp.created_on + "</td></tr>";
                        }
                        else {
                            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.activity_type + "</td><td>" + emp.summary + "</td><td>-</a></td><td>" + emp.due_date + "</td><td>" + emp.assigned_to + "</td><td>" + emp.notes + "</td><td>" + emp.activity_status + "</td><td>" + emp.created_on + "</td></tr>";
                        }
                    });
                    $('#M_activity_table_data_body').html(row_data);
                }
                if (data1.Table3.length > 0) {
                    $.each(data1.Table3, function (i, emp) {
                        if (emp.type_of_admission == "1") type_of_admission = "In Patient";
                        else type_of_admission = "Out Patient";
                        $('#a_type_admission').html(type_of_admission);
                        $('#a_date_admission').html(emp.date_of_admission);
                        $('#a_con_dr_id').html(emp.consulting_doctor_id);
                        $('#a_dr_name').html(emp.doctor_name);
                        var d, n, drloimage;
                        if (emp.attachment_file != null) {
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnreferralfileviewpath').val() + $('#ReferralCodeID').val() + "/" + emp.attachment_file + '?' + n;
                            $('#a_admit_iamge_view').append('<a href=" ' + drloimage + '" target="_blank">File</a>');
                        }
                        $('#a_notes').html(emp.notes);
                        $('#a_created_on').html(emp.created_on);
                    });
                }
                if (data1.Table4.length > 0) {
                    $.each(data1.Table4, function (i, emp) {
                        $('#m_dis_date').html(emp.discharge_date);
                        $('#m_diagnosis').html(emp.diagnosis);
                        $('#m_notes').html(emp.notes);
                        $('#m_f_advice').html(emp.followup_advice);
                        var d, n, drloimage;
                        if (emp.attachment_file != null) {
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnreferralfileviewpath').val() + $('#ReferralCodeID').val() + "/" + emp.attachment_file + '?' + n;
                            $('#a_dis_iamge_view').append('<a href=" ' + drloimage + '" target="_blank">File</a>');
                        }
                        $('#m_dis_created_on').html(emp.created_on);
                    });
                }
            }
        },
    });
}

//cancel refferal
function WidthdrawReferralCase(case_id) {
    var CaseDetailsData = {
        dml_indicator: "W",
        case_id: case_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/ReferralManagement/ReferralHistory',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(CaseDetailsData),
        success: function (data) {
            if (jQuery.isEmptyObject((data))) {
            }
            else {
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    history_data_binding(data);
                }
            }
        }
    });
}


//referral history filter
$('#refstatus').change(function () {
    if($('#refstatus').val() == '') 
    {
        get_history_data();
    }
    else if($('#refstatus').val() == '1')
    {
        var value = "referred";
        history_filter(value);
    }
    else if ($('#refstatus').val() == '2') {
        var value = "communication inprogress";
        history_filter(value);
    }
    else if ($('#refstatus').val() == '3') {
        var value = "admitted";
        history_filter(value);
    }
    else if ($('#refstatus').val() == '4') {
        var value = "discharged";
        history_filter(value);
    }
    else if ($('#refstatus').val() == '5') {
        var value = "lost";
        history_filter(value);
    }
    else if ($('#refstatus').val() == '6') {
        var value = "withdrawal";
        history_filter(value);
    }
});

function history_filter(val)
{
    $("#patient_list_table_body tr").filter(function () {
        $(this).toggle($(this).text().toLowerCase().indexOf(val) > -1)
    });
}

//referral history filter ended

$('#UM_108').click(function () {
    window.location.href = "/DirectPatientEnroll?RefID=" + $('#ReferralCodeID').val()
});


//referral print
function casedetails_print(id)
{
    window.open('/ReferralManagement/ReferralPrint?CaseID=' + id);
}


$('#checknewpatient').click(function () {
    if (($('#val_checknewpatient').prop("checked") == true)) { $("#txtPatientName,#txtPhoneNo1,#txtBloodGroup,#txtpDOB,#txtPAge").removeAttr('readonly'); $('#txtPaitentSearch').attr('readonly', true); $("input[name='optradio1']").prop("disabled", false); $('#txtBloodGroup').prop("disabled", false); $('#div_patsearch').hide(); $('#txtpDOB').prop("disabled", false); }
    else { $("#txtPatientName,#txtPhoneNo1,#txtBloodGroup,#txtpDOB,#txtPAge").attr('readonly', true); $('#txtPaitentSearch').removeAttr('readonly'); $("input[name='optradio1']").prop("disabled", true); $("input[name='optradio1']").prop("checked", false); $('#div_patsearch').show(); $('#txtBloodGroup').prop("disabled", true); $('#txtpDOB').prop("disabled", true); }
});


//new patient creation

function patient_creation() {
    if ($.trim($('#doc_list').val()) == "" || $.trim($('#doc_list').val()) == 0) {
        $('#Pdoc_list').show();
        $('#Pdoc_list').fadeOut(8000);
        $('#Pdoc_list').html('Select Doctor Name');
        $('#doc_list').focus();
        $('#doc_list').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }
    if ($.trim($('#txtPatientName').val()) == "") {
        $('#PtxtPatientName').show();
        $('#PtxtPatientName').fadeOut(8000);
        $('#PtxtPatientName').html('Enter Patient Name');
        $("#PtxtPatientName").val('');
        $("#PtxtPatientName").focus();
        return false;
    }
    if ($.trim($('#txtPhoneNo1').val()) == "") {
        $('#PtxtPhoneNo1').show();
        $('#PtxtPhoneNo1').fadeOut(8000);
        $('#PtxtPhoneNo1').html('Enter Phone Number');
        $("#txtPhoneNo1").val('');
        $("#txtPhoneNo1").focus();
        return false;
    }
    if ($.trim($('#txtpDOB').val()) == "") {
        $('#PtxtpDOB').show();
        $('#PtxtpDOB').fadeOut(8000);
        $('#PtxtpDOB').html('Enter DOB');
        $("#txtpDOB").val('');
        $("#txtpDOB").focus();
        return false;
    }
    if ($.trim($("input[name='optradio1']:checked").val()) == "") {
        $('#PSelGender').show();
        $('#PSelGender').fadeOut(8000);
        $('#PSelGender').html('Select Gender');
        $("#PSelGender").val('');
        $("#PSelGender").focus();
        return false;
    }
    if ($.trim($('#txtDepartment').val()) == "" || $('#txtDepartment').val() == 0) {
        $('#PtxtDepartment').show();
        $('#PtxtDepartment').fadeOut(8000);
        $('#PtxtDepartment').html('Select Department');
        $('#txtDepartment').focus();
        $('#txtDepartment').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }

    if ($.trim($('#SelDoctor').val()) == "" || $('#SelDoctor').val() == 0) {
        $('#PSelDoctor').show();
        $('#PSelDoctor').fadeOut(8000);
        $('#PSelDoctor').html('Select Referred To');
        $('#SelDoctor').focus();
        $('#SelDoctor').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }
    if ($.trim($('#txtReferredReason').val()) == "") {
        $('#PtxtReferredReason').show();
        $('#PtxtReferredReason').fadeOut(8000);
        $('#PtxtReferredReason').html('Enter Referred Reason');
        $('#txtReferredReason').focus();
        $('#txtReferredReason').val('');
        $('#btnSubmit').prop('disabled', false);
        return false;
    }
    else {

        var dob = $('#txtpDOB').val();
        if (dob == '') {
            dob = '';
        }
        else {
            var a = dob.split('/');
            dob = a[2] + '-' + a[0] + '-' + a[1];
        }

        var DirectPatientData = {
            patient_first_name: $("#txtPatientName").val(),
            patient_phone_number: $.trim($("#txtPhoneNo1").val()),
            patient_blood_group: $("#txtBloodGroup").val(),
            Dml_Indicator: "I",
            dob: dob,
            age: $.trim($("#txtPAge").val()),
            product_code: "2",
            gender: $("input[name='optradio1']:checked").val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: 'DirectPatientEnroll/PatientEnroll',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DirectPatientData),
            success: function (data) {
                $('#reg-patient-details').html('');
                var data1 = JSON.parse(data);
                console.log(data1);
                if (data1.msg == "Success") {
                    var data1 = data1.data.Table;
                    if (jQuery.isEmptyObject((data))) {
                        toastr.warning('Entered Email Address\Mobile Number Already Exist');
                    }
                    else {
                        debugger;
                        console.log(data1);
                        $.each(data1, function (i, emp) {
                            var result = emp.StringMsg
                            if (result == 'Phone already registerd') {
                            }
                            else if (result == 'listofpatient') {
                                $('#customerRegistration').modal('show');
                                var tr = '';
                                for (var i = 0; i < data1.length; i++) {
                                    var gender = '-', address = '', dob = '-', image = '';
                                    if (data1[i].gender == "1") {
                                        gender = 'Male';
                                    }
                                    else if (data1[i].gender == "2") {
                                        gender = 'Female';
                                    }

                                    if (data1[i].address != null || data1[i].address != '' || data1[i].address != "null") {
                                        address = data1[i].address;
                                    }
                                    if (data1[i].town_village != null || data1[i].town_village != '' || data1[i].town_village != "null") {
                                        address = address + " " + data1[i].town_village;
                                    }
                                    address = address + " " + data1[i].pincode;

                                    if (data1[i].dob != null || data1[i].dob != '' || data1[i].dob != 'null') {
                                        dob = data1[i].dob;
                                    }
                                    if (data1[i].photo == null || data1[i].photo == '') {
                                        image = "/Content/img/profile_icon.png";
                                    }
                                    else {
                                        image = $('#patphotop').val() + data[i].photo;
                                    }
                                    tr = tr + '<div class="col-md-6 reg-patient-details"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><div class="reg-patient-details-inner"><div class="row"><div class="col-sm-3"><img src=' + image + ' class="eu-pat-prf-pic" onerror="changedefault(this)" /></div><div class="col-sm-9"><p class="eu-pat-name"> ' + data1[i].first_name + ' <span class="eu-pat-age">(' + data1[i].age + ')</span></p><p class="eu-pat-id">' + data1[i].patient_id + '</p><div class="row"><div class="col-sm-6"><p class="eu-pat-gender">Dob : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-6"><p class="eu-pat-gender">Gender : <span>' + gender + '</span></p></div></div></div></div><div class="row m22"><div class="col-sm-12"><p>Address : </p><p class="eu-pat-address">' + address + '</p></div></div></div></div>';
                                }
                                tr = tr + '<div class="col-md-6 reg-patient-details"><label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><div class="reg-patient-details-inner"><div class="row"><div class="col-md-12"><div class="eu-pat-align-pp"><img src="/Content/img/profile_icon.png" class="eu-pat-prf-pic" /></div><p class="eu-pat-newcustomer">Register as a New patient </p></div></div></div> </div>';
                                $('#reg-patient-details').html(tr);
                                $('#btnlist').html('Submit');
                            }
                            else if (emp.StringResult == 'success') {
                                var dob = $('#txtpDOB').val();
                                if (dob == '') {
                                    dob = '';
                                }
                                else {
                                    var a = dob.split('/');
                                    dob = a[2] + '-' + a[0] + '-' + a[1];
                                }
                                $('#txtPatientID').val(emp.StringMsg);
                                $('#txtAge').val($.trim($("#txtPAge").val()));
                                $('#txtIndividualID').val(emp.IndividualID);
                                $('#txtDOB').val(dob);
                                insert_referral();
                            }
                        });
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}


$('#btnlist').click(function () {
    patientlist();
});


function patientlist() {
    var btnval = '1';
    if ($('#btncheckval').val() == '0') {
        btnval = '2';
    }
    else if ($('#btncheckval').val() == '3') {
        btnval = '3';
    }
    var val1 = $("input[name='patientlist']:checked").val();

    var patient_id, PName;
    var Dml_Indicator = "";
    var individual_id = '';
    if (val1 == "New") {
        Dml_Indicator = "New";
    }
    else {
        Dml_Indicator = "NU";
        individual_id = val1;
    }
    var dob = $('#txtpDOB').val();
    if (dob == '') {
        dob = '';
    }
    else {
        var a = dob.split('/');
        dob = a[2] + '-' + a[0] + '-' + a[1];
    }
    var DirectPatientData = {
        patient_first_name: $("#txtPatientName").val(),
        patient_phone_number: $.trim($("#txtPhoneNo1").val()),
        patient_blood_group: $("txtBloodGroup").val(),
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,
        product_code: "2",
        dob: dob,
        age: $.trim($("#txtPAge").val()),
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            
            
                
                if (jQuery.isEmptyObject((data))) {
                    toastr.warning('Entered Email Address\Mobile Number already Exist');
                }
                else {
                    var data = JSON.parse(data);
                    if (data.msg == "Success") {
                    var data = data.data;
                    if (data.length > 0) {

                        var result = data[0].StringMsg;
                        if (result == 'Phone already registerd') {
                        }
                        else if (result == 'listofpatient') {
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            console.log(data1);
                            for (var i = 0; i < data1.length; i++) {
                                var gender = '-', address = '', dob = '-', image = '';
                                if (data1[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1[i].gender == "2") {
                                    gender = 'Female';
                                }

                                if (data1[i].address != null || data1[i].address != '' || data1[i].address != "null") {
                                    address = data1[i].address;
                                }
                                if (data1[i].town_village != null || data1[i].town_village != '' || data1[i].town_village != "null") {
                                    address = address + " " + data1[i].town_village;
                                }
                                address = address + " " + data1[i].pincode;

                                if (data1[i].dob != null || data1[i].dob != '' || data1[i].dob != 'null') {
                                    dob = data1[i].dob;
                                }
                                if (data1[i].photo == null || data1[i].photo == '') {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data[i].photo;
                                }
                                tr = tr + '<div class="col-md-6 reg-patient-details"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><div class="reg-patient-details-inner"><div class="row"><div class="col-sm-3"><img src=' + image + ' class="eu-pat-prf-pic" onerror="changedefault(this)" /></div><div class="col-sm-9"><p class="eu-pat-name"> ' + data1[i].first_name + ' <span class="eu-pat-age">(' + data1[i].age + ')</span></p><p class="eu-pat-id">' + data1[i].patient_id + '</p><div class="row"><div class="col-sm-6"><p class="eu-pat-gender">Dob : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-6"><p class="eu-pat-gender">Gender : <span>' + gender + '</span></p></div></div></div></div><div class="row m22"><div class="col-sm-12"><p>Address : </p><p class="eu-pat-address">' + address + '</p></div></div></div></div>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details"><label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><div class="reg-patient-details-inner"><div class="row"><div class="col-md-12"><div class="eu-pat-align-pp"><img src="/Content/img/profile_icon.png" class="eu-pat-prf-pic" /></div><p class="eu-pat-newcustomer">Register as a New patient </p></div></div></div> </div>';
                            $('#reg-patient-details').html(tr);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            var dob = $('#txtpDOB').val();
                            if (dob == '') {
                                dob = '';
                            }
                            else {
                                var a = dob.split('/');
                                dob = a[2] + '-' + a[0] + '-' + a[1];
                            }
                            $('#txtPatientID').val(data[0].StringMsg);
                            $('#txtAge').val($.trim($("#txtPAge").val()));
                            $('#txtDOB').val(dob);
                            $('#txtGender').val($("input[name='optradio1']:checked").val())
                            insert_referral();
                            $('.close').click();
                        }
                    }
                    }
                    else {
                        console.log(data);
                    }
            }
           
        }

    });
}


$('#UM_110').click(function () {
    if ($('#doc_list').val() != '0' && $('#doc_list').val() != '')
    {
        $('#txtPaitentSearch').prop('disabled', false);
    }
    LoadClassification();
    LoadHospitalName();
})


$('#txtpDOB').change(function () {
    var dob = $('#txtpDOB').val();
    var a = dob.split('/');
    dob = a[0] + '/' + a[1] + '/' + a[2];
    dob = new Date(dob);
    var today = new Date();
    var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
    $('#txtPAge').val(age);
    //$('#txtAge').attr('disabled', true);
});