
$(document).ready(function () {
    Load_DonorTable()
    load_state()
});
$('#pldonor_register').click(function () {
    debugger;
    Load_DonorTable();
    $('.asidefilterclass').addClass('hidden');
    $('#asideDonor_Register').removeClass('hidden');
    $('.groupclass').addClass('hidden');
    $('#asideDonor_Registergroupclass').removeClass('hidden');
    $('.Filterclass').addClass('hidden');
    $('#asideDonor_RegisterFilterclass').removeClass('hidden');

});
$('#DR_filter').click(function () {
    Load_DonorTable();
})
$('#DR_clear').click(function () {
    $('#DRFdonor_name').val('');
    $('#DRtxtreg_date').val('');
    $('#DRFbldgrp').val('');
    $('#DRFmobileno').val('');
    $('#DRFgender').val(0);
    Load_DonorTable();
})

$('#donor_dob').change(function () {
    debugger;

    var dob = $('#donor_dob').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));
        $('#donor_age').val(age);
    }
    else {
        $('#donor_age').val('');
        $('#donor_age').attr('disabled', false);
    }

});


$('#donorsubmit').click(function () {
    debugger;
    if ($.trim($('#donorname').val()) == "") {
        $('#Pdonorname').show();
        $('#Pdonorname').fadeOut(8000);
        $('#Pdonorname').html('Enter Donor Name');
        $('#donorname').focus();
        return false;
    }

    if ($.trim($('#donor_bloodgrp').val()) == "") {
        $('#Pdonor_bloodgrp').html('Select Blood Group');
        $('#Pdonor_bloodgrp').fadeIn(500).fadeOut(8000);
        $('#donor_bloodgrp').focus();
        return false;
    }

    if ($.trim($('#donor_gender').val()) == "") {
        $('#Pdonor_gender').show();
        $('#Pdonor_gender').fadeOut(8000);
        $('#Pdonor_gender').html('Select The Gender');
        $('#Pdonor_gender').focus();
        $('#donor_gender').val('');
        return false;
    }
    if ($.trim($('#bag_no').val()) == "") {
        $('#Pbag_no').show();
        $('#Pbag_no').fadeOut(8000);
        $('#Pbag_no').html('Enter Bag No');
        $('#bag_no').focus();
        return false;
    }
    if ($.trim($('#donor_dob').val()) == "") {
        $('#Pdonor_dob').show();
        $('#Pdonor_dob').fadeOut(8000);
        $('#Pdonor_dob').html('Enter DOB');
        $('#donor_dob').focus();
        return false;
    }
    if ($.trim($('#donor_age').val()) == "") {
        $('#Pdonor_age').show();
        $('#Pdonor_age').fadeOut(8000);
        $('#Pdonor_age').html('Enter Age');
        $('#donor_age').focus();
        return false;
    }
    if ($.trim($('#donor_maritial_status').val()) == 0) {
        $('#Pdonor_maritial_status').show();
        $('#Pdonor_maritial_status').fadeOut(8000);
        $('#Pdonor_maritial_status').html('Enter Maritial Status');
        $('#donor_maritial_status').focus();
        return false;
    }

    if ($.trim($('#donor_reg_source').val()) == 0) {
        $('#Pdonor_reg_source').show();
        $('#Pdonor_reg_source').fadeOut(8000);
        $('#Pdonor_reg_source').html('Enter Registration Source');
        $('#donor_reg_source').focus();
        return false;
    }

    if ($.trim($('#donor_regdate').val()) == "") {
        $('#Pdonor_regdate').show();
        $('#Pdonor_regdate').fadeOut(8000);
        $('#Pdonor_regdate').html('Enter Registration Date');
        $('#donor_regdate').focus();
        return false;
    }

    if ($('#donor_mobileno').val() != "" && $('#donor_mobileno').val().length != "10") {
        $('#Pdonor_mobileno').show();
        $('#Pdonor_mobileno').fadeOut(8000);
        $('#Pdonor_mobileno').html('Invalid Mobile Number');
        $('#donor_mobileno').focus();
        return false;
    }
    if ($.trim($('#donor_email').val()) == "") {
        $('#Pdonor_email').show();
        $('#Pdonor_email').fadeOut(8000);
        $('#Pdonor_email').html('Enter Email');
        $('#donor_email').focus();
        return false;
    }
    if ($.trim($('#donor_status').val()) == '0' || $.trim($('#donor_status').val()) == '') {
        $('#Pdonor_status').show();
        $('#Pdonor_status').fadeOut(8000);
        $('#Pdonor_status').html('select Status');
        $('#donor_status').focus();
        return false;
    }
    donor_insert()
});

function donor_insert() {
    debugger;
    var dob_date = null, reg_date = null;
    if ($('#donor_dob').val() != '') {
        var date1 = $('#donor_dob').val().split('/');
        dob_date = date1[2] + '-' + date1[1] + '-' + date1[0];
    }
    if ($('#donor_regdate').val() != '') {
        var date2 = $('#donor_regdate').val().split('/');
        reg_date = date2[2] + '-' + date2[1] + '-' + date2[0];
    }

    var indicator_id = '', donorid = ''
    if ($('#donorsubmit').html() == 'Update') {
        indicator_id = 'UP'

    }
    else {
        indicator_id = 'IS'
    }

    if ($('#Htdnid').val() == "") {
        donorid = 0
    }
    else {
        donorid = $('#Htdnid').val();
    }

    var submit = {
        Dml_Indicator: indicator_id,
        Donor_id: donorid,
        Donor_name: $('#donorname').val(),
        Donor_last_name: $('#donorlastname').val(),
        //Bag_no: $('#bag_no').val(),
        Blood_group: $('#donor_bloodgrp').val(),
        Gender: $('#donor_gender').val(),
        DOB: dob_date,
        Age: $('#donor_age').val(),
        Maritial_status: $('#donor_maritial_status').val(),
        Refno: $('#donor_refno').val(),
        Refno2: $('#donor_refno2').val(),
        Registration_source: $('#donor_reg_source').val(),
        Camp_name: $('#HdCampid').val(),
        Donor_reg_date: reg_date,
        Mobile_no: $('#donor_mobileno').val(),
        Alternate_contact_no: $('#donor_altmobileno').val(),
        Email_id: $('#donor_email').val(),
        Area: $('#donor_area').val(),
        State: $('#donor_state').val(),
        Willing_after_months: $('#donor_willing').val(),
        Address: $('#donor_address').val(),
        Status: $('#donor_status').val(),
        Remarks: $('#donor_remarks').val(),
        Hospital_id: $('#HospitalId').val(),
        Branch_id: $('#HospitalBranchID').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteDonorRegister',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(submit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;
                if (data2.Table1[0].Message == 'Inserted') {
                    toastr.success('Inserted Successfully');
                    Load_DonorTable()
                    cleardonor()
                }
                else if (data2.Table1[0].Message == 'Updated') {
                    toastr.success('Updated Successfully');
                    Load_DonorTable()
                    cleardonor()
                }
                else {
                    toastr.success('Somthing Went Wrong');
                }
                $('.nav-tabs li').removeClass('active');
                $('a[href="#donor_register"]').tab('show');
                gobackdonor()
            }
            else {
                toastr.success('Somthing Went Wrong');
            }
        },
    });
}
$('#donor_table').click(function () {
    debugger;
    $('#donorsubmit').html('Submit')
    ShowDonarBagNocode();
});
function ShowDonarBagNocode() {
    debugger;
    $('#bag_no').val('')
    var donarvalues = {
        Dml_Indicator: "DCT",
        Hospital_id: $('#HospitalId').val(),
        Branch_id: $('#HospitalBranchID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteDonorRegister',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(donarvalues),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    $('#bag_no').val(data1.Table[0].bag_no);
                    $('#bag_no').attr('disabled', true);
                }
                else {
                    console.log(data);
                }
            }

        },
        error: function (data) {
            toastr.warning("Error Occured,Please Try again later")
        }
    });

}

function Load_DonorTable() {
    debugger;
    var values = {
        Dml_Indicator: "S",
        Hospital_id: $('#HospitalId').val(),
        Donor_name: $('#DRFdonor_name').val(),
        Donor_reg_date: $('#DRtxtreg_date').val(),
        Blood_group: $('#DRFbldgrp').val(),
        Mobile_no: $('#DRFmobileno').val(),
        Gender: $('#DRFgender').val()
    }

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

                }
                else {
                    $('#tbl_donor tbody').empty();
                    $('#tbl_donor').dataTable().fnClearTable();
                    $('#tbl_donor').dataTable().fnDraw();
                    $('#tbl_donor').dataTable().fnDestroy();

                    var j = 0, b = '', tr = '', edit = '', del = '', active_inactive = '', active = '', other_info = '';

                    b = data1.Table;
                    $.each(b, function (i, emp) {
                        j++

                        var gender = '';

                        if (data1.Table[i].gender == "1") {
                            gender = 'Male';
                        }
                        else if (data1.Table[i].gender == "2") {
                            gender = 'Female';
                        }
                        else if (data1.Table[i].gender == "3") {
                            gender = 'Transgender';
                        }
                        else {
                            gender = '-';
                        }
                        edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=Donoredit(this,"' + emp.donor_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="TPAdel_' + emp.donor_id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=donordel(this,"' + emp.donor_id + '","D")><i class="fa fa-trash" aria-hidden="true"></i></a>';
                        if (emp.status == '1') {
                            active_inactive = '<span class="label label-success">Active</span>';
                            active = '<a  data-toggle="tooltip" title="Make In Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick=donordel(this,"' + emp.donor_id + '","INACT")><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + active + '</div></div>';
                        }
                        else if (emp.status == '2') {
                            active_inactive = '<span class="label label-warning">Inactive</span>';
                            active = '<a  data-toggle="tooltip" title="Make Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick=donordel(this,"' + emp.donor_id + '","ACT")><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></a>';
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' ' + active + '</div></div>';
                        }

                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.bag_no + '</td><td>' + emp.donor_name + '</td><td>' + emp.donor_reg_date + '</td><td >' + emp.blood_group + '</td><td>' + emp.mobile_no + '</td><td >' + emp.area + '</td><td >' + gender + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#tbl_donor tbody').html(tr);
                    datatable('tbl_donor', 'donor_register_list', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

function donordel(event, val, Dml_Indicator) {
    debugger;

    var status = "";
    if (Dml_Indicator == 'ACT') {
        status = "Are You Sure, Do you Want to Active the Donor Register?";
    }
    else if (Dml_Indicator == 'INACT') {
        status = "Are You Sure, Do you Want to In-active the Donor Register?";
    }
    else if (val != '') {

        status = "Are You Sure, Do you want to Delete?";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
{

    closeButton: true,
    progressBar: true,
    allowHtml: true,
    timeOut: 20000000,

    onShown: function (toast) {
        $("#confirmationRevertYes").click(function () {
            debugger;

            var servicevalues = {
                Donor_id: val,
                Dml_Indicator: Dml_Indicator

            }


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

                    var data2 = JSON.parse(data);


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

                    }
                    else {

                        if (data2.msg == "Success") {
                            debugger;
                            data1 = data2.data;
                            if (Dml_Indicator == 'D') {
                                toastr.success("Deleted Successfully ");
                                Load_DonorTable()

                            }
                            else if (Dml_Indicator == 'ACT') {
                                toastr.success("Activated Successfully");
                                Load_DonorTable()
                            }
                            else if (Dml_Indicator == 'INACT') {
                                toastr.success("In-activated Successfully");
                                Load_DonorTable()

                            }
                            else {
                                toastr.warning("Somthing Went Wrong");
                                return false;
                            }
                        }
                    }
                }
            });
        });
    }
});
}

function Donoredit(event, Id) {
    debugger;
    $('#Htdnid').val(Id)

    //$('#donor_form').show();
    //$('#tbl_donor').hide();
    //$('#donor_container_div').hide();
    //$('#donor_table').hide();

    $('#donor_form').show();
    $('#donor_table_div').hide();
    $('#divmaster').hide();
    $('#regtab').hide();
    $('#divdonor').show();


    var Edit = {
        Donor_id: Id,
        Dml_Indicator: "E"
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/BloodBank/insert_update_deleteDonorRegister',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table[0];

            $('#donorname').val(emp.donor_name),
            $('#donorlastname').val(emp.donor_last_name),

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

            $('#donor_gender').val(emp.gender),
            $('a[data-toggle=donor_gender][data-title="' + emp.gender + '"]').removeClass('not-active'),
            $('a[data-toggle=donor_gender][data-title="' + emp.gender + '"]').addClass('active'),
            $('#bag_no').val(emp.bag_no),
            $('#bag_no').attr('disabled', true),
            $('#donor_dob').val(emp.DOB),
            $('#donor_age').val(emp.age),
            $('#donor_maritial_status').val(emp.maritial_status),
            $('#donor_refno').val(emp.refno),
            $('#donor_refno2').val(emp.refno2),
            $('#donor_reg_source').val(emp.registration_source),
            $('#donor_campname').val(emp.camp_name),
            $('#donor_regdate').val(emp.donor_reg_date),
            $('#donor_mobileno').val(emp.mobile_no),
            $('#donor_altmobileno').val(emp.Alternate_contact_no),
            $('#donor_email').val(emp.Email_id),
            $('#donor_area').val(emp.area),
            //$('#donor_state').val(emp.state),
            load_state(emp.state)
            $('#donor_willing').val(emp.willing_after_months),
            $('#donor_address').val(emp.address),
            $('#donor_status').val(emp.status),
            $('#donor_remarks').val(emp.remarks),
            $('#HdCampid').val(emp.camp_id)
            $('#donorsubmit').html('Update');
        }
    })
}
function cleardonor() {
    $('#donorname').val(''),
    $('#donorlastname').val(''),
    $('#donor_dob').val(''),
    $('#donor_age').val(''),
    $('#donor_maritial_status').val(0),
    $('#donor_refno').val(''),
    $('#donor_refno2').val(''),
    $('#donor_reg_source').val(''),
    $('#donor_campname').val(''),
    $('#donor_regdate').val(''),
    $('#donor_mobileno').val(''),
    $('#donor_altmobileno').val(''),
    $('#donor_email').val(''),
    $('#donor_area').val(''),
    $('#donor_state').val(0),
    $('#donor_willing').val(0),
    $('#donor_address').val(''),
    $('#donor_status').val(0),
    $('#donor_remarks').val(''),

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

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

function load_state(id) {
    debugger;
    var state = {
        country_id: '101',
        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;
                    $('#donor_state').empty();
                    $.each(data1, function (i, emp) {
                        state = state + '<option value="' + emp.id + '">' + emp.name + '</option>';
                    });
                    $('#donor_state').append(state);

                    if (id != '' || id != null) {
                        $('#donor_state').val(id)
                    }
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

//Autocomplete Camp
$('#donor_campname').autocomplete({
    source: function (request, response) {
        debugger;
        $.ajax({
            async: true,
            url: "/BloodBank/CampAutoCompleteData?DName=" + $('#donor_campname').val(),
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "CN" },
            success: function (data) {
                debugger;
                console.log(data);
                response($.map(data, function (item) {
                    return { label: item.Camp_name, value: item.Camp_name, id: item.Camp_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HdCampid').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
})