$(document).ready(function () {
    debugger;
    $('#selMaritalStatus').val(0);
    Hideshow();
    loadvisit_type()
    $('#BtnSubmit').hide();
    $('#btn_div').show();

    $('#div_p_no_visa').hide();

    $("#present_address").click();
    $(".foreigner").hide();
    //CheckCodeTemplate();


    var patient_id = $('#Patient_Id').val();
    if (patient_id != null && patient_id != '') {
        loadPatient();
    }
    else {
        loadcountry();
        ReferralDoctor();
        Loadidproof();
        LoadBranch();
        LoadReferralType(0, 0);
        LoadCorporate(0, 0);
    }
    $('#div_refdoctor').hide();
});

function nationality_check(val) {
    debugger;
    if (val == 1) {
        $(".foreigner").hide();
    }
    else {
        $(".foreigner").show();
    }
}


//CheckCodeTemplate
function CheckCodeTemplate() {
    debugger;
    var codeData = {
        //Dml_Indicator: "CT",
        Dml_Indicator: "BCT",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#SelBranch').val()
        //branch_id: $('#HospitalBranchID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            debugger;

            var data1 = JSON.parse(data)
            data1 = data1.data;

            if (data1[0].count1 == 0) {
                alert('' + $('#SelBranch  option:selected').html() + ' Not Added Code Template. Please Add the Code Template at SetupIds');
                window.location.href = "/Hospitalsetup"
            }
            //else {
            //    LoadBranch()
            //}

        }
    });
}
$('#txtOccupations').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: 'DirectPatientEnroll/PatientEnroll',
            type: "POST",
            dataType: "json",
            data: { occupation: request.term, Dml_Indicator: "OS", branch_id: $('#HospitalBranchID').val() },
            success: function (data) {
                debugger;
                var data2 = JSON.parse(data)
                response($.map(data2.data.Table, function (item) {
                    return { label: item.occupation, value: item.occupation };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#hdserve_id').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
function LoadBranch() {
    debugger;
    $('#SelBranch').empty();
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            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) {
                        debugger;
                        $('#SelBranch').append(SubDepartment);
                        CheckCodeTemplate();
                        if ($('#hiddenRole_id').val() == 2) {
                            LoadReferralType($('#SelBranch').val(), 0);
                            LoadCorporate($('#SelBranch').val(), 0);
                        }
                    }
                    else {
                        $('#SelBranch').append(default_opt + SubDepartment);
                    }

                    if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        CheckCodeTemplate();
                        if ($('#Patient_Id').val() == null || $('#Patient_Id').val() == "") {
                            LoadReferralType($('#SelBranch').val(), 0);
                            LoadCorporate($('#SelBranch').val(), 0);
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

//refer Doctor start
function ReferralDoctor(value) {
    //$('#txtPatientName').val($('.PatientName').html());
    debugger;
    var DoctorData = {
        Dml_Indicator: "HDL",
        hospital_id: $('#HospitalId').val(),
        //branch_id: b_id
        //branch_id: $('#SelBranch').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            debugger;
            $('#ddReferraldoctor').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#ddReferraldoctor').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.data.length > 0) {
                        for (var i = 0; i < data1.data.length; i++) {
                            j++;
                            SelRole = SelRole + '<option value="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#ddReferraldoctor').html(default_opt + SelRole);
                        if (parseInt($('#hiddenRole_id').val()) == 1) {
                            $("#ddReferraldoctor option[value='" + $('#doctorId').val() + "']").remove();
                        }
                        if (value != 0) {
                            $('#ddReferraldoctor').val(value);
                        }
                    }
                }
            }
        }
    });
}

//load country and defaultly selected to india
function loadcountry() {
    var country = {
        Dml_Indicator: "C"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(country),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var Country;
                    //var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        Country = Country + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    //$('#txtCountry').append(default_opt + Country);
                    ////$('#txtCountry').val('101');

                    //$('#txtJCountry').append(default_opt + Country);

                    //$('#txtJCountry2').append(default_opt + Country);
                    $('#txtCountry').append(Country);
                    //$('#txtCountry').val('101');

                    $('#txtJCountry').append(Country);

                    $('#txtJCountry2').append(Country);

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

            }
        }
    });
}

$("#txtCountry").change(function () {
    debugger;
    $('#passport_no_visa').val('');
    var country_name = $('#txtCountry option:selected').text();

    if (country_name != 'India' && country_name != 'india' && country_name != 'INDIA') {
        $('#div_p_no_visa').show();
        $('#divFormC').show();
    }
    else {
        $('#div_p_no_visa').hide();
        $('#divFormC').hide();
    }


    var state = {
        country_id: $("#txtCountry").val(),
        Dml_Indicator: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var state;
                    $('#txtState').empty();
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtState').append(default_opt + state);
                    $("#txtState").change()
                }
                else {
                    console.log(data);
                }
            }
        }
    });
});

//load state and defaultly selected to tamil nadu
function load_state() {
    debugger;
    var state = {
        country_id: $("#txtCountry").val(),
        Dml_Indicator: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var state;
                    $('#txtState').empty();
                    $('#txtCity').empty();
                    //var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtState').append(state);
                    //$('#txtState').val('35');
                    load_city();
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

$("#txtState").change(function () {
    var state = {
        state_id: $("#txtState").val(),
        Dml_Indicator: "CI"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

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

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

            }
        }
    });
});

function load_city(state_id, city_id) {
    debugger;
    var stateid = ''
    if (state_id != '') {
        stateid = state_id
    }
    else {
        stateid = $("#txtState").val()
    }
    var state = {
        state_id: stateid,
        Dml_Indicator: "CI"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtCity').append(default_opt + City);

                    // LoadBranch();

                    if (city_id != "") {
                        $('#txtCity').val(city_id)
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

$('#Btndelcls').click(function () {
    var overlay = document.getElementById('tblDoctorUser1');
    $('#tblDoctorUser1').modal('toggle');
})

$('#mpinsubmit').click(function () {
    debugger;
    if ($.trim($('#mpinnum').val()).length == "") {
        $('#Pmpinnum').show();
        $('#Pmpinnum').fadeOut(8000);
        $('#Pmpinnum').html('Please enter MPIN');
        $('#mpinnum').focus();
        $('#mpinnum').val('');
        return false;
    }
    if ($.trim($('#mpinnum')).length > 0) {
        var individual_id = '';
        if ($('#BtnSubmit').html() == "Update" || $('#BtnDetailsSubmit').html() == "Update") {
            individual_id = $('#Individual_id').val();
        }
        mpin = $('#mpinnum').val();
        delpatient1(mpin, individual_id);
    }
});


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

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        if (data1.length > 0) {
                            var result = data1[0].result;
                            if (result == 'success') {
                                toastr.success("Patient Deleted Successfully");
                                location.href = "/PatientSearch";
                            }
                            else if (result == '1') {
                                toastr.warning("Unable to Delete the Patient – Patient Name already exist in VIP list");
                            }
                            else if (result == '2') {
                                toastr.warning("Unable to Delete the Patient – Patient Name already exist in Watch list");
                            }
                            else if (result == '3') {
                                toastr.warning("Unable to Delete the Patient - Patient has active package coupons");
                            }
                            else if (result == '4') {
                                toastr.warning("Unable to Delete the Patient - Patient has active lab order");
                            }
                            else if (result == '5') {
                                toastr.warning("Unable to Delete the Patient - Patient has active appointment");
                            }
                            else if (result == '6') {
                                toastr.warning("Unable to Delete the Patient – Patient has pending payment");
                            }
                            else {
                                toastr.warning("Entered MPIN is Wrong!!")
                            }
                        }
                    }
                    else {
                        console.log(data);
                    }


                }
            }
        });
    }
    else {
    }
}


function loadPatient() {
    debugger;
    var DirectPatientData = {
        patient_id: $("#Patient_Id").val(),
        Dml_Indicator: "S",
        product_code: $('#HProductCode').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            debugger;
            console.log(data);
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    debugger;
                    if ($('#UM_123').css('display') != 'none') {
                        $.each(data1.Table, function (i, emp) {
                            $('#txtuserName').val(emp.first_name);
                            if (emp.phone_number_1 == null) {
                                $('#Chkmobileno').attr('checked', true);
                                $('#txtmobileno').attr('disabled', true);
                            }
                            else {
                                jQuery(function () {
                                    jQuery('#showmenu1').click();
                                });
                                $('#txtmobileno').val(emp.phone_number_1);
                            }
                            if (emp.phone_number_2 == null) {
                                $('#txtmobileno1').attr('disabled', true);
                            }
                            else {
                                $('#txtmobileno1').val(emp.phone_number_2);
                            }

                            age = '';
                            if (emp.DOB == "" || emp.DOB == null) {
                                if (emp.age_registered_date == "" || emp.age_registered_date == null) {
                                    if (emp.age == "" || emp.age == null) {
                                        age = '-'
                                        ages = age;
                                    }
                                    else {
                                        ages = emp.age + ' years';
                                    }
                                }
                                else {
                                    if (emp.age_registered_date != null || emp.age_registered_date != "") {
                                        age_reg_date = new Date(emp.age_registered_date);
                                        var today = new Date();
                                        var ageval = '';
                                        ageval = Math.floor((today - age_reg_date) / (365.25 * 24 * 60 * 60 * 1000));
                                        age = ageval + ' Years';
                                        ages = ageval;
                                    }
                                }
                            }
                            else {
                                if (emp.DOB == "" || emp.DOB == null) {

                                }
                                dob = new Date(emp.pa_dob);
                                var today = new Date();
                                var ageval = '';
                                ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                                age = ageval + ' Years';
                                ages = ageval;
                            }

                            $('#txtAge').attr('disabled', true);
                            $('#txtAge').val(ages);

                            $('#agemonths').val(emp.agemonth);
                            //$("input[name='optradio1'][value='" + emp.gender + "']").prop('checked', true);
                            //$("input[name='optradio'][value='" + emp.patient_blood_group + "']").prop('checked', true);
                            $('#gender_type').val(emp.gender);

                            $('#attenderName').val(emp.attender_name);
                            $('#attenderNameRelationship').val(emp.attender_relationship);
                            $('#attenderPhonenumber').val(emp.attender_phone_number);

                            $('a[data-toggle=gender_type][data-title="' + emp.gender + '"]').removeClass('not-active');
                            $('a[data-toggle=gender_type][data-title="' + emp.gender + '"]').addClass('active');
                            $('#bg_type').val(emp.patient_blood_group);
                            $('a[data-toggle=bg_type][data-title="' + emp.patient_blood_group + '"]').removeClass('not-active');
                            $('a[data-toggle=bg_type][data-title="' + emp.patient_blood_group + '"]').addClass('active');
                            $('#txtEmailid').val(emp.email_id);
                            $('#Individual_id').val(emp.individual_id);
                            $('#txtDOB').val(emp.DOB);
                            // $('#txtAge').attr('disabled', true);
                            $('#txtLine1').val(emp.address_line_1);
                            $('#txtLine2').val(emp.address_line_2);
                            $('#txtPlace').val(emp.town_village);
                            //$('#txtCountry').val(emp.country);
                            //$('#txtState').val(emp.state);

                            country(emp.country, emp.state, emp.city);

                            if (emp.country == 101) {
                                $('#div_p_no_visa').hide();
                                $('#divFormC').hide();
                            }
                            else {
                                $('#div_p_no_visa').show();
                                $('#divFormC').show();
                                $('#passport_no_visa').val(emp.passport_no_visa)
                            }
                            //state(emp.country, emp.state,emp.city);
                            ////$('#txtCity').val(emp.city);
                            //city(emp.state, emp.city);
                            $('#txtpincode').val(emp.pincode);                         
                           // $('#txtreferby').val(emp.refer_by);
                            $('#txtaddressid1').val(emp.address_id);
                            $('#txtdoctor_patient_id').val(emp.doctor_patient_id);

                            $('#selSalutation').val(emp.salutation);
                            $('#selMaritalStatus').val(emp.marital_status);
                            setbranch(emp.branch_id);
                            //$('#SelBranch').val(emp.branch_id);

                            //commented by nandhini on 07/04/2022 (as discussed with pandiyaraj sir this concept removed)
                            //if ($('#hiddenRole_id').val() != 1 && $('#hiddenRole_id').val() != 5) {
                            //    $('#Btndelcls').show();
                            //    $('#Btndelcls').html('Delete');
                            //}



                            //$('#ddReferraldoctor').val(emp.ref_doctor); 
                            $('#ddReferraldoctor').val(emp.ReferralDocName);
                            $('#HddnRefDoctorid').val(emp.ReferralDocId);
                            $('#txtReferralDetails').val(emp.referral_details);
                            $('#txtEmployeeName').val(emp.employee_name);
                            $('#txtEmployeeCode').val(emp.employee_code);

                            $('#txtOccupations').val(emp.occupation);
                            $('#txtSecondName').val(emp.last_name);
                            $('#txtFatherName').val(emp.father_name);
                            $('#txtSContactNo').val(emp.second_phone_number);
                            $('#proofno').val(emp.proof_no);
                            Loadidproof(emp.proof_id);
                            var profilephoto = emp.upload_proof;
                            //$('#Hdn_profile_image').val(emp.upload_proof);                           
                            var filepath = $('#hdnfilepath1').val();
                            var photo = $('#hdnfilepath1').val();
                            var d, n, drphimage, drrrfile, PtImage;
                            d = new Date();
                            n = d.getTime();
                            if (profilephoto == null || $.trim(profilephoto) == "" || $.trim(profilephoto).length < 1) {
                            }
                            else {
                                $('#profile-photo').show();
                                $('#profile-photo').empty();
                                drphimage = $('#hdnfilepath1').val() + $('#HiddenDoctorID').val() + '/Photos/' + profilephoto + '?' + n;
                                $('#profile-photo').append('<a href="' + drphimage + '" target="_blank">Image</a>');
                                $('#drphoto').val(profilephoto);
                            }

                            if (emp.PatientImage == null || $.trim(emp.PatientImage) == "") {
                                $("#ImgAvatar").attr("src", "/Content/img/profile_icon.png");
                            }
                            else {
                                $('#PatientImage-photo').show();
                                $('#PatientImage-photo').empty();
                                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + emp.PatientImage + '?' + n;
                                $("#ImgAvatar").attr("src", PtImage);
                                $("#HWebCamImage").val(emp.PatientImage)
                            }

                            LoadCorporate(emp.branch_id, emp.corporate_name);
                            LoadReferralType(emp.branch_id, emp.referral_type);
                            loadreferby(emp.refer_by)
                            //$('#BtnSubmit').html('Update');

                            if (emp.IsApproved == 1 || $('#HFromApproval').val() == 1) {
                                $('#BtnSubmit').show();
                                $('#BtnSubmit').html('Update')
                            }
                            $('#btn_div').hide();

                            $('#BtnSaveCls').hide();
                        });
                    }
                    else {
                        //Detail Patient creation
                        debugger;
                        var isPermanentAddress = '';
                        $(".foreigner").show();
                        $.each(data1.Table, function (i, emp) {
                            $('#txtuserName1').val(emp.first_name);
                            isPermanentAddress = emp.is_permanent_address;
                            $('#chkIsSameAddress').prop('checked', (emp.is_permanent_address == "1" ? true : false))
                            if (emp.phone_number_1 == null && emp.phone_number_2 == null) {
                                $('#Chkmobileno1').attr('checked', true);
                                $('#txtmobileno2').attr('disabled', true);
                            }
                            else {
                                jQuery(function () {
                                    jQuery('#showmenu1').click();
                                });
                                $('#txtmobileno2').val(emp.phone_number_1);
                            }
                            if (emp.phone_number_2 == null) {
                                $('#txtmobileno3').attr('disabled', true);
                            }
                            else {
                                $('#txtmobileno2').val(emp.phone_number_2);
                            }

                            age = '';
                            if (emp.DOB == "" || emp.DOB == null) {
                                if (emp.age_registered_date == "" || emp.age_registered_date == null) {
                                    if (emp.age == "" || emp.age == null) {
                                        age = '-'
                                        ages = age;
                                    }
                                    else {
                                        ages = emp.age + ' years';
                                    }
                                }
                                else {
                                    if (emp.age_registered_date != null || emp.age_registered_date != "") {
                                        age_reg_date = new Date(emp.age_registered_date);
                                        var today = new Date();
                                        var ageval = '';
                                        ageval = Math.floor((today - age_reg_date) / (365.25 * 24 * 60 * 60 * 1000));
                                        age = ageval + ' Years';
                                        ages = ageval;
                                    }
                                }
                            }
                            else {
                                if (emp.DOB == "" || emp.DOB == null) {

                                }
                                dob = new Date(emp.pa_dob);
                                var today = new Date();
                                var ageval = '';
                                ageval = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                                age = ageval + ' Years';
                                ages = ageval;
                            }

                            debugger;
                            $('#txtAge1').val(ages);
                            $('#agemonths').val(emp.agemonth);
                            $('#gender_type1').val(emp.gender);
                            $('a[data-toggle=gender_type1][data-title="' + emp.gender + '"]').removeClass('not-active');
                            $('a[data-toggle=gender_type1][data-title="' + emp.gender + '"]').addClass('active');
                            $('#bg_type1').val(emp.patient_blood_group);
                            $('a[data-toggle=bg_type1][data-title="' + emp.patient_blood_group + '"]').removeClass('not-active');
                            $('a[data-toggle=bg_type1][data-title="' + emp.patient_blood_group + '"]').addClass('active');
                            $('#txtEmailid1').val(emp.email_id);
                            $('#Individual_id').val(emp.individual_id);
                            $('#txtDOB1').val(emp.DOB);

                            $('#txtJLine1').val(emp.address_line_1);
                            $('#txtJLine2').val(emp.address_line_2);
                            countryJ1(emp.country, emp.state, emp.city);
                            $('#txtJpincode').val(emp.pincode);
                            $('#txtJaddressid1').val(emp.address_id);

                            $('#txtdoctor_patient_id1').val(emp.doctor_patient_id);

                            $('#selSalutation1').val(emp.salutation);
                            $('#selMaritalStatus1').val(emp.marital_status);

                            $('#BtnDetaildelcls').show();
                            $('#BtnDetailsSubmit').html('Update');
                            $('#BtnDetaildelcls').html('Delete');
                            $('#BtnDetailsSaveCls').hide();


                            $('#txtPreferedLanguage').val(emp.preferred_language);
                            var referralVal = emp.referral_source;
                            if (referralVal != null && referralVal != "") {
                                var referralSplit = referralVal.split(',');
                                for (i = 0; i < referralSplit.length; i++) {
                                    $("input[name='chkReferralSource'][value=" + referralSplit[i] + "]").prop('checked', true);
                                }
                            }

                            $("#foreigner_acc").click();
                            $('#txtPassportNo').val(emp.passport_no);
                            $('#txtVisaNo').val(emp.visa_no);
                            $('#txtVisaType').val(emp.visa_type);
                            $('#txtVisaValidity').val(emp.visa_validity);
                            $('#txtFormCStatus').val(emp.formc_status);
                            $('#txtOccupation').val(emp.occupation);

                            $('#annual_income').val(emp.annual_income);
                            $('a[data-toggle=annual_income][data-title="' + emp.annual_income + '"]').removeClass('not-active');
                            $('a[data-toggle=annual_income][data-title="' + emp.annual_income + '"]').addClass('active');

                            $('#txtNameofEmployer').val(emp.name_of_employer);
                            $('#txtDesignation').val(emp.designation);
                            $('#txtWorkLocation').val(emp.work_location);
                            $('#txtWorkLocationAddress').val(emp.work_address);
                            $('#nationality_type').val(emp.nationality);
                            $('a[data-toggle=nationality_type][data-title="' + emp.nationality + '"]').removeClass('not-active');
                            $('a[data-toggle=nationality_type][data-title="' + emp.nationality + '"]').addClass('active');
                            $('#txtReligion').val(emp.religion);
                            //var nationality = emp.nationality;
                            //if (nationality == 2) {
                            //}
                        });
                        debugger;
                        if (isPermanentAddress != null && isPermanentAddress == 0) {
                            if (data1.Table1.length > 0) {
                                $('#txtJPLine1').val(data1.Table1[0].address_line_1);
                                $('#txtJPLine2').val(data1.Table1[0].address_line_2);
                                countryJ2(data1.Table1[0].country, data1.Table1[0].state, data1.Table1[0].city);
                                $('#txtJpincode2').val(data1.Table1[0].pincode);
                                $('#txtJaddressid2').val(data1.Table1[0].address_id);
                            }
                        }
                        else {
                            $('#txtJPLine1').val(emp.address_line_1);
                            $('#txtJPLine2').val(emp.address_line_2);
                            countryJ2(emp.country, emp.state, emp.city);
                            $('#txtJpincode2').val(emp.pincode);
                            $('#txtJaddressid2').val(emp.address_id);
                        }

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

            }
        }
    });

}

function setbranch(branch_id) {
    $('#SelBranch').empty();
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    $('#SelBranch').empty();
                    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>';
                    });
                    $('#SelBranch').append(default_opt + SubDepartment);
                    $('#SelBranch').val(branch_id);
                    $('#SelBranch').prop('disabled', true);

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

        }
    });
}

//$('#BtnSubmit').click(function () {
//    debugger;
//    var op_appointment = $('#BtnSubmit').val();
//    register_insert(op_appointment)
//})

//$('#IP_register').click(function () {
//    debugger;
//    var IP_registration = $('#IP_register').val();
//    register_insert(IP_registration)
//})

//$('#OP_billing_register').click(function () {
//    debugger;
//    var op_billing = $('#OP_billing_register').val();
//    register_insert(op_billing)
//})

//$('#daycare_register').click(function () {
//    debugger;
//    var daycare_registration = $('#daycare_register').val();
//    register_insert(daycare_registration)
//})

$('#btn_select').change(function () {
    debugger;
    var btn_select_value = $('#btn_select').val();
    if (btn_select_value != "" && btn_select_value != null) {
        register_insert(btn_select_value);
    }

})

$('#BtnSubmit').click(function () {
    debugger;
    register_insert()
})

function register_insert(register_val) {
    debugger;
    if ($.trim($('#SelBranch').val()) == 0) {
        $('#PSelBranch').show();
        $('#PSelBranch').fadeOut(8000);
        $('#PSelBranch').html('Choose Branch');
        $('#SelBranch').focus();
        $('#SelBranch').val(0);

        $('#btn_select').val('');
        return false;
    }

    if ($.trim($('#selSalutation').val()) == 0) {
        $('#PselSalutation').show();
        $('#PselSalutation').fadeOut(8000);
        $('#PselSalutation').html('Select Salutation');
        $('#selSalutation').focus();
        $('#selSalutation').val(0);

        $('#btn_select').val('');
        return false;
    }
    if ($.trim($('#txtuserName').val()) == "") {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('Enter Patient Name');
        $('#txtuserName').focus();
        $('#txtuserName').val('');

        $('#btn_select').val('');
        return false;
    }
    if ($.trim($("#txtuserName").val()).length < 2) {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('You must have enter minimum of 2 characters');
        $('#txtuserName').focus();
        $('#txtuserName').val('');

        $('#btn_select').val('');
        return false;
    }
    //15/02/2023-Hide for magna requirement

    //if ($.trim($('#txtFatherName').val()) == "") {
    //    $('#PtxtFatherName').show();
    //    $('#PtxtFatherName').fadeOut(8000);
    //    $('#PtxtFatherName').html('Enter the Field');
    //    $('#txtFatherName').focus();
    //    $('#txtFatherName').val('');

    //    $('#btn_select').val('');
    //    return false;
    //}

    if ($('#Chkmobileno').prop("checked") == true) {
    }
    else {
        if ($.trim($('#txtmobileno').val()) == "") {
            $('#Ptxtmobileno').show();
            $('#Ptxtmobileno').fadeOut(8000);
            $('#Ptxtmobileno').html('Enter The Moblie No');
            $('#txtmobileno').focus();
            $('#txtmobileno').val('');

            $('#btn_select').val('');
            return false;
        }
        //if ($.trim($('#txtmobileno').val()).length > 10) {
        //    $('#Ptxtmobileno').show();
        //    $('#Ptxtmobileno').fadeOut(8000);
        //    $('#Ptxtmobileno').html('Invalid Moblie No');
        //    $('#txtmobileno').focus();
        //    $('#txtmobileno').val('');

        //    $('#btn_select').val('');
        //    return false;
        //}
    }

    if ($.trim($('#txtAge').val()) == "") {
        $('#PtxtAge').show();
        $('#PtxtAge').fadeOut(8000);
        $('#PtxtAge').html('Enter The Age');
        $('#txtAge').focus();
        $('#txtAge').val('');
        return false;
    }
    if ($.trim($('#txtAge').val()) == "") {
        if ($.trim($('#txtDOB').val()) == "") {
            $('#PtxtDOB').show();
            $('#PtxtDOB').fadeOut(8000);
            $('#PtxtDOB').html('Enter date of birth');
            $('#txtDOB').focus();
            $('#txtDOB').val('');

            $('#btn_select').val('');
            return false;
        }
    }

    //commented by nandhini for dhanwanthralaya req on 02/08/24
    //if ($("#gender_type").val() == "") {
    //    $('#PSelGender').show();
    //    $('#PSelGender').fadeOut(8000);
    //    $('#PSelGender').html('Select The Gender');
    //    $('#SelGender').focus();
    //    $('#SelGender').val('');

    //    $('#btn_select').val('');
    //    return false;
    //}

    //if ($("#bg_type").val() == "") {
    //    $('#PSelbloodgroup').show();
    //    $('#PSelbloodgroup').fadeOut(8000);
    //    $('#PSelbloodgroup').html('Select The Blood Group');
    //    $('#Selbloodgroup').focus();
    //    $('#Selbloodgroup').val('');

    //    $('#btn_select').val('');
    //    return false;
    //}
    //if ($.trim($('#selMaritalStatus').val()) == 0) {
    //    $('#PMaritalStatus').show();
    //    $('#PMaritalStatus').fadeOut(8000);
    //    $('#PMaritalStatus').html('Select Marital Status');
    //    $('#selMaritalStatus').focus();
    //    $('#selMaritalStatus').val(0);

    //    $('#btn_select').val('');
    //    return false;
    //}

    //if ($.trim($('#ddReferralType').val()) == 0) {
    //    $('#PddReferralType').show();
    //    $('#PddReferralType').fadeOut(8000);
    //    $('#PddReferralType').html('Select Referral Type');
    //    $('#ddReferralType').focus();
    //    $('#ddReferralType').val(0);

    //    $('#btn_select').val('');
    //    return false;
    //}

    var ctry_name = $('#txtCountry option:selected').text();

    if (ctry_name != 'India' && ctry_name != 'india' && ctry_name != 'INDIA') {
        if ($.trim($('#passport_no_visa').val()) == '') {
            $('#Ppassport_no_visa').show();
            $('#Ppassport_no_visa').fadeOut(8000);
            $('#Ppassport_no_visa').html('Enter Passport No/Visa');
            $('#passport_no_visa').focus();
            $('#passport_no_visa').val('');

            $('#btn_select').val('');
            return false;
        }
    }



    if ($.trim($("#txtuserName").val()).length > 0) {
        $('#btncheckval').val("1");
        DirectPatientInsert(register_val);
    }
}

$('#documents').change(function () {
    proofidupload();
});

function proofidupload() {
    debugger;
    var uploadpath = $('#documents').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (fileExtension == "pdf" || fileExtension == "jpg" || fileExtension == "PDF" || fileExtension == "JPG") {
    }
    else {
        $('#Pdocuments').show();
        $('#Pdocuments').fadeOut(8000);
        $('#Pdocuments').html('Please upload file having extensions .pdf/.jpg only.');
        $('#documents').val('');
        $('#documents').focus();
        return false;
    }
    if (window.FormData !== undefined) {
        var fileUpload = $("#documents").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: 'DirectPatientEnroll/UploadPhotoFiles',
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                $.each(result, function (i, emp) {
                    $('#profile-photo').empty();
                    $('#profile-photo').show();
                    var d, n, drreimage;
                    d = new Date();
                    n = d.getTime();
                    drreimage = $('#hdnfilepath1').val() + $('#HiddenDoctorID').val() + '/ID_Proof/' + emp; //+ '?' + n;
                    $('#profile-photo').append('<a href="' + drreimage + '" target="_blank">Proof</a>');
                    $('#drproof').val(emp);

                });
            }
        });
    }
}





function DirectPatientInsert(register_val) {
    debugger;
    $('#BtnSubmit').attr('disabled', true);
    var patient_id, PName;
    var Dml_Indicator = "I";
    var individual_id = '';
    if ($('#BtnSubmit').html() == "Update") {
        Dml_Indicator = "U";
        individual_id = $('#Individual_id').val();

        //if ($.trim($("#txtmobileno").val()) == $.trim($("#txtmobileno1").val())) {
        //    Dml_Indicator = "PPHU";
        //}
    }
    var dob = $('#txtDOB').val();
    if (dob == '') {
        dob = '';
    }
    else {
        var a = dob.split('/');
        dob = a[2] + '-' + a[1] + '-' + a[0];
    }
    var filename = $('#myHiddenVar').val();
    var prooffilename = " "
    var proofupload = $('#documents').val();
    if ($.trim(proofupload) != "") {
        var prooffileExtension = proofupload.substring(proofupload.lastIndexOf(".") + 1, proofupload.length);

        if (prooffileExtension == "pdf" || prooffileExtension == "jpg" || prooffileExtension == "PDF" || prooffileExtension == "JPG") {
            prooffilename = filename + '_IDproof.' + prooffileExtension;
        }
        else {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('Please upload file having extensions .pdf/.doc only.');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
        if (window.FormData === undefined) {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('File format is not supported');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
    }
    else {
        prooffilename = $('#Hdn_profile_image').val();
    }

    var DirectPatientData = {
        patient_first_name: $("#txtuserName").val(),
        patient_phone_number: $.trim($("#txtmobileno").val()),
        P_patient_phone_number: $.trim($("#txtmobileno1").val()),
        patient_email_id: $.trim($("#txtEmailid").val()),
        age: $.trim($("#txtAge").val()),
        gender: $("#gender_type").val(),
        patient_blood_group: $("#bg_type").val(),
        dob: dob,
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,
        address_id: $('#txtaddressid1').val(),
        address_line_1: $('#txtLine1').val(),
        address_line_2: $('#txtLine2').val(),
        town_village: $('#txtPlace').val(),
        country: $('#txtCountry').val(),
        state: $('#txtState').val(),
        city: $('#txtCity').val(),
        pincode: $('#txtpincode').val(),
        refer_by: $('#txtreferby').val(),
        doctor_patient_id: $('#txtdoctor_patient_id').val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation').val(),
        marital_status: $('#selMaritalStatus').val(),
        branch_id: $('#SelBranch').val(),
        referral_type: $('#ddReferralType').val(),
        referral_doctor: $('#HddnRefDoctorid').val(),
        referral_details: $('#txtReferralDetails').val(),
        corporate_name: $('#ddCorporateName').val(),
        employee_name: $('#txtEmployeeName').val(),
        employee_code: $('#txtEmployeeCode').val(),
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),
        register_value: register_val,
        passport_no_visa: $('#passport_no_visa').val(),
        id_proof: $('#txtproof').val(),
        proof_no: $('#proofno').val(),
        upload_proof: prooffilename,
        agemonth: $('#agemonths').val(),
        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val(),
        PatientImage: $("#HWebCamImage").val(),
        occupation: $('#txtOccupations').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            $('#reg-patient-details').html('');
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something Went Wrong..');
                $('#BtnSubmit').attr('disabled', false);
            }
            else {

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

                    $.each(data1.Table, function (i, emp) {
                        debugger;
                        var result = emp.StringMsg
                        if (result == 'Phone already registerd') {
                            $('#Ptxtmobileno').show();
                            $('#Ptxtmobileno').fadeOut(8000);
                            //$('#Ptxtmobileno').html('Mobile number exists');
                            $('#txtmobileno').focus();
                            //$('#txtmobileno').val('');
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsert('1');
                            } else {
                                $('#Ptxtmobileno').show();
                                $('#Ptxtmobileno').fadeOut(8000);
                                $('#Ptxtmobileno').html('Mobile number exists');
                                $('#txtmobileno').focus();
                                $('#txtmobileno').val('');
                                //alert('Why did you press cancel? You should have confirmed');
                            }
                            $('#BtnSubmit').attr('disabled', false);
                            return false;
                        }
                        else if (result == 'Updated') {
                            //$('#Ptxtmobileno').show();
                            //$('#Ptxtmobileno').fadeOut(8000);
                            //$('#Ptxtmobileno').html('Mobile number exists');
                            //$('#txtmobileno').focus();
                            //$('#txtmobileno').val('');
                            toastr.success("Patient Updated Successfully")
                            setTimeout(function () {
                                window.location.href = "/PatientSearch/";
                            }, 2000);

                            return false;
                        }
                        else if (result == 'listofpatient') {
                            debugger;
                            $('#customerRegistration').modal('show');
                            $('#btn_select').val('');
                            var tr = '';
                            for (var i = 0; i < data1.Table.length; i++) {
                                var gender = '-', address = '', dob = '-', image = '', branch_name = '';
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }
                                branch_name = data1.Table[i].branch_name;
                                if (data1.Table[i].address != null || data1.Table[i].address != '' || data1.Table[i].address != "null") {
                                    address = data1.Table[i].address;
                                }
                                if (data1.Table[i].town_village != null || data1.Table[i].town_village != '' || data1.Table[i].town_village != "null") {
                                    address = address + " " + data1.Table[i].town_village;
                                }
                                address = address + " " + data1.Table[i].pincode;

                                if (data1.Table[i].dob != null || data1.Table[i].dob != '' || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == '') {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><div class="selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[i].patient_id + '</p><div class="row"><div class="col-sm-12"><p class="eu-pat-gender">DOB : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-12"><p class="eu-pat-gender">Gender : <span>' + gender + '</span></p></div><div class="col-sm-12"><p class="eu-pat-gender">BranchName : <span>' + branch_name + '</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></div>';
                                //tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><span>' + name + '</span></label>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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>';
                            //  tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><span>+ New Patient</span></label>';
                            $('#reg-patient-details').html(tr);
                            $('#BtnSubmit').attr('disabled', false);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            debugger;
                            var phone = emp.P_patient_phone_number;
                            patient_id = emp.StringMsg;
                            PName = emp.P_patient_first_name;

                            var hospitalid = emp.P_hospitalid;
                            var branchid = emp.branch_id;
                            var register_value = emp.register_value;
                            var patientid = emp.P_Patientid1;
                            var employee_name = emp.employee_name;
                            var employee_code = emp.employee_code;

                            var emp_name_Pid = PName + '/' + patient_id

                            var printcard = PrintCard1(patientid, hospitalid, branchid);
                            $.when(printcard)
                                .then(function (data) {

                                    if (register_value == 'B_APT') {
                                        window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                                    }
                                    else if (register_value == 'IPR') {
                                        window.location.href = "/Ipmanagement/admitpatient?PatientId=" + patient_id + "&branchId=" + branchid;
                                    }
                                    else if (register_value == 'OPB') {
                                        window.location.href = "/BillingMaster/index?patient_id=" + emp_name_Pid + "&H_En_patient_id=" + patient_id + "&branchId=" + branchid + "&op_daycare=" + 1 + "&employee_name=" + employee_name + "&employee_code=" + employee_code;
                                    }
                                    else if (register_value == 'DR') {
                                        window.location.href = "/BillingMaster/index?patient_id=" + emp_name_Pid + "&H_En_patient_id=" + patient_id + "&branchId=" + branchid + "&op_daycare=" + 7;
                                    }
                                    else if (register_value == 'ER') {
                                        window.location.href = "/BillingMaster/index?patient_id=" + emp_name_Pid + "&H_En_patient_id=" + patient_id + "&branchId=" + branchid + "&op_daycare=" + 8;
                                    }
                                    else if (register_value == 'DGR') {
                                        window.location.href = "/BillingMaster/index?patient_id=" + emp_name_Pid + "&H_En_patient_id=" + patient_id + "&branchId=" + branchid + "&op_daycare=" + 4;
                                    }
                                    else if (register_value == 'SP') {
                                        toastr.success('Patient data saved successfully');
                                        cleardetails();
                                    }
                                    else {
                                        console.log(register_value)
                                    }

                                });

                            //var message = "Hi " + emp.P_patient_first_name + "  Thank you for registering into ursugar.Kindly Click the Link to download the application https://goo.gl/RWDUwi"
                            //// window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                            //var sms = {
                            //    phone: phone,
                            //    message: message
                            //}
                            //$.ajax({
                            //    async: true,
                            //    type: 'POST',
                            //    url: '/DirectPatientEnroll/sms',
                            //    contentType: 'application/json; charset=UTF-8',
                            //    data: JSON.stringify(sms),
                            //    success: function (data) {

                            //        //alert('Direct Patient Enroll Record is insert successfully');
                            //        window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                            //    }
                            //});

                        }
                    });
                }
                else {
                    console.log(data);
                    window.location = "/PatientSearch";
                }
            }

        }

    });
}
function cleardetails() {
    $('#BtnSaveCls').attr('disabled', false);
    $('#txtuserName').val('');
    $('#txtOccupations').val('');
    $('#txtSecondName').val('');
    $('#txtFatherName').val('');
    $('#txtdoctor_patient_id').val('');
    $('#txtSContactNo').val('');

    $('#txtmobileno').val('');
    $('#txtAge').val('');
    $('#txtDOB').val('')
    $("input[name='optradio1']:checked").prop("checked", false);
    $("input[name='optradio']:checked").prop("checked", false);
    $('#txtEmailid').val('');
    $('#Chkmobileno').prop('checked', false);
    $('#txtmobileno').prop('disabled', false);
    $('#txtaddressid1').val(''),
        $('#txtLine1').val(''),
        $('#txtLine2').val(''),
        $('#txtPlace').val(''),
    //$('#txtCountry').val(''),
        $('#txtCountry').val(101),
    //$('#txtState').val(''),
        $('#txtState').val(''),
        $('#txtCountry').change();
    $('#txtCity').val(''),
        $('#txtpincode').val(''),
        $('#passport_no_visa').val(''),
        $('#txtreferby').val(''),
        $('#txtdoctor_patient_id1').val(''),
        $('#selSalutation').val(0),
        $('#selMaritalStatus').val(0);

    if ($('#hiddenRole_id').val() == 2) {
        if ($('#SelBranch > option').length != 1) {
            $('#SelBranch').val(0)
        }
    }
    else {
        if ($('#SelBranch > option').length != 1) {
            $('#SelBranch').val($('#HospitalBranchID').val())
        }
    }

    $('a[data-toggle=gender_type]').removeClass('active');
    $('a[data-toggle=gender_type]').addClass('not-active');
    $('a[data-toggle=bg_type]').removeClass('active');
    $('a[data-toggle=bg_type]').addClass('not-active');

    $('#ddReferralType').val(0);
    $('#txtReferralDetails').val('');
    $('#ddReferraldoctor').val('');
    $('#ddCorporateName').val(0);
    $('#txtEmployeeName').val('');
    $('#txtEmployeeCode').val('');
    $('#txtproof').val(0);
    $('#proofno').val('');

    $('#attenderName').val('');
    $('#attenderNameRelationship').val('');
    $('#attenderPhonenumber').val('');
}

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

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

    var returnval = val;
    var DirectPatientData = {
        patient_first_name: $("#txtuserName").val(),
        patient_phone_number: $.trim($("#txtmobileno").val()),
        patient_email_id: $.trim($("#txtEmailid").val()),
        age: $.trim($("#txtAge").val()),
        gender: $("#gender_type").val(),
        patient_blood_group: $("#bg_type").val(),
        dob: dob,
        Dml_Indicator: 'MI',
        patient_id: individual_id,

        address_id: $('#txtaddressid1').val(),
        address_line_1: $('#txtLine1').val(),
        address_line_2: $('#txtLine2').val(),
        town_village: $('#txtPlace').val(),
        country: $('#txtCountry').val(),
        state: $('#txtState').val(),
        city: $('#txtCity').val(),
        pincode: $('#txtpincode').val(),
        refer_by: $('#txtreferby').val(),
        doctor_patient_id: $('#txtdoctor_patient_id').val(),
        salutation: $('#selSalutation').val(),
        marital_status: $('#selMaritalStatus').val(),
        branch_id: $('#SelBranch').val(),
        referral_type: $('#ddReferralType').val(),
        referral_doctor: $('#HddnRefDoctorid').val(),
        referral_details: $('#txtReferralDetails').val(),
        corporate_name: $('#ddCorporateName').val(),
        employee_name: $('#txtEmployeeName').val(),
        employee_code: $('#txtEmployeeCode').val(),
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),

        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $.each(data1.Table, function (i, emp) {
                        if (returnval == 1) {
                            var phone = emp.P_patient_phone_number;
                            patient_id = emp.StringMsg;
                            PName = emp.P_patient_first_name;
                            window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                        }
                        else if (returnval == 3) {
                            toastr.success('Patient data saved successfully');
                            window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                        }
                        else {
                            toastr.success('Patient created successfully...');
                            $('#txtuserName').val('');
                            $('#txtDOB').val('');
                            $('#txtmobileno').val('');
                            $('#txtAge').val('');
                            $('#agemonths').val('');
                            $('#SelGender').val(0);
                            $('#Selbloodgroup').val(0);
                            $('#txtEmailid').val('');
                            $('#Chkmobileno').prop('checked', false);
                            $('#txtaddressid1').val(''),
                                $('#txtLine1').val(''),
                                $('#txtLine2').val(''),
                                $('#txtPlace').val(''),
                                $('#txtCountry').val(''),
                                $('#txtState').val(''),
                                $('#txtCity').val(''),
                                $('#txtpincode').val(''),
                                $('#txtreferby').val(''),
                                $('#txtdoctor_patient_id').val(''),
                                $('#selSalutation').val(0),
                                $('#SelBranch').val(0),
                                $('#selMaritalStatus').val(0),

                             $('#attenderName').val('');
                            $('#attenderNameRelationship').val('');
                            $('#attenderPhonenumber').val('');

                            $("input[name='optradio1']:checked").prop("checked", false);
                            $("input[name='optradio']:checked").prop("checked", false);
                        }
                    });
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}





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

    if ($.trim($('#selSalutation').val()) == 0) {
        $('#PselSalutation').show();
        $('#PselSalutation').fadeOut(8000);
        $('#PselSalutation').html('Select Salutation');
        $('#selSalutation').focus();
        $('#selSalutation').val(0);
        return false;
    }
    if ($.trim($('#txtuserName').val()) == "") {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('Enter Patient Name');
        $('#txtuserName').focus();
        $('#txtuserName').val('');
        return false;
    }
    if ($.trim($("#txtuserName").val()).length < 2) {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('You must have enter minimum of 2 characters');
        $('#txtuserName').focus();
        $('#txtuserName').val('');
        return false;
    }
    //15/02/2023-Hide for magna requirement

    //if ($.trim($('#txtFatherName').val()) == "") {
    //    $('#PtxtFatherName').show();
    //    $('#PtxtFatherName').fadeOut(8000);
    //    $('#PtxtFatherName').html('Enter the Field');
    //    $('#txtFatherName').focus();
    //    $('#txtFatherName').val('');
    //    return false;
    //}



    if ($('#Chkmobileno').prop("checked") == true) {
    }
    else {
        if ($.trim($('#txtmobileno').val()) == "") {
            $('#Ptxtmobileno').show();
            $('#Ptxtmobileno').fadeOut(8000);
            $('#Ptxtmobileno').html('Enter The Moblie No');
            $('#txtmobileno').focus();
            $('#txtmobileno').val('');
            return false;
        }
        //if ($.trim($("#txtmobileno").val()).length > 10) {
        //    $('#Ptxtmobileno').show();
        //    $('#Ptxtmobileno').fadeOut(8000);
        //    $('#Ptxtmobileno').html('Invalid Moblie No');
        //    $('#txtmobileno').focus();
        //    $('#txtmobileno').val('');
        //    return false;
        //}
    }
    //if ($.trim($('#txtmobileno1').val()) != "" && $.trim($("#txtmobileno1").val()).length != "") {
    //    $('#Ptxtmobileno1').show();
    //    $('#Ptxtmobileno1').fadeOut(8000);
    //    $('#Ptxtmobileno1').html('Invalid Moblie No');
    //    $('#txtmobileno1').focus();
    //    $('#txtmobileno1').val('');
    //    return false;
    //}
    

    if ($.trim($('#txtAge').val()) == "") {
        $('#PtxtAge').show();
        $('#PtxtAge').fadeOut(8000);
        $('#PtxtAge').html('Enter The Age');
        $('#txtAge').focus();
        $('#txtAge').val('');
        return false;
    }

    if ($.trim($('#txtAge').val()) == "") {
        if ($.trim($('#txtDOB').val()) == "") {
            $('#PtxtDOB').show();
            $('#PtxtDOB').fadeOut(8000);
            $('#PtxtDOB').html('Enter date of birth');
            $('#txtDOB').focus();
            $('#txtDOB').val('');
            return false;
        }
    }



    //if ($.trim($("input[name='optradio1']:checked").val()) == "") {
    //    $('#PSelGender').show();
    //    $('#PSelGender').fadeOut(8000);
    //    $('#PSelGender').html('Select The Gender');
    //    $('#SelGender').focus();
    //    $('#SelGender').val('');
    //    return false;
    //}

    //commented by nandhini for dhanwanthralaya req on 02/08/24
    //if ($('#gender_type').val() == "") {
    //    $('#PSelGender').show();
    //    $('#PSelGender').fadeOut(8000);
    //    $('#PSelGender').html('Select The Gender');
    //    $('#SelGender').focus();
    //    $('#SelGender').val('');
    //    return false;
    //}
    //if ($('#bg_type').val() == "") {
    //    $('#PSelbloodgroup').show();
    //    $('#PSelbloodgroup').fadeOut(8000);
    //    $('#PSelbloodgroup').html('Select The Blood Group');
    //    $('#Selbloodgroup').focus();
    //    $('#Selbloodgroup').val('');
    //    return false;
    //}
    //if ($.trim($('#selMaritalStatus').val()) == 0) {
    //    $('#PMaritalStatus').show();
    //    $('#PMaritalStatus').fadeOut(8000);
    //    $('#PMaritalStatus').html('Select Marital Status');
    //    $('#selMaritalStatus').focus();
    //    $('#selMaritalStatus').val(0);
    //    return false;
    //}

    //if ($.trim($('#ddReferralType').val()) == 0) {
    //    $('#PddReferralType').show();
    //    $('#PddReferralType').fadeOut(8000);
    //    $('#PddReferralType').html('Select Referral Type');
    //    $('#ddReferralType').focus();
    //    $('#ddReferralType').val(0);

    //    $('#btn_select').val('');
    //    return false;
    //}

    var ctry_name = $('#txtCountry option:selected').text();

    if (ctry_name != 'India' && ctry_name != 'india' && ctry_name != 'INDIA') {
        if ($.trim($('#passport_no_visa').val()) == '') {
            $('#Ppassport_no_visa').show();
            $('#Ppassport_no_visa').fadeOut(8000);
            $('#Ppassport_no_visa').html('Enter Passport No/Visa');
            $('#passport_no_visa').focus();
            $('#passport_no_visa').val('');
            return false;
        }
    }

    if ($.trim($("#txtuserName").val()).length > 0) {
        $('#btncheckval').val("0");
        DirectPatientInsertclose();
    }
});


//$('#txtDOB').change(function () {
//    debugger;
//    var dob = $('#txtDOB').val();
//    if (dob != '' && dob != null) {
//        var a = dob.split('/');
//        dob = a[1] + '/' + a[0] + '/' + a[2];
//        dob = new Date(dob);
//        var today = new Date();
//        var age = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
//        $('#txtAge').val(age);


//        //$('#txtDOB').change(function () {
//        //    debugger;
//        var dob1 = $('#txtDOB').val();
//        if (dob1 != '' && dob1 != null) {
//            var ab = dob1.split('/');
//            dob1 = ab[1] + '/' + ab[0] + '/' + ab[2];
//            dob1 = new Date(dob1);
//            var today1 = new Date();
//            var age1 = calculateAge(dob1, today1);
//            $('#agemonths').val(age1.months + ' months and ' + age1.days + ' days');
//            $('#agemonths').attr('disabled', true);
//            //var Hage = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
//            //$('#Hage').val(Hage);
//        }
//        else {
//            $('#agemonths').val('');
//            $('#agemonths').attr('disabled', false);
//        }
//        /*  });*/


//        if ($('#txtAge').val() < 18) {

//            $('#selMaritalStatus').val(2);
//        }
//        else {
//            $('#selMaritalStatus').val(0);
//        }
//        $('#txtAge').attr('disabled', true);
//    }
//    else {
//        $('#txtAge').val('');
//        $('#txtAge').attr('disabled', false);
//    }

//});


$('#txtDOB').change(function () {
    debugger;
    var dob = $('#txtDOB').val();
    if (dob) {
        var parts = dob.split('/');
        // Ensure the date is in the format MM/DD/YYYY
        var formattedDOB = parts[1] + '/' + parts[0] + '/' + parts[2];
        var dobDate = new Date(formattedDOB);

        if (!isNaN(dobDate.getTime())) { // Valid date
            var today = new Date();
            var age = today.getFullYear() - dobDate.getFullYear();
            var monthDiff = today.getMonth() - dobDate.getMonth();
            if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < dobDate.getDate())) {
                age--; // Subtract 1 if the birthday hasn't occurred yet this year
            }
            $('#txtAge').val(age);
            $('#txtAge').prop('disabled', true);

            var dob1 = $('#txtDOB').val();
            if (dob1 != '' && dob1 != null) {
                var ab = dob1.split('/');
                dob1 = ab[1] + '/' + ab[0] + '/' + ab[2];
                dob1 = new Date(dob1);
                var today1 = new Date();
                var age1 = calculateAge(dob1, today1);
                $('#agemonths').val(age1.months + ' months and ' + age1.days + ' days');
                $('#agemonths').attr('disabled', true);
                //var Hage = Math.floor((today - dob) / (365.25 * 24 * 60 * 60 * 1000));
                //$('#Hage').val(Hage);
            }
            else {
                $('#agemonths').val('');
                $('#agemonths').attr('disabled', false);
            }

            // Setting marital status based on age
            if (age < 18) {
                $('#selMaritalStatus').val(2); // Minor
            } else {
                $('#selMaritalStatus').val(0); // Adult
            }
            //$('#agemonths').val(''); // Reset the months input
            //$('#agemonths').prop('disabled', true);
        } else {
            // Invalid date
            $('#txtAge').val('');
            $('#selMaritalStatus').val('');
            $('#txtAge').prop('disabled', false);
            $('#agemonths').prop('disabled', false);
        }
    } else {
        // Empty date of birth
        $('#txtAge').val('');
        $('#selMaritalStatus').val('');
        $('#txtAge').prop('disabled', false);
        $('#agemonths').prop('disabled', false);
    }
});


function DirectPatientInsertclose() {
    debugger;
    $('#BtnSaveCls').attr('disabled', true);
    var patient_id, PName;
    var Dml_Indicator = "IC";
    var individual_id = '';

    var dob = $('#txtDOB').val();
    if (dob == '') {
        dob = '';
    }
    else {
        var a = dob.split('/');
        dob = a[2] + '-' + a[1] + '-' + a[0];
    }
    var filename = $('#myHiddenVar').val();
    var prooffilename = " "
    var proofupload = $('#documents').val();
    if ($.trim(proofupload) != "") {
        var prooffileExtension = proofupload.substring(proofupload.lastIndexOf(".") + 1, proofupload.length);

        if (prooffileExtension == "pdf" || prooffileExtension == "jpg" || prooffileExtension == "PDF" || prooffileExtension == "JPG") {
            prooffilename = filename + '_IDproof.' + prooffileExtension;
        }
        else {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('Please upload file having extensions .pdf/.doc only.');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
        if (window.FormData === undefined) {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('File format is not supported');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
    }
    else {
        prooffilename = $('#Hdn_profile_image').val();
    }
    var DirectPatientData = {
        patient_first_name: $("#txtuserName").val(),
        patient_phone_number: $.trim($("#txtmobileno").val()),
        P_patient_phone_number: $.trim($("#txtmobileno1").val()),
        patient_email_id: $.trim($("#txtEmailid").val()),
        age: $.trim($("#txtAge").val()),
        gender: $("#gender_type").val(),
        dob: dob,
        patient_blood_group: $("#bg_type").val(),
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,
        address_id: $('#txtaddressid1').val(),
        address_line_1: $('#txtLine1').val(),
        address_line_2: $('#txtLine2').val(),
        town_village: $('#txtPlace').val(),
        country: $('#txtCountry').val(),
        state: $('#txtState').val(),
        city: $('#txtCity').val(),
        pincode: $('#txtpincode').val(),
        refer_by: $('#txtreferby').val(),
        doctor_patient_id: $('#txtdoctor_patient_id').val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation').val(),
        marital_status: $('#selMaritalStatus').val(),
        branch_id: $('#SelBranch').val(),
        referral_type: $('#ddReferralType').val(),
        referral_doctor: $('#HddnRefDoctorid').val(),
        referral_details: $('#txtReferralDetails').val(),
        corporate_name: $('#ddCorporateName').val(),
        employee_name: $('#txtEmployeeName').val(),
        employee_code: $('#txtEmployeeCode').val(),
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),
        passport_no_visa: $('#passport_no_visa').val(),
        id_proof: $('#txtproof').val(),
        proof_no: $('#proofno').val(),
        upload_proof: prooffilename,
        agemonth: $('#agemonths').val(),
        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val(),
        PatientImage: $("#HWebCamImage").val(),
        occupation: $('#txtOccupations').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            $('#reg-patient-details').html('');
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning(' Something Went Wrong.. ');
                $('#BtnSaveCls').attr('disabled', false);
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $.each(data1.Table, function (i, emp) {
                        var result = emp.StringMsg
                        if (result == 'Phone already registerd') {
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsert('2');
                            } else {
                                $('#Ptxtmobileno').show();
                                $('#Ptxtmobileno').fadeOut(8000);
                                $('#Ptxtmobileno').html('Mobile number exists');
                                $('#txtmobileno').focus();
                                $('#txtmobileno').val('');
                                //alert('Why did you press cancel? You should have confirmed');
                            }
                            $('#BtnSaveCls').attr('disabled', false);
                            return false;
                        }
                        else if (result == 'Updated') {
                            window.location.href = "/PatientSearch/";
                            return false;
                        }
                        else if (result == 'listofpatient') {
                            $('#BtnSaveCls').attr('disabled', false);
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            console.log(data1.Table);
                            for (var i = 0; i < data1.Table.length; i++) {
                                debugger;
                                var gender = '-', address = '', dob = '-', image = '', branch_name = '';
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }

                                if (data1.Table[i].address != null || data1.Table[i].address != "" || data1.Table[i].address != "null") {
                                    address = data1.Table[i].address;
                                }
                                if (data1.Table[i].town_village != null || data1.Table[i].town_village != "" || data1.Table[i].town_village != "null") {
                                    address = address + " " + data1.Table[i].town_village;
                                }
                                address = address + " " + data1.Table[i].pincode;
                                branch_name = data1.Table[i].branch_name;
                                if (data1.Table[i].dob != null || data1.Table[i].dob != "" || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == "") {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                //tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><div class="Selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[i].patient_id + '</p><div class="row"><div class="col-sm-12"><p class="eu-pat-gender">DOB : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-12"><p class="eu-pat-gender">Gender : <span>' + gender + '</span></p></div><div class="col-sm-12"><p class="eu-pat-gender">BranchName : <span>' + branch_name + '</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></div>';

                                // tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><span>' + name + '</span></label>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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>';

                            //  tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><span>+ New Patient</span></label>';
                            $('#reg-patient-details').html(tr);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            toastr.success('Patient data saved successfully');
                            $('#BtnSaveCls').attr('disabled', false);
                            $('#txtuserName').val('');
                            $('#txtOccupations').val('');
                            $('#txtSecondName').val('');
                            $('#txtFatherName').val('');
                            $('#txtdoctor_patient_id').val('');
                            $('#txtSContactNo').val('');
                            $('#agemonths').val('');
                            $('#txtmobileno').val('');
                            $('#txtAge').val('');
                            $('#txtDOB').val('')
                            $("input[name='optradio1']:checked").prop("checked", false);
                            $("input[name='optradio']:checked").prop("checked", false);
                            $('#txtEmailid').val('');
                            $('#Chkmobileno').prop('checked', false);
                            $('#txtmobileno').prop('disabled', false);
                            $('#txtaddressid1').val(''),
                                $('#txtLine1').val(''),
                                $('#txtLine2').val(''),
                                $('#txtPlace').val(''),
                            //$('#txtCountry').val(''),
                                $('#txtCountry').val(101),
                            //$('#txtState').val(''),
                                $('#txtState').val(''),
                                $('#txtCountry').change();
                            $('#txtCity').val(''),
                                $('#txtpincode').val(''),
                                $('#passport_no_visa').val(''),
                                $('#txtreferby').val(''),
                                $('#txtdoctor_patient_id1').val(''),
                                $('#selSalutation').val(0),
                                $('#selMaritalStatus').val(0);

                            if ($('#hiddenRole_id').val() == 2) {
                                if ($('#SelBranch > option').length != 1) {
                                    $('#SelBranch').val(0)
                                }
                            }
                            else {
                                if ($('#SelBranch > option').length != 1) {
                                    $('#SelBranch').val($('#HospitalBranchID').val())
                                }
                            }

                            $('a[data-toggle=gender_type]').removeClass('active');
                            $('a[data-toggle=gender_type]').addClass('not-active');
                            $('a[data-toggle=bg_type]').removeClass('active');
                            $('a[data-toggle=bg_type]').addClass('not-active');

                            $('#ddReferralType').val(0);
                            $('#txtReferralDetails').val('');
                            $('#ddReferraldoctor').val('');
                            $('#ddCorporateName').val(0);
                            $('#txtEmployeeName').val('');
                            $('#txtEmployeeCode').val('');
                            $('#txtproof').val(0);
                            $('#proofno').val('');

                            $('#attenderName').val('');
                            $('#attenderNameRelationship').val('');
                            $('#attenderPhonenumber').val('');


                            $('#HPrintPatientId').val(data1.Table1[0].P_Patientid1)
                            $('#HPrintHospitalId').val(data1.Table1[0].P_hospitalid)
                            $('#HPrintBranchId').val(data1.Table1[0].P_branch_id)
                            $('#profile-photo').empty();
                            $('#documents').val('');
                            $('#PatientImage-photo').empty();
                            $("#ImgAvatar").attr("src", "/Content/img/profile_icon.png");
                            $("#HWebCamImage").val('')
                            //$("#ImgAvatar").show();
                            PrintCard($('#HPrintPatientId').val(), $('#HPrintHospitalId').val(), $('#HPrintBranchId').val())
                        }
                    });
                }
                else {
                    console.log(data);
                    window.location = "/PatientSearch";
                }

            }
        }
    });
}

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


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

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

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

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


function PrintCard1(patientid, hospitalid, branch_id) {
    debugger;
    var load_data = {
        formid: "75",
        //report_name: ReportName,
        branchid: branch_id,
        hospitalid: hospitalid,
        patientid: patientid,

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

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

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


function state(coval, stateval, city_val) {
    debugger;
    var state = {
        country_id: coval,
        Dml_Indicator: "S"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

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

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

                    });
                    // $('#txtState').append(default_opt + state);
                    $('#txtState').append(state);
                    $('#txtState').val(stateval);
                    city(stateval, city_val)
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}


function city(stateval, citval) {
    var state = {
        state_id: stateval,
        Dml_Indicator: "CI"
    }

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

            var data1 = JSON.parse(data);

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

            }
            else {
                // alert(' Sorry, The values you entered are invalid.\n Please try again. ');

                var data2 = JSON.parse(data);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

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

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

            }
        }

    });
}

function country(country_val, state_val, city_val) {
    var country = {
        Dml_Indicator: "C"
    }

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

            var data1 = JSON.parse(data);

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

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

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

                    });
                    //$('#txtCountry').append(default_opt + Country);
                    $('#txtCountry').append(Country);
                    $('#txtCountry').val(country_val);
                    state(country_val, state_val, city_val);
                }
                else {
                    console.log(data);
                }

            }
        }
    });

}

$('#btnlist').click(function () {
    debugger;
    if ($('#UM_123').css('display') != 'none') {
        patientlist();
    }
    else {
        DetailPatientList();
    }
});

function patientlist() {
    debugger;
    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 = $('#txtDOB').val();
    if (dob == '') {
        dob = '';
    }
    else {
        var a = dob.split('/');
        dob = a[2] + '-' + a[1] + '-' + a[0];
    }
    var filename = $('#myHiddenVar').val();
    var prooffilename = " "
    var proofupload = $('#documents').val();
    if ($.trim(proofupload) != "") {
        var prooffileExtension = proofupload.substring(proofupload.lastIndexOf(".") + 1, proofupload.length);

        if (prooffileExtension == "pdf" || prooffileExtension == "jpg" || prooffileExtension == "PDF" || prooffileExtension == "JPG") {
            prooffilename = filename + '_IDproof.' + prooffileExtension;
        }
        else {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('Please upload file having extensions .pdf/.doc only.');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
        if (window.FormData === undefined) {
            $('#Pdocuments').show();
            $('#Pdocuments').fadeOut(8000);
            $('#Pdocuments').html('File format is not supported');
            $('#documents').val('');
            $('#documents').focus();
            return false;
        }
    }
    else {
        prooffilename = $('#Hdn_profile_image').val();
    }

    var DirectPatientData = {
        patient_first_name: $("#txtuserName").val(),
        patient_phone_number: $.trim($("#txtmobileno").val()),
        patient_email_id: $.trim($("#txtEmailid").val()),
        age: $.trim($("#txtAge").val()),
        gender: $("#gender_type").val(),
        patient_blood_group: $("#bg_type").val(),
        dob: dob,
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,

        address_id: $('#txtaddressid1').val(),
        address_line_1: $('#txtLine1').val(),
        address_line_2: $('#txtLine2').val(),
        town_village: $('#txtPlace').val(),
        country: $('#txtCountry').val(),
        state: $('#txtState').val(),
        city: $('#txtCity').val(),
        pincode: $('#txtpincode').val(),
        refer_by: $('#txtreferby').val(),
        doctor_patient_id: $('#txtdoctor_patient_id').val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation').val(),
        marital_status: $('#selMaritalStatus').val(),
        branch_id: $('#SelBranch').val(),
        referral_type: $('#ddReferralType').val(),
        referral_doctor: $('#HddnRefDoctorid').val(),
        referral_details: $('#txtReferralDetails').val(),
        corporate_name: $('#ddCorporateName').val(),
        employee_name: $('#txtEmployeeName').val(),
        employee_code: $('#txtEmployeeCode').val(),
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),
        id_proof: $('#txtproof').val(),
        proof_no: $('#proofno').val(),
        upload_proof: prooffilename,
        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something went wrong');
            }
            else {

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

                        var result = data1.Table[0].StringMsg;
                        if (result == 'Phone already registerd') {
                            $('#Ptxtmobileno').show();
                            $('#Ptxtmobileno').fadeOut(8000);
                            $('#txtmobileno').focus();
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsert('1');
                            } else {
                                $('#Ptxtmobileno').show();
                                $('#Ptxtmobileno').fadeOut(8000);
                                $('#Ptxtmobileno').html('Mobile number exists');
                                $('#txtmobileno').focus();
                                $('#txtmobileno').val('');
                                //alert('Why did you press cancel? You should have confirmed');
                            }
                            return false;
                        }
                        else if (result == 'Updated') {
                            window.location.href = "/PatientSearch/";
                            return false;
                        }
                        else if (result == 'listofpatient') {
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            console.log(data1.Table);
                            debugger;
                            for (var i = 0; i < data1.Table.length; i++) {
                                var gender = '-', address = '', dob = '-', image = ''; var branch_name = "";
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }
                                branch_name = data1.Table[i].branch_name
                                if (data1.Table[i].address != null || data1.Table[i].address != '' || data1.Table[i].address != "null") {
                                    address = data1.Table[i].address;
                                }
                                if (data1.Table[i].town_village != null || data1.Table[i].town_village != '' || data1.Table[i].town_village != "null") {
                                    address = address + " " + data1.Table[i].town_village;
                                }
                                address = address + " " + data1[i].pincode;

                                if (data1.Table[i].dob != null || data1.Table[i].dob != '' || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == '') {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                //tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><div class="selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 class="col-sm-6"><p class="eu-pat-gender">BranchName : <span>' + branch_name + '</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></div>';

                                // tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><span>' + name + '</span></label>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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>';

                            //  tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><span>+ New Patient</span></label>';
                            $('#reg-patient-details').html(tr);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            if (btnval == 1) {
                                var phone = data1.Table[0].P_patient_phone_number;
                                patient_id = data1.Table[0].StringMsg;
                                PName = data1.Table[0].P_patient_first_name;
                                window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                            }
                            else if (btnval == 3) {
                                toastr.success('Patient data saved successfully');
                                window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                            }
                            else {
                                toastr.success('Patient data saved successfully');
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);

                                $('#txtuserName').val('');
                                $('#txtmobileno').val('');
                                $('#txtAge').val('');
                                $('#txtDOB').val('')
                                $("input[name='optradio1']:checked").prop("checked", false);
                                $("input[name='optradio']:checked").prop("checked", false);
                                $('#txtEmailid').val('');
                                $('#Chkmobileno').prop('checked', false);
                                $('#txtmobileno').prop('disabled', false);
                                $('#txtAge').prop('disabled', false);
                                $('#txtaddressid1').val(''),
                                    $('#txtLine1').val(''),
                                    $('#txtLine2').val(''),
                                    $('#txtPlace').val(''),
                                    $('#txtCountry').val(''),
                                    $('#txtState').val(''),
                                    $('#txtCity').val(''),
                                    $('#txtpincode').val(''),
                                    $('#txtreferby').val(''),
                                    $('#txtdoctor_patient_id').val(''),
                                    $('#selSalutation').val(0),
                                    $('#SelBranch').val(0),
                                    $('#selMaritalStatus').val(0)

                                $('#attenderName').val('');
                                $('#attenderNameRelationship').val('');
                                $('#attenderPhonenumber').val('');

                                $('.close').click();

                                window.location.href = "/PatientSearch";
                            }
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        }

    });
}


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

    if ($.trim($('#selSalutation').val()) == 0) {
        $('#PselSalutation').show();
        $('#PselSalutation').fadeOut(8000);
        $('#PselSalutation').html('Select Salutation');
        $('#selSalutation').focus();
        $('#selSalutation').val(0);
        return false;
    }

    if ($.trim($('#txtuserName').val()) == "") {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('Enter The Patient Name');
        $('#txtuserName').focus();
        $('#txtuserName').val('');
        return false;
    }

    if ($.trim($("#txtuserName").val()).length < 2) {
        $('#PtxtuserName').show();
        $('#PtxtuserName').fadeOut(8000);
        $('#PtxtuserName').html('You must have enter minimum of 2 characters');
        $('#txtuserName').focus();
        $('#txtuserName').val('');
        return false;
    }

    if ($('#Chkmobileno').prop("checked") == true) {
    }
    else {
        if ($.trim($('#txtmobileno').val()) == "") {
            $('#Ptxtmobileno').show();
            $('#Ptxtmobileno').fadeOut(8000);
            $('#Ptxtmobileno').html('Enter The Moblie No');
            $('#txtmobileno').focus();
            $('#txtmobileno').val('');
            return false;
        }
        if ($.trim($("#txtmobileno").val()).length > 10) {
            $('#Ptxtmobileno').show();
            $('#Ptxtmobileno').fadeOut(8000);
            $('#Ptxtmobileno').html('Invalid Moblie No');
            $('#txtmobileno').focus();
            $('#txtmobileno').val('');
            return false;
        }
    }

    if ($.trim($('#txtAge').val()) == "") {
        if ($.trim($('#txtDOB').val()) == "") {
            $('#PtxtDOB').show();
            $('#PtxtDOB').fadeOut(8000);
            $('#PtxtDOB').html('Enter date of birth');
            $('#txtDOB').focus();
            $('#txtDOB').val('');
            return false;
        }
    }

    if ($.trim($("input[name='optradio1']:checked").val()) == "") {
        $('#PSelGender').show();
        $('#PSelGender').fadeOut(8000);
        $('#PSelGender').html('Select The Gender');
        $('#SelGender').focus();
        $('#SelGender').val('');
        return false;
    }

    if ($.trim($("#txtuserName").val()).length > 0) {
        $('#btncheckval').val("3");
        var patient_id, PName;
        var Dml_Indicator = "IC";
        var individual_id = '';

        var dob = $('#txtDOB').val();
        if (dob == '') {
            dob = '';
        }
        else {
            var a = dob.split('/');
            dob = a[2] + '-' + a[1] + '-' + a[0];
        }
        var DirectPatientData = {
            patient_first_name: $("#txtuserName").val(),
            patient_phone_number: $.trim($("#txtmobileno").val()),
            P_patient_phone_number: $.trim($("#txtmobileno1").val()),
            patient_email_id: $.trim($("#txtEmailid").val()),
            age: $.trim($("#txtAge").val()),
            gender: $("#gender_type").val(),
            dob: dob,
            patient_blood_group: $("#bg_type").val(),
            Dml_Indicator: Dml_Indicator,
            patient_id: individual_id,

            address_id: $('#txtaddressid1').val(),
            address_line_1: $('#txtLine1').val(),
            address_line_2: $('#txtLine2').val(),
            town_village: $('#txtPlace').val(),
            country: $('#txtCountry').val(),
            state: $('#txtState').val(),
            city: $('#txtCity').val(),
            pincode: $('#txtpincode').val(),
            refer_by: $('#txtreferby').val(),
            doctor_patient_id: $('#txtdoctor_patient_id').val(),
            product_code: $('#HProductCode').val(),
            salutation: $('#selSalutation').val(),
            marital_status: $('#selMaritalStatus').val(),
            branch_id: $('#SelBranch').val(),
            referral_type: $('#ddReferralType').val(),
            referral_doctor: $('#HddnRefDoctorid').val(),
            referral_details: $('#txtReferralDetails').val(),
            corporate_name: $('#ddCorporateName').val(),
            employee_name: $('#txtEmployeeName').val(),
            employee_code: $('#txtEmployeeCode').val(),
            patient_last_name: $('#txtSecondName').val(),
            father_name: $('#txtFatherName').val(),
            second_phone_number: $('#txtSContactNo').val(),

            attender_name: $('#attenderName').val(),
            attender_relationship: $('#attenderNameRelationship').val(),
            attender_phone_number: $('#attenderPhonenumber').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: 'DirectPatientEnroll/PatientEnroll',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DirectPatientData),
            success: function (data) {
                var data2 = JSON.parse(data);
                $('#reg-patient-details').html('');
                if (jQuery.isEmptyObject((data2.data))) {
                    toastr.warning('Something went wrong');
                }
                else {

                    if (data2.msg == "Success") {
                        var data1 = data2.data;
                        $.each(data1.Table, function (i, emp) {
                            var result = emp.StringMsg
                            if (result == 'Phone already registerd') {
                                if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                    secondmobileInsert('3');
                                } else {
                                    $('#Ptxtmobileno').show();
                                    $('#Ptxtmobileno').fadeOut(8000);
                                    $('#Ptxtmobileno').html('Mobile number exists');
                                    $('#txtmobileno').focus();
                                    $('#txtmobileno').val('');
                                }
                                return false;
                            }
                            else if (result == 'Updated') {
                                window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                                return false;
                            }
                            else if (result == 'listofpatient') {
                                $('#customerRegistration').modal('show');
                                var tr = '';
                                console.log(data1.Table);
                                for (var i = 0; i < data1.Table.length; i++) {
                                    debugger;
                                    var gender = '-', address = '', dob = '-', image = '', branch_name = '';
                                    if (data1.Table[i].gender == "1") {
                                        gender = 'Male';
                                    }
                                    else if (data1.Table[i].gender == "2") {
                                        gender = 'Female';
                                    }
                                    branch_name = data1.Table[i].branch_name;
                                    if (data1.Table[i].address != null || data1.Table[i].address != "" || data1.Table[i].address != "null") {
                                        address = data1.Table[i].address;
                                    }
                                    if (data1.Table[i].town_village != null || data1.Table[i].town_village != "" || data1.Table[i].town_village != "null") {
                                        address = address + " " + data1.Table[i].town_village;
                                    }
                                    address = address + " " + data1.Table[i].pincode;
                                    if (data1.Table[i].dob != null || data1.Table[i].dob != "" || data1.Table[i].dob != 'null') {
                                        dob = data1.Table[i].dob;
                                    }
                                    if (data1.Table[i].photo == null || data1.Table[i].photo == "") {
                                        image = "/Content/img/profile_icon.png";
                                    }
                                    else {
                                        image = $('#patphotop').val() + data.Table[i].photo;
                                    }
                                    //tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><div class="selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 class="col-sm-6"><p class="eu-pat-gender">BranchName : <span>' + branch_name + '</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></div>';
                                }
                                tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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 {
                                toastr.success('Patient data saved successfully');
                                window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                            }
                        });
                    }
                    else {
                        console.log(data);
                    }

                }
            }
        });
    }

});



// New Detail patient creation page


$("#BtnDetailsSaveCls").click(function () {
    if ($.trim($('#selSalutation1').val()) == 0) {
        $('#PselSalutation1').show();
        $('#PselSalutation1').fadeOut(8000);
        $('#PselSalutation1').html('Select Salutation');
        $('#selSalutation1').focus();
        $('#selSalutation1').val(0);
        return false;
    }

    if ($.trim($('#txtuserName1').val()) == "") {
        $('#PtxtuserName1').show();
        $('#PtxtuserName1').fadeOut(8000);
        $('#PtxtuserName1').html('Enter The Patient Name');
        $('#txtuserName1').focus();
        $('#txtuserName1').val('');
        return false;
    }

    if ($.trim($("#txtuserName1").val()).length < 2) {
        $('#PtxtuserName1').show();
        $('#PtxtuserName1').fadeOut(8000);
        $('#PtxtuserName1').html('You must have enter minimum of 2 characters');
        $('#txtuserName1').focus();
        $('#txtuserName1').val('');
        return false;
    }

    if ($.trim($('#txtAge1').val()) == "") {
        if ($.trim($('#txtDOB1').val()) == "") {
            $('#PtxtDOB1').show();
            $('#PtxtDOB1').fadeOut(8000);
            $('#PtxtDOB1').html('Enter date of birth');
            $('#txtDOB1').focus();
            $('#txtDOB1').val('');
            return false;
        }
    }


    if ($('#gender_type1').val() == "") {
        $('#PSelGender1').show();
        $('#PSelGender1').fadeOut(8000);
        $('#PSelGender1').html('Select The Gender');
        $('#SelGender1').focus();
        $('#SelGender1').val('');
        return false;
    }

    if ($.trim($('#selMaritalStatus1').val()) == 0) {
        $('#PMaritalStatus1').show();
        $('#PMaritalStatus1').fadeOut(8000);
        $('#PMaritalStatus1').html('Select Marital Status');
        $('#selMaritalStatus1').focus();
        $('#selMaritalStatus1').val(0);
        return false;
    }

    if ($("#nationality_type").val() == "") {
        $('#Pnationality_type').show();
        $('#Pnationality_type').fadeOut(8000);
        $('#Pnationality_type').html('Select Nationality');
        $('#nationality_type').focus();
        $('#nationality_type').val('');
        return false;
    }


    if ($('#Chkmobileno1').prop("checked") == true) {
    }
    else {
        if ($.trim($('#txtmobileno2').val()) == "") {
            $('#Ptxtmobileno2').show();
            $('#Ptxtmobileno2').fadeOut(8000);
            $('#Ptxtmobileno2').html('Enter The Moblie No');
            $('#txtmobileno2').focus();
            $('#txtmobileno2').val('');
            return false;
        }
        if ($.trim($("#txtmobileno2").val()).length > 10) {
            $('#Ptxtmobileno2').show();
            $('#Ptxtmobileno2').fadeOut(8000);
            $('#Ptxtmobileno2').html('Invalid Moblie No');
            $('#txtmobileno2').focus();
            $('#txtmobileno2').val('');
            return false;
        }
    }



    if ($("#txtJLine1").val() == "") {
        $('#PtxtJLine1').show();
        $('#PtxtJLine1').fadeOut(8000);
        $('#PtxtJLine1').html('Enter Address');
        $('#txtJLine1').focus();
        $('#txtJLine1').val('');
        return false;
    }
    if ($.trim($("#txtJpincode").val()) == "") {
        $('#PtxtJpincode').show();
        $('#PtxtJpincode').fadeOut(8000);
        $('#PtxtJpincode').html('Enter Pincode');
        $('#txtJpincode').focus();
        $('#txtJpincode').val('');
        return false;
    }

    if ($.trim($("#txtJCountry").val()) == 0) {
        $('#PtxtJCountry').show();
        $('#PtxtJCountry').fadeOut(8000);
        $('#PtxtJCountry').html('Select Country');
        $('#txtJCountry').focus();
        $('#txtJCountry').val(0);
        return false;
    }
    if ($.trim($("#txtJState").val()) == 0) {
        $('#PtxtJState').show();
        $('#PtxtJState').fadeOut(8000);
        $('#PtxtJState').html('Select State');
        $('#PtxtJState').focus();
        $('#txtJState').val(0);
        return false;
    }
    if ($.trim($("#txtJCity").val()) == 0) {
        $('#PtxtJCity').show();
        $('#PtxtJCity').fadeOut(8000);
        $('#PtxtJCity').html('Select City');
        $('#txtJCity').focus();
        $('#txtJCity').val(0);
        return false;
    }

    if ($.trim($("#txtuserName1").val()).length > 0) {
        $('#btncheckval').val("0");
        DirectDetailPatientInsertclose();
    }
});



function DirectDetailPatientInsertclose() {
    var patient_id, PName;
    var Dml_Indicator = "IC";
    var individual_id = '';

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

    var referralList = [];
    $.each($("input[name='chkReferralSource']:checked"), function () {
        referralList.push($(this).val());
    });

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

    var DirectPatientData = {
        patient_first_name: $("#txtuserName1").val(),
        patient_phone_number: $.trim($("#txtmobileno2").val()),
        P_patient_phone_number: $.trim($("#txtmobileno3").val()),
        patient_email_id: $.trim($("#txtEmailid1").val()),
        age: $.trim($("#txtAge1").val()),
        gender: $("#gender_type1").val(),
        dob: dob,
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,

        address_id: $('#txtJaddressid1').val(),
        address_line_1: $('#txtJLine1').val(),
        address_line_2: $('#txtJLine2').val(),
        country: $('#txtJCountry').val(),
        state: $('#txtJState').val(),
        city: $('#txtJCity').val(),
        pincode: $('#txtJpincode').val(),
        doctor_patient_id: $('#txtdoctor_patient_id1').val(),
        patient_blood_group: $("#bg_type1").val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation1').val(),
        marital_status: $('#selMaritalStatus1').val(),

        preferred_language: $('#txtPreferedLanguage').val(),
        referral_source: referralList.toString(),
        passport_no: $('#txtPassportNo').val(),
        visa_no: $('#txtVisaNo').val(),
        visa_type: $('#txtVisaType').val(),
        visa_validity: visa_validity,
        formc_status: $('#txtFormCStatus').val(),
        occupation: $('#txtOccupation').val(),
        annual_income: $('#annual_income').val(),
        name_of_employer: $('#txtNameofEmployer').val(),
        designation: $('#txtDesignation').val(),
        work_location: $('#txtWorkLocation').val(),
        work_address: $('#txtWorkLocationAddress').val(),
        nationality: $('#nationality_type').val(),
        religion: $('#txtReligion').val(),


        Jaddress_id: $('#txtJaddressid2').val(),
        Jaddress_line_1: $('#txtJPLine1').val(),
        Jaddress_line_2: $('#txtJPLine2').val(),
        Jcountry: $('#txtJCountry2').val(),
        Jstate: $('#txtJState2').val(),
        Jcity: $('#txtJCity2').val(),
        Jpincode: $('#txtJpincode2').val(),
        JisSameAddress: ($('#chkIsSameAddress').prop('checked') == true) ? "1" : "0",
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),

        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#reg-patient-details').html('');
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something went wrong');
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $.each(data1.Table, function (i, emp) {
                        var result = emp.StringMsg
                        if (result == 'Phone already registerd') {
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsertForDetailCreation('2');
                            } else {
                                $('#Ptxtmobileno2').show();
                                $('#Ptxtmobileno2').fadeOut(8000);
                                $('#Ptxtmobileno2').html('Mobile number exists');
                                $('#txtmobileno2').focus();
                                $('#txtmobileno2').val('');
                                //alert('Why did you press cancel? You should have confirmed');
                            }
                            return false;
                        }
                        else if (result == 'Updated') {
                            window.location.href = "/PatientSearch/";
                            return false;
                        }
                        else if (result == 'listofpatient') {
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            console.log(data1.Table);
                            for (var i = 0; i < data1.Table.length; i++) {
                                debugger;
                                var gender = '-', address = '', dob = '-', image = '';
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }

                                if (data1.Table[i].address != null || data1.Table[i].address != "" || data1.Table[i].address != "null") {
                                    address = data1.Table[i].address;
                                }
                                if (data1.Table[i].town_village != null || data1.Table[i].town_village != "" || data1.Table[i].town_village != "null") {
                                    address = address + " " + data1.Table[i].town_village;
                                }
                                address = address + " " + data1.Table[i].pincode;
                                if (data1.Table[i].dob != null || data1.Table[i].dob != "" || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == "") {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                //tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><div class="selector"><div class="selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[i].patient_id + '</p><div class="row"><div class="col-sm-12"><p class="eu-pat-gender">DOB : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-12"><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></div></div>';

                                // tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><span>' + name + '</span></label>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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>';

                            //  tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><span>+ New Patient</span></label>';
                            $('#reg-patient-details').html(tr);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            toastr.success('Patient data saved successfully');
                            $('#txtuserName1').val('');
                            $('#txtmobileno2').val('');
                            $('#txtAge1').val('');
                            $('#txtDOB1').val('');
                            $('#Selbloodgroup').val(0);
                            $('#txtEmailid1').val('');
                            $('#Chkmobileno1').prop('checked', false);
                            $('#txtJaddressid1').val(),
                                $('#txtJLine1').val(''),
                                $('#txtJLine2').val(''),
                                $('#txtJCountry').val(''),
                                $('#txtJState').val(''),
                                $('#txtJCity').val(''),
                                $('#txtJpincode').val(''),
                                $('#txtreferby').val(''),
                                $('#txtdoctor_patient_id').val(''),
                                $('#selSalutation1').val(0),
                                $('#selMaritalStatus1').val(0)
                            $("input[name='optradio1']:checked").prop("checked", false);
                            $("input[name='optradio']:checked").prop("checked", false);
                            $('#gender_type1').val('');
                            $('a[data-toggle=gender_type1]').removeClass('active');
                            $('a[data-toggle=gender_type1]').addClass('not-active');

                            $('#nationality_type').val('');
                            $('a[data-toggle=nationality_type]').removeClass('active');
                            $('a[data-toggle=nationality_type]').addClass('not-active');

                            $('#annual_income').val('');
                            $('a[data-toggle=annual_income]').removeClass('active');
                            $('a[data-toggle=annual_income]').addClass('not-active');

                            $('#txtPreferedLanguage').val(''),
                                $('#txtPassportNo').val(''),
                                $('#txtVisaNo').val(''),
                                $('#txtVisaType').val(''),
                                $('#txtFormCStatus').val(''),
                                $('#txtOccupation').val(''),
                                $('#annual_income').val(''),
                                $('#txtNameofEmployer').val(''),
                                $('#txtDesignation').val(''),
                                $('#txtWorkLocation').val(''),
                                $('#txtWorkLocationAddress').val(''),
                                $('#nationality_type').val(''),
                                $('#txtReligion').val(''),

                                $('#txtJaddressid2').val(''),
                                $('#txtJPLine1').val(''),
                                $('#txtJPLine2').val(''),
                                $('#txtJCountry2').val(''),
                                $('#txtJState2').val(''),
                                $('#txtJCity2').val(''),
                                $('#txtJpincode2').val(''),
                                $('#chkIsSameAddress').prop('checked', false);
                        }
                    });
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}



$("#BtnDetailsSubmit").click(function () {
    debugger;
    if ($.trim($('#selSalutation1').val()) == 0) {
        $('#PselSalutation1').show();
        $('#PselSalutation1').fadeOut(8000);
        $('#PselSalutation1').html('Select Salutation');
        $('#selSalutation1').focus();
        $('#selSalutation1').val(0);
        return false;
    }

    if ($.trim($('#txtuserName1').val()) == "") {
        $('#PtxtuserName1').show();
        $('#PtxtuserName1').fadeOut(8000);
        $('#PtxtuserName1').html('Enter The Patient Name');
        $('#txtuserName1').focus();
        $('#txtuserName1').val('');
        return false;
    }

    if ($.trim($("#txtuserName1").val()).length < 2) {
        $('#PtxtuserName1').show();
        $('#PtxtuserName1').fadeOut(8000);
        $('#PtxtuserName1').html('You must have enter minimum of 2 characters');
        $('#txtuserName1').focus();
        $('#txtuserName1').val('');
        return false;
    }

    if ($.trim($('#txtAge1').val()) == "") {
        if ($.trim($('#txtDOB1').val()) == "") {
            $('#PtxtDOB1').show();
            $('#PtxtDOB1').fadeOut(8000);
            $('#PtxtDOB1').html('Enter date of birth');
            $('#txtDOB1').focus();
            $('#txtDOB1').val('');
            return false;
        }
    }

    if ($.trim($("#gender_type1").val()) == "") {
        $('#PSelGender1').show();
        $('#PSelGender1').fadeOut(8000);
        $('#PSelGender1').html('Select The Gender');
        $('#SelGender1').focus();
        $('#SelGender1').val('');

        return false;
    }

    if ($.trim($('#selMaritalStatus1').val()) == 0) {
        $('#PMaritalStatus1').show();
        $('#PMaritalStatus1').fadeOut(8000);
        $('#PMaritalStatus1').html('Select Marital Status');
        $('#selMaritalStatus1').focus();
        $('#selMaritalStatus1').val(0);
        return false;
    }

    if ($.trim($("#nationality_type").val()) == "") {
        $('#Pnationality_type').show();
        $('#Pnationality_type').fadeOut(8000);
        $('#Pnationality_type').html('Select Nationality');
        $('#nationality_type').focus();
        $('#nationality_type').val('');
        return false;
    }

    if ($('#Chkmobileno1').prop("checked") == true) {
    }
    else {
        if ($.trim($('#txtmobileno2').val()) == " ") {
            $('#Ptxtmobileno2').show();
            $('#Ptxtmobileno2').fadeOut(8000);
            $('#Ptxtmobileno2').html('Enter The Moblie No');
            $('#txtmobileno2').focus();
            $('#txtmobileno2').val('');
            return false;
        }
        if ($.trim($('#txtmobileno2').val()).length > 10) {
            $('#Ptxtmobileno2').show();
            $('#Ptxtmobileno2').fadeOut(8000);
            $('#Ptxtmobileno2').html('Invalid Moblie No');
            $('#txtmobileno2').focus();
            $('#txtmobileno2').val('');
            return false;
        }
    }

    if ($('#UM_124').css('display') != 'none') {
        if ($("#txtJLine1").val() == "") {
            $('#PtxtJLine1').show();
            $('#PtxtJLine1').fadeOut(8000);
            $('#PtxtJLine1').html('Enter Address');
            $('#txtJLine1').focus();
            $('#txtJLine1').val('');
            return false;
        }
    }
    if ($.trim($("#txtJpincode").val()) == "") {
        $('#PtxtJpincode').show();
        $('#PtxtJpincode').fadeOut(8000);
        $('#PtxtJpincode').html('Enter Pincode');
        $('#txtJpincode').focus();
        $('#txtJpincode').val('');
        return false;
    }

    if ($.trim($("#txtJCountry").val()) == 0) {
        $('#PtxtJCountry').show();
        $('#PtxtJCountry').fadeOut(8000);
        $('#PtxtJCountry').html('Select Country');
        $('#txtJCountry').focus();
        $('#txtJCountry').val(0);
        return false;
    }
    if ($.trim($("#txtJState").val()) == 0) {
        $('#PtxtJState').show();
        $('#PtxtJState').fadeOut(8000);
        $('#PtxtJState').html('Select State');
        $('#PtxtJState').focus();
        $('#txtJState').val(0);
        return false;
    }
    if ($.trim($("#txtJCity").val()) == 0) {
        $('#PtxtJCity').show();
        $('#PtxtJCity').fadeOut(8000);
        $('#PtxtJCity').html('Select City');
        $('#txtJCity').focus();
        $('#txtJCity').val(0);
        return false;
    }
    if ($.trim($("#txtuserName1").val()).length > 0) {
        $('#btncheckval').val("1");
        DirectDetailPatientInsert();
    }
});

$('#selSalutation').change(function () {
    debugger;
    $('#Gender_male').removeClass('disabled');
    $('#Gender_Others').removeClass('disabled');
    $('#Gender_Female').removeClass('disabled');

    if ($('#selSalutation').val() == 3) {
        $('#Gender_male').click();
        $('#Gender_Female').addClass('disabled');
        $('#Gender_Others').addClass('disabled');

    }
    else if ($('#selSalutation').val() == 6 || $('#selSalutation').val() == 1) {
        $('#Gender_Female').click();
        $('#Gender_male').addClass('disabled');
        $('#Gender_Others').addClass('disabled');
    }
    else {
        $('a[data-toggle=gender_type]').removeClass('active');
        $('a[data-toggle=gender_type]').addClass('not-active');
    }

    if ($('#selSalutation').val() == 6) {
        $('#selMaritalStatus').val(1);
    }
    else {
        $('#selMaritalStatus').val(0);
    }

})

//$('#selMaritalStatus').change(function () {
//    debugger;
//    if ($('#txtAge').val() < 18 && $('#selMaritalStatus').val() == 1 || $('#selMaritalStatus').val() == 3) {
//        $('#PMaritalStatus').html('Invalid Marital Status');
//        $('#selMaritalStatus').focus();
//        $('#selMaritalStatus').val(0);
//    }
//    else {
//        $('#PMaritalStatus').html('');
//    } 
//})
$('#selMaritalStatus').change(function () {
    debugger;
    if ($('#txtAge').val() < 18) {
        debugger;
        if ($('#selMaritalStatus').val() == 1 || $('#selMaritalStatus').val() == 3) {
            debugger;
            $('#PMaritalStatus').html('Invalid Marital Status');
            $('#selMaritalStatus').focus();
            $('#selMaritalStatus').val(0);
        }
        else {
            $('#PMaritalStatus').html('');
        }
    }
    else {
        $('#PMaritalStatus').html('');
    }

})


function DirectDetailPatientInsert() {
    debugger;
    var patient_id, PName;
    var Dml_Indicator = "I";
    var individual_id = '';
    if ($('#BtnDetailsSubmit').html() == "Update") {
        Dml_Indicator = "U";
        individual_id = $('#Individual_id').val();

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

    var referralList = [];
    $.each($("input[name='chkReferralSource']:checked"), function () {
        referralList.push($(this).val());
    });

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

    var DirectPatientData = {
        patient_first_name: $("#txtuserName1").val(),
        patient_phone_number: $.trim($("#txtmobileno2").val()),
        P_patient_phone_number: $.trim($("#txtmobileno3").val()),
        patient_email_id: $.trim($("#txtEmailid1").val()),
        age: $.trim($("#txtAge1").val()),
        gender: $("#gender_type1").val(),
        dob: dob,
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,

        address_id: $('#txtJaddressid1').val(),
        address_line_1: $('#txtJLine1').val(),
        address_line_2: $('#txtJLine2').val(),
        country: $('#txtJCountry').val(),
        state: $('#txtJState').val(),
        city: $('#txtJCity').val(),
        pincode: $('#txtJpincode').val(),
        doctor_patient_id: $('#txtdoctor_patient_id1').val(),
        patient_blood_group: $("#bg_type1").val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation1').val(),
        marital_status: $('#selMaritalStatus1').val(),

        preferred_language: $('#txtPreferedLanguage').val(),
        referral_source: referralList.toString(),
        passport_no: $('#txtPassportNo').val(),
        visa_no: $('#txtVisaNo').val(),
        visa_type: $('#txtVisaType').val(),
        visa_validity: visa_validity,
        formc_status: $('#txtFormCStatus').val(),
        occupation: $('#txtOccupation').val(),
        annual_income: $('#annual_income').val(),
        name_of_employer: $('#txtNameofEmployer').val(),
        designation: $('#txtDesignation').val(),
        work_location: $('#txtWorkLocation').val(),
        work_address: $('#txtWorkLocationAddress').val(),
        nationality: $('#nationality_type').val(),
        religion: $('#txtReligion').val(),

        Jaddress_id: $('#txtJaddressid2').val(),
        Jaddress_line_1: $('#txtJPLine1').val(),
        Jaddress_line_2: $('#txtJPLine2').val(),
        Jcountry: $('#txtJCountry2').val(),
        Jstate: $('#txtJState2').val(),
        Jcity: $('#txtJCity2').val(),
        Jpincode: $('#txtJpincode2').val(),
        JisSameAddress: ($('#chkIsSameAddress').prop('checked') == true) ? "1" : "0",
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),

        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#reg-patient-details').html('');
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something went wrong');
            }
            else {

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

                    $.each(data1.Table, function (i, emp) {
                        var result = emp.StringMsg
                        if (result == 'Phone already registerd') {
                            $('#Ptxtmobileno2').show();
                            $('#Ptxtmobileno2').fadeOut(8000);
                            $('#txtmobileno2').focus();
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsertForDetailCreation('1');
                            } else {
                                $('#Ptxtmobileno2').show();
                                $('#Ptxtmobileno2').fadeOut(8000);
                                $('#Ptxtmobileno2').html('Mobile number exists');
                                $('#txtmobileno2').focus();
                                $('#txtmobileno2').val('');

                            }
                            return false;
                        }
                        else if (result == 'Updated') {

                            window.location.href = "/PatientSearch/";
                            return false;
                        }
                        else if (result == 'listofpatient') {
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            for (var i = 0; i < data1.Table.length; i++) {
                                var gender = '-', address = '', dob = '-', image = '';
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }

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

                                if (data1.Table[i].dob != null || data1.Table[i].dob != '' || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == '') {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                ////tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><div class="selector"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[i].patient_id + '</p><div class="row"><div class="col-sm-12"><p class="eu-pat-gender">DOB : <span class="spn-strong"> ' + dob + ' </span></p></div><div class="col-sm-12"><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></div>';

                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><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 phone = emp.P_patient_phone_number;
                            patient_id = emp.StringMsg;
                            PName = emp.P_patient_first_name;
                            window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;

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

        }

    });
}


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

    var referralList = [];
    $.each($("input[name='chkReferralSource']:checked"), function () {
        referralList.push($(this).val());
    });

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

    var returnval = val;
    var DirectPatientData = {
        patient_first_name: $("#txtuserName1").val(),
        patient_phone_number: $.trim($("#txtmobileno2").val()),
        patient_email_id: $.trim($("#txtEmailid1").val()),
        age: $.trim($("#txtAge1").val()),
        gender: $("#gender_type1").val(),
        dob: dob,
        Dml_Indicator: 'MI',
        patient_id: individual_id,

        address_id: $('#txtJaddressid1').val(),
        address_line_1: $('#txtJLine1').val(),
        address_line_2: $('#txtJLine2').val(),
        country: $('#txtJCountry').val(),
        state: $('#txtJState').val(),
        city: $('#txtJCity').val(),
        pincode: $('#txtJpincode').val(),
        doctor_patient_id: $('#txtdoctor_patient_id1').val(),
        patient_blood_group: $("#bg_type1").val(),
        salutation: $('#selSalutation1').val(),
        marital_status: $('#selMaritalStatus1').val(),

        preferred_language: $('#txtPreferedLanguage').val(),
        referral_source: referralList.toString(),
        passport_no: $('#txtPassportNo').val(),
        visa_no: $('#txtVisaNo').val(),
        visa_type: $('#txtVisaType').val(),
        visa_validity: visa_validity,
        formc_status: $('#txtFormCStatus').val(),
        occupation: $('#txtOccupation').val(),
        annual_income: $('#annual_income').val(),
        name_of_employer: $('#txtNameofEmployer').val(),
        designation: $('#txtDesignation').val(),
        work_location: $('#txtWorkLocation').val(),
        work_address: $('#txtWorkLocationAddress').val(),
        nationality: $('#nationality_type').val(),
        religion: $('#txtReligion').val(),

        Jaddress_id: $('#txtJaddressid2').val(),
        Jaddress_line_1: $('#txtJPLine2').val(),
        Jaddress_line_2: $('#txtJPLine2').val(),
        Jcountry: $('#txtJCountry2').val(),
        Jstate: $('#txtJState2').val(),
        Jcity: $('#txtJCity2').val(),
        Jpincode: $('#txtJpincode2').val(),
        JisSameAddress: ($('#chkIsSameAddress').prop('checked') == true) ? "1" : "0",
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),
        agemonth: $('#agemonths').val(),

        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $.each(data1.Table, function (i, emp) {
                        if (returnval == 1) {
                            var phone = emp.P_patient_phone_number;
                            patient_id = emp.StringMsg;
                            PName = emp.P_patient_first_name;
                            window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                        }
                        else if (returnval == 3) {
                            toastr.success('Patient data saved successfully');
                            window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                        }
                        else {
                            toastr.success('Patient created successfully');
                            $('#txtuserName1').val('');
                            $('#txtmobileno2').val('');
                            $('#txtAge1').val('');
                            $('#txtDOB1').val('');
                            $('#Selbloodgroup').val(0);
                            $('#txtEmailid1').val('');
                            $('#Chkmobileno1').prop('checked', false);
                            $('#txtJaddressid1').val(),
                                $('#txtJLine1').val(''),
                                $('#txtJLine2').val(''),
                                $('#txtJCountry').val(''),
                                $('#txtJState').val(''),
                                $('#txtJCity').val(''),
                                $('#txtJpincode').val(''),
                                $('#txtreferby').val(''),
                                $('#txtdoctor_patient_id').val(''),
                                $('#selSalutation1').val(0),
                                $('#selMaritalStatus1').val(0)
                            $("input[name='optradio1']:checked").prop("checked", false);
                            $("input[name='optradio']:checked").prop("checked", false);

                            $('#gender_type1').val('');
                            $('a[data-toggle=gender_type1]').removeClass('active');
                            $('a[data-toggle=gender_type1]').addClass('not-active');

                            $('#nationality_type').val('');
                            $('a[data-toggle=nationality_type]').removeClass('active');
                            $('a[data-toggle=nationality_type]').addClass('not-active');

                            $('#bg_type1').val('');
                            $('a[data-toggle=bg_type1]').removeClass('active');
                            $('a[data-toggle=bg_type1]').addClass('not-active');

                            $('#annual_income').val('');
                            $('a[data-toggle=annual_income]').removeClass('active');
                            $('a[data-toggle=annual_income]').addClass('not-active');

                            $('#txtPreferedLanguage').val(''),
                                $('#txtPassportNo').val(''),
                                $('#txtVisaNo').val(''),
                                $('#txtVisaType').val(''),
                                $('#txtFormCStatus').val(''),
                                $('#txtOccupation').val(''),
                                $('#annual_income').val(''),
                                $('#txtNameofEmployer').val(''),
                                $('#txtDesignation').val(''),
                                $('#txtWorkLocation').val(''),
                                $('#txtWorkLocationAddress').val(''),
                                $('#nationality_type').val(''),
                                $('#txtReligion').val(''),

                                $('#txtJaddressid2').val(''),
                                $('#txtJPLine1').val(''),
                                $('#txtJPLine2').val(''),
                                $('#txtJCountry2').val(''),
                                $('#txtJState2').val(''),
                                $('#txtJCity2').val(''),
                                $('#txtJpincode2').val(''),
                                $('#chkIsSameAddress').prop('checked', false);

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

            }
        }
    });
}


function DetailPatientList() {
    debugger;
    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 = $('#txtDOB1').val();
    if (dob == '') {
        dob = '';
    }
    else {
        var a = dob.split('/');
        dob = a[2] + '-' + a[1] + '-' + a[0];
    }

    var referralList = [];
    $.each($("input[name='chkReferralSource']:checked"), function () {
        referralList.push($(this).val());
    });

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

    var DirectPatientData = {
        patient_first_name: $("#txtuserName1").val(),
        patient_phone_number: $.trim($("#txtmobileno2").val()),
        patient_email_id: $.trim($("#txtEmailid1").val()),
        age: $.trim($("#txtAge1").val()),
        gender: $("#gender_type1").val(),
        dob: dob,
        Dml_Indicator: Dml_Indicator,
        patient_id: individual_id,

        address_id: $('#txtJaddressid1').val(),
        address_line_1: $('#txtJLine1').val(),
        address_line_2: $('#txtJLine2').val(),
        country: $('#txtJCountry').val(),
        state: $('#txtJState').val(),
        city: $('#txtJCity').val(),
        pincode: $('#txtJpincode').val(),
        doctor_patient_id: $('#txtdoctor_patient_id1').val(),
        patient_blood_group: $("#bg_type1").val(),
        product_code: $('#HProductCode').val(),
        salutation: $('#selSalutation1').val(),
        marital_status: $('#selMaritalStatus1').val(),

        preferred_language: $('#txtPreferedLanguage').val(),
        referral_source: referralList.toString(),
        passport_no: $('#txtPassportNo').val(),
        visa_no: $('#txtVisaNo').val(),
        visa_type: $('#txtVisaType').val(),
        visa_validity: visa_validity,
        formc_status: $('#txtFormCStatus').val(),
        occupation: $('#txtOccupation').val(),
        annual_income: $('#annual_income').val(),
        name_of_employer: $('#txtNameofEmployer').val(),
        designation: $('#txtDesignation').val(),
        work_location: $('#txtWorkLocation').val(),
        work_address: $('#txtWorkLocationAddress').val(),
        nationality: $('#nationality_type').val(),
        religion: $('#txtReligion').val(),

        Jaddress_id: $('#txtJaddressid2').val(),
        Jaddress_line_1: $('#txtJPLine1').val(),
        Jaddress_line_2: $('#txtJPLine2').val(),
        Jcountry: $('#txtJCountry2').val(),
        Jstate: $('#txtJState2').val(),
        Jcity: $('#txtJCity2').val(),
        Jpincode: $('#txtJpincode2').val(),
        JisSameAddress: ($('#chkIsSameAddress').prop('checked') == true) ? "1" : "0",
        patient_last_name: $('#txtSecondName').val(),
        father_name: $('#txtFatherName').val(),
        second_phone_number: $('#txtSContactNo').val(),

        attender_name: $('#attenderName').val(),
        attender_relationship: $('#attenderNameRelationship').val(),
        attender_phone_number: $('#attenderPhonenumber').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DirectPatientData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
                toastr.warning('Something went wrong');
            }
            else {

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

                        var result = data.Table[0].StringMsg;
                        if (result == 'Phone already registerd') {
                            $('#Ptxtmobileno').show();
                            $('#Ptxtmobileno').fadeOut(8000);
                            $('#txtmobileno').focus();
                            if (confirm('The patient mobile number is already exists do you want to add same mobile number for the family mumber ?')) {
                                secondmobileInsertForDetailCreation('1');
                            } else {
                                $('#Ptxtmobileno').show();
                                $('#Ptxtmobileno').fadeOut(8000);
                                $('#Ptxtmobileno').html('Mobile number exists');
                                $('#txtmobileno').focus();
                                $('#txtmobileno').val('');
                                //alert('Why did you press cancel? You should have confirmed');
                            }
                            return false;
                        }
                        else if (result == 'Updated') {
                            window.location.href = "/PatientSearch/";
                            return false;
                        }
                        else if (result == 'listofpatient') {
                            $('#customerRegistration').modal('show');
                            var tr = '';
                            console.log(data1.Table);
                            debugger;
                            for (var i = 0; i < data1.Table.length; i++) {
                                var gender = '-', address = '', dob = '-', image = '';
                                if (data1.Table[i].gender == "1") {
                                    gender = 'Male';
                                }
                                else if (data1.Table[i].gender == "2") {
                                    gender = 'Female';
                                }

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

                                if (data1.Table[i].dob != null || data1.Table[i].dob != '' || data1.Table[i].dob != 'null') {
                                    dob = data1.Table[i].dob;
                                }
                                if (data1.Table[i].photo == null || data1.Table[i].photo == '') {
                                    image = "/Content/img/profile_icon.png";
                                }
                                else {
                                    image = $('#patphotop').val() + data.Table[i].photo;
                                }
                                //tr = tr + '<div class="col-md-6 reg-patient-details"><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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 selectedcard"><label class="radio-inline"><input type="radio" name="patientlist" value="' + data1.Table[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.Table[i].first_name + ' <span class="eu-pat-age">(' + data1.Table[i].age + ')</span></p><p class="eu-pat-id">' + data1.Table[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 + '<label class="radio-inline"><input type="radio" name="patientlist" value="' + data1[i].individual_id + '"><span>' + name + '</span></label>';
                            }
                            tr = tr + '<div class="col-md-6 reg-patient-details selectedcard"><div class="selector"><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></div>';

                            //  tr = tr + '<label class="radio-inline"><input type="radio" name="patientlist" name="patientlist" value="New"><span>+ New Patient</span></label>';
                            $('#reg-patient-details').html(tr);
                            $('#btnlist').html('Submit');
                        }
                        else {
                            if (btnval == 1) {
                                var phone = data.Table[0].P_patient_phone_number;
                                patient_id = data.Table[0].StringMsg;
                                PName = data.Table[0].P_patient_first_name;
                                window.location.href = "/DirectPatientEnroll/AppointmentSlot?patient_id=" + patient_id + "&PName=" + PName;
                            }
                            else if (btnval == 3) {
                                toastr.success('Patient data saved successfully');
                                window.location.href = "/ReferralManagement?RefID=" + $('#RefID').val();
                            }
                            else {
                                toastr.success('Patient data saved successfully');
                                $('#txtuserName1').val('');
                                $('#txtmobileno2').val('');
                                $('#txtAge1').val('');
                                $('#txtDOB1').val('');
                                $('#Selbloodgroup').val(0);
                                $('#txtEmailid1').val('');
                                $('#Chkmobileno1').prop('checked', false);
                                $('#txtJaddressid1').val(),
                                    $('#txtJLine1').val(''),
                                    $('#txtJLine2').val(''),
                                    $('#txtJCountry').val(''),
                                    $('#txtJState').val(''),
                                    $('#txtJCity').val(''),
                                    $('#txtJpincode').val(''),
                                    $('#txtreferby').val(''),
                                    $('#txtdoctor_patient_id').val(''),
                                    $('#selSalutation1').val(0),
                                    $('#selMaritalStatus1').val(0)
                                $("input[name='optradio1']:checked").prop("checked", false);
                                $("input[name='optradio']:checked").prop("checked", false);

                                $('#gender_type1').val('');
                                $('a[data-toggle=gender_type1]').removeClass('active');
                                $('a[data-toggle=gender_type1]').addClass('not-active');

                                $('#nationality_type').val('');
                                $('a[data-toggle=nationality_type]').removeClass('active');
                                $('a[data-toggle=nationality_type]').addClass('not-active');

                                $('#bg_type1').val('');
                                $('a[data-toggle=bg_type1]').removeClass('active');
                                $('a[data-toggle=bg_type1]').addClass('not-active');

                                $('#annual_income').val('');
                                $('a[data-toggle=annual_income]').removeClass('active');
                                $('a[data-toggle=annual_income]').addClass('not-active');
                                $('#txtPreferedLanguage').val(''),
                                    $('#txtPassportNo').val(''),
                                    $('#txtVisaNo').val(''),
                                    $('#txtVisaType').val(''),
                                    $('#txtFormCStatus').val(''),
                                    $('#txtOccupation').val(''),
                                    $('#annual_income').val(''),
                                    $('#txtNameofEmployer').val(''),
                                    $('#txtDesignation').val(''),
                                    $('#txtWorkLocation').val(''),
                                    $('#txtWorkLocationAddress').val(''),
                                    $('#nationality_type').val(''),
                                    $('#txtReligion').val(''),

                                    $('#txtJaddressid2').val(''),
                                    $('#txtJPLine1').val(''),
                                    $('#txtJPLine2').val(''),
                                    $('#txtJCountry2').val(''),
                                    $('#txtJState2').val(''),
                                    $('#txtJCity2').val(''),
                                    $('#txtJpincode2').val(''),
                                    $('#attenderName').val(''),
                                    $('#attenderNameRelationship').val(''),
                                    $('#attenderPhonenumber').val(''),
                                    $('#chkIsSameAddress').prop('checked', false);
                                $('.close').click();
                            }
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        }

    });
}

$('#chkIsSameAddress').change(function () {
    if ($('#chkIsSameAddress').prop('checked') == true) {
        $('#txtJPLine1').val($('#txtJLine1').val());
        $('#txtJPLine2').val($('#txtJLine2').val());
        $('#txtJpincode2').val($('#txtJpincode').val());
        country = ($('#txtJCountry').val());
        console.log(country);
        $('#txtJCountry2').val(country);
        state = ($('#txtJState').val());
        city = ($('#txtJCity').val());
        console.log(state);
        stateJ2(country, state, city);
        //$('#txtJState2').val(state);

        //console.log(city);
        //$('#txtJCity2').val(city);
        $('#txtJaddressid2').val($('#txtJaddressid1').val());
        $('#txtJPLine1').prop('disabled', true);
        $('#txtJPLine2').prop('disabled', true);
        $('#txtJpincode2').prop('disabled', true);
        $('#txtJCountry2').prop('disabled', true);
        $('#txtJState2').prop('disabled', true);
        $('#txtJCity2').prop('disabled', true);
    }
    else {
        $('#txtJPLine1').val('');
        $('#txtJPLine2').val('');
        $('#txtJpincode2').val('');
        $('#txtJCountry2').val('');
        $('#txtJState2').val('');
        $('#txtJCity2').val('');
        $('#txtJaddressid2').val('');
        $('#txtJPLine1').prop('disabled', false);
        $('#txtJPLine2').prop('disabled', false);
        $('#txtJpincode2').prop('disabled', false);
        $('#txtJCountry2').prop('disabled', false);
        $('#txtJState2').prop('disabled', false);
        $('#txtJCity2').prop('disabled', false);


    }
});


$("#txtJCountry").change(function () {
    var state = {
        country_id: $("#txtJCountry").val(),
        Dml_Indicator: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var state;
                    $('#txtJState').empty();
                    $('#txtJCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtJState').append(default_opt + state);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});


$("#txtJState").change(function () {
    var state = {
        state_id: $("#txtJState").val(),
        Dml_Indicator: "CI"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

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

                    $('#txtJCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtJCity').append(default_opt + City);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
});


$("#txtJCountry2").change(function () {
    var state = {
        country_id: $("#txtJCountry2").val(),
        Dml_Indicator: "S"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var state;
                    $('#txtJState2').empty();
                    $('#txtJCity2').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtJState2').append(default_opt + state);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});


$("#txtJState2").change(function () {
    var state = {
        state_id: $("#txtJState2").val(),
        Dml_Indicator: "CI"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtJCity2').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        City = City + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#txtJCity2').append(default_opt + City);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
});



function countryJ1(country_val, state_val, city_val) {
    var country = {
        Dml_Indicator: "C"
    }

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

            }
            else {

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

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

                    });
                    $('#txtJCountry').append(default_opt + Country);
                    $('#txtJCountry').val(country_val);
                    stateJ1(country_val, state_val, city_val);
                }
                else {
                    console.log(data);
                }

            }
        }
    });

}


function stateJ1(coval, stateval, city_val) {
    var state = {
        country_id: coval,
        Dml_Indicator: "S"
    }

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

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

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

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

                    });
                    $('#txtJState').append(default_opt + state);
                    $('#txtJState').val(stateval);
                    cityJ1(stateval, city_val)
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}


function cityJ1(stateval, citval) {
    var state = {
        state_id: stateval,
        Dml_Indicator: "CI"
    }

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

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtJCity').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

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

                    });
                    $('#txtJCity').append(default_opt + City);
                    $('#txtJCity').val(citval);

                }
                else {
                    console.log(data);
                }

            }
        }

    });
}



function countryJ2(country_val, state_val, city_val) {
    var country = {
        Dml_Indicator: "C"
    }

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

            }
            else {

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

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

                    });
                    //$('#txtJCountry2').append(default_opt + Country);
                    $('#txtJCountry2').append(Country);
                    $('#txtJCountry2').val(country_val);
                    stateJ2(country_val, state_val, city_val);
                }
                else {
                    console.log(data);
                }

            }
        }
    });

}


function stateJ2(coval, stateval, city_val) {
    var state = {
        country_id: coval,
        Dml_Indicator: "S"
    }

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


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

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

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

                    });
                    //$('#txtJState2').append(default_opt + state);
                    $('#txtJState2').append(state);
                    $('#txtJState2').val(stateval);
                    cityJ2(stateval, city_val)
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}


function cityJ2(stateval, citval) {
    var state = {
        state_id: stateval,
        Dml_Indicator: "CI"
    }

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

            }
            else {

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var City;
                    $('#txtJCity2').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {

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

                    });
                    $('#txtJCity2').append(default_opt + City);
                    $('#txtJCity2').val(citval);

                }
                else {
                    console.log(data);
                }

            }
        }

    });
}


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



$('#BtnDetaildelcls').click(function () {
    var overlay = document.getElementById('tblDoctorUser1');
    $('#tblDoctorUser1').modal('toggle');
})

$('#SelBranch').change(function () {
    debugger;
    CheckCodeTemplate();
    //LoadReferralType($('#SelBranch').val(), 0);
    //LoadCorporate($('#SelBranch').val(), 0);
    //ReferralDoctor($('#SelBranch').val(), 0);
});


function LoadReferralType(branchid, value) {
    debugger;
    $('#ddReferralType').empty();
    var Referral = {
        Dml_Indicator: "RFT",
        branch_id: branchid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Referral),
        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 ReferralType = '';
                    $('#ddReferralType').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        //ReferralType = ReferralType + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                        ReferralType = ReferralType + '<option value="' + emp.master_servie_type_id + '" data-id=' + emp.ref_doctor + ' >' + emp.master_service_name + '</option>';
                    });

                    $('#ddReferralType').append(default_opt + ReferralType);

                    if (value != 0) {
                        $('#ddReferralType').val(value);
                        $('#ddReferralType').change();
                    }

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

        }
    });
}

function LoadCorporate(branchid, value) {
    $('#ddCorporateName').empty();
    var Corporate = {
        Dml_Indicator: "CRN",
        branch_id: branchid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Corporate),
        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 CorporateName = '';
                    $('#ddCorporateName').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        CorporateName = CorporateName + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });

                    $('#ddCorporateName').append(default_opt + CorporateName);

                    if (value != 0) {
                        $('#ddCorporateName').val(value);
                    }

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

        }
    });
}

//load visit type
function loadvisit_type() {
    debugger;
    var data = {
        P_Dml_Indicator: 'DVT'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);

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

            }
            else {

                if (data2.msg == "Success") {

                    var data1 = data2.data;
                    if (data1[1].status == 0 && data1[6].status == 0 && data1[7].status == 0) {
                        $('#ip_reg').hide()
                        $('#day_reg').hide()
                        $('#emer_reg').hide()
                    }
                    else {
                        $('#ip_reg').show()
                        $('#day_reg').show()
                        $('#emer_reg').show()
                    }
                }
            }
        }
    })
}
$('#ddReferralType').change(function () {
    debugger;
    var did = $('#ddReferralType option:selected').attr("data-id");
    if (did == 1) {
        $('#div_refdoctor').show();
        $('#div_ddCorporateName').show();
        $('#div_txtEmployeeName').show();
        $('#div_txtEmployeeCode').show();
        $('#div_txtreferby').hide();

    }
    else if (did == 0) {
        $('#div_refdoctor').hide();
        $('#div_ddCorporateName').hide();
        $('#div_txtEmployeeName').hide();
        $('#div_txtEmployeeCode').hide();
        $('#div_txtreferby').show();
    }
    else {
        $('#div_refdoctor').hide();
        $('#div_ddCorporateName').show();
        $('#div_ddCorporateName').show();
        $('#div_txtEmployeeName').show();
        $('#div_txtEmployeeCode').show();
        $('#div_txtreferby').show();
    }
    if ($('#txtreferby').val() == 0 || $('#txtreferby').val() == '' || $('#txtreferby').val() == null) {
        loadreferby()
    }
})
$('#ddReferraldoctor').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/Ipmanagement/DoctorNameAutoCompletelist",
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "REFD", branch_id: $('#SelBranch').val() == "" || $('#SelBranch').val() == null ? $('#hBack_branchid').val() : $('#SelBranch').val() },
            success: function (data) {
                debugger;
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.doctorname, value: item.doctorname, id: item.doctorid };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HddnRefDoctorid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function loadreferby(refby) {
    //var did = $('#ddReferralType option:selected').attr("data-id");
    var selectedServiceName = $('#ddReferralType option:selected').text();
    var branchValue = $('#SelBranch').val();

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

                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    var SelRole = '';
                    $('#txtreferby').empty();
                    debugger;
                    var default_opt = '<option value="0">--Select--</option>';
                    var j = 0;
                    if (data1.length > 0) {
                        for (var i = 0; i < data1.length; i++) {
                            j++;

                            SelRole = SelRole + '<option value="' + data1[i].doctor_id + '">' + data1[i].first_name + '</option>';

                        }
                        $('#txtreferby').append(default_opt + SelRole);

                        if ($('#hiddenRole_id').val() == 1) {
                            $('#txtreferby').val($('#HiddenDoctorID').val());
                            //$('#txtreferby').attr('disabled', true);
                        }
                        if (refby != '' || refby != null) {
                            $('#txtreferby').val(refby)
                        }
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

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);
            $('#hstatus').empty();
            $('#hvisit').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;

                var status = data.data.Table[31].status;
                var visit = data.data.Table[31].master_vist_type_id;
                $('#hstatus').val(status);
                $('#hvisit').val(visit);
                if ($('#hstatus').val() == 0 && $('#hvisit').val() == 32) {
                    debugger;
                    $('#div_ddCorporateName').hide();
                    $('#div_txtEmployeeName').hide();
                    $('#div_txtEmployeeCode').hide();
                    //$('#claim').hide()
                }

            }
        }
    });
}

$('#txtpincode').autocomplete({

    source: function (request, response) {
        debugger;
        $.ajax({
            // if($('#txtpincode').length == 3){}
            async: true,
            url: '/DoctorProfile/Getpincode?PName=' + $('#txtpincode').val() + '',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term },
            success: function (data) {
                debugger;
                // var data2 = JSON.parse(data);
                var data2 = data;
                response($.map(data2, function (item) {
                    return { label: item.search + '/' + item.area + '/' + item.city + '/' + item.state, value: item.pincode, area: item.area, City: item.city, State: item.state, city_id: item.city_id, state_id: item.state_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#txtPlace').val(ui.item.area);
        $('#txtState').val(ui.item.state_id);
        load_city(ui.item.state_id, ui.item.city_id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

function Loadidproof(value) {
    debugger;
    var proofData = {
        Dml_Indicator: "LIP",
        id_proof: value
        //hospital_id: $('#HospitalId').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: 'DirectPatientEnroll/PatientEnroll',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(proofData),
        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;
                    $('#txtproof').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.proof_id + '">' + emp.id_proof + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        debugger;
                        $('#txtproof').append(SubDepartment);
                    }
                    else {
                        $('#txtproof').append(default_opt + SubDepartment);
                    }

                    //if ($('#hiddenRole_id').val() != 2) {
                    //    $('#txtproof').val($('#HospitalBranchID').val());
                    //    $('#txtproof').attr('disabled', true);
                    //}
                    if (value != 0) {
                        $('#txtproof').val(value);
                    }
                }
            }
        }
    });
}
$('#proofno').change(function () {
    debugger;
    if ($('#txtproof').val() == 1) {
        Aadharno()
    }
    if ($('#txtproof').val() == 2) {
        Pan_no()
    }
    if ($('#txtproof').val() == 3) {
        Voter_no()
    }
    if ($('#txtproof').val() == 4) {
        Ration_Card()
    }
});

function Aadharno() {
    debugger
    var regex = /^([0-9]{4}[0-9]{4}[0-9]{4}$)|([0-9]{4}\s[0-9]{4}\s[0-9]{4}$)|([0-9]{4}-[0-9]{4}-[0-9]{4}$)/;
    if (!regex.test($("#proofno").val())) {
        debugger;
        $('#Pproofno').show();
        $('#Pproofno').fadeOut(8000);
        $('#Pproofno').html('Invalid Aadhar Number');
        $("#proofno").focus();
        $('#proofno').val('');
        return false;
    }
}
function Pan_no() {
    debugger
    var regex = /[A-Z]{5}[0-9]{4}[A-Z]{1}$/;
    if (!regex.test($("#proofno").val())) {
        debugger;
        $('#Pproofno').show();
        $('#Pproofno').fadeOut(8000);
        $('#Pproofno').html('Invalid Pan Number');
        $("#proofno").focus();
        $('#proofno').val('');
        return false;
    }
}
function Voter_no() {
    debugger
    var regex = /^([a-zA-Z]) {3}([0-9]) {7}?$/g;
    if (!regex.test($("#proofno").val())) {
        debugger;
        $('#Pproofno').show();
        $('#Pproofno').fadeOut(8000);
        $('#Pproofno').html('Invalid Voter ID');
        $("#proofno").focus();
        $('#proofno').val('');
        return false;
    }
}
function Ration_Card() {
    debugger
    var regex = /^[0-9]{9}[vVxX]$|^[0-9]{1, 12}$/;
    if (!regex.test($("#proofno").val())) {
        debugger;
        $('#Pproofno').show();
        $('#Pproofno').fadeOut(8000);
        $('#Pproofno').html('Invalid Ration Card');
        $("#proofno").focus();
        $('#proofno').val('');
        return false;
    }
}


function calculateAge(dob1, today1) {
    debugger;
    var age1 = {};
    var yearDiff = today1.getFullYear() - dob1.getFullYear();
    var monthDiff = today1.getMonth() - dob1.getMonth();
    var dayDiff = today1.getDate() - dob1.getDate();

    // Check if dayDiff is negative
    if (dayDiff < 0) {
        // Calculate the number of days in the month of birth
        var daysInMonth = new Date(today1.getFullYear(), dob1.getMonth() + 1, 0).getDate();
        // Add the days in the month of birth to dayDiff to make it positive
        dayDiff += daysInMonth;
        // Subtract 1 from monthDiff to account for the extra month
        monthDiff--;
    }

    if (monthDiff < 0) {
        yearDiff--;
        monthDiff += 12;
    }
    age1.years = yearDiff;
    age1.months = monthDiff;
    age1.days = dayDiff;
    return age1;
}




$("#BtnWebCam").click(function () {
    debugger;
    $("#videoElement").show();
    $("#ImgAvatar").hide();
    $("#BtnCapture").show();
    $("#BtnWebCam").hide();

    WebCam_On_Off("On")
})


$("#BtnCapture").click(function () {
    debugger;
    $("#BtnCapture").hide();
    $("#BtnWebCam").show();
    $("#videoElement").hide();

    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    canvas.width = videoElement.videoWidth; // Set canvas width and height to match video dimensions
    canvas.height = videoElement.videoHeight;
    context.drawImage(videoElement, 0, 0, canvas.width, canvas.height);

    // Convert canvas to base64 data or Blob
    const imageData = canvas.toDataURL('image/jpeg');

    $.ajax({
        url: '/WebCam/CaptureImage',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ imageData: imageData }),
        success: function (result) {
            debugger;

            var d, n, PtImage;
            d = new Date();
            n = d.getTime();
            PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + result.img + '?' + n;
            $("#ImgAvatar").attr("src", PtImage);
            $("#HWebCamImage").val(result.img)
            $("#ImgAvatar").show();
            alert("Image captured successfully.")
            WebCam_On_Off("Off")
        },
        error: function (xhr, status, error) {
            // Handle error response from the server
            console.error(xhr.responseText);
            alert("Error capturing image.")
            $("#videoElement").show();
        }
    });
})


function WebCam_On_Off(val) {
    debugger;
    var videoElement = document.getElementById('videoElement');
    var stream = videoElement.srcObject;

    if (val === "On") {
        navigator.mediaDevices.getUserMedia({ video: true })
            .then(stream => {
                debugger;
                videoElement.srcObject = stream;
            })
            .catch(error => {
                console.error('Error accessing webcam:', error);
            });
    } else {
        if (stream) { // Check if stream is not null or undefined
            var tracks = stream.getTracks();

            tracks.forEach(track => {
                track.stop(); // Stop each track in the stream
            });

            videoElement.srcObject = null;
        }
    }
}



$("#BtnBrowse").click(function () {
    debugger;
    $('#PatientImage').click();
})

$('#PatientImage').change(function () {
    PatientImageUpload();
});

function PatientImageUpload() {
    debugger;

    $("#videoElement").hide();
    $("#BtnCapture").hide();
    $("#BtnWebCam").show();

    WebCam_On_Off("Off")

    var uploadpath = $('#PatientImage').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (fileExtension == "jpg" || fileExtension == "jpeg" || fileExtension == "png") {
    }
    else {
        $('#PPatientImage').show();
        $('#PPatientImage').fadeOut(8000);
        $('#PPatientImage').html('Please upload file having extensions .jpg/.jpeg/.png only.');
        $('#PPatientImage').val('');
        $('#PPatientImage').focus();
        return false;
    }
    if (window.FormData !== undefined) {
        var fileUpload = $("#PatientImage").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();
        for (var i = 0; i < files.length; i++) {
            fileData.append(files[i].name, files[i]);
        }
        fileData.append('username', 'Manas');
        $.ajax({
            url: 'DirectPatientEnroll/UploadPatientImages',
            type: "POST",
            contentType: false,
            processData: false,
            data: fileData,
            success: function (result) {
                debugger;
                $('#PatientImage-photo').empty();
                $('#PatientImage-photo').show();
                var d, n, PtImage;
                d = new Date();
                n = d.getTime();
                PtImage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/PatientImage/' + result.img + '?' + n;
                $('#PatientImage-photo').append('<a href="' + PtImage + '" target="_blank">Proof</a>');
                $("#ImgAvatar").attr("src", PtImage);
                $("#HWebCamImage").val(result.img)
                $("#ImgAvatar").show();
            }
        });
    }
}

