$(document).ready(function () {
    LoadBranch();
})
/*---Tab Next Click--*/
function tab_click(id) {

    if (id == '1') {
        create_visit();

    }
    else {
        $('#bill_tab_' + (id + 1)).addClass('active');
        $('#right_tab_' + (id + 1)).addClass('active in')
        $('#bill_tab_' + id).removeClass('active');
        $('#right_tab_' + id).removeClass('active in');
    }
}
/*-----Tab 1----*/

//Load Branch
function LoadBranch() {
    debugger;
    document.getElementById("pkg_branch_id").innerHTML = null;
    var subdepartment = {
        Dml_Indicator: "LBRAN"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);

            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--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) {
                        $('#pkg_branch_id').append(SubDepartment);
                        $('#pkg_branch_id').change();
                    }
                    else {
                        $('#pkg_branch_id').append(default_opt + SubDepartment);
                    }
                    if ($('#FPatientid').val() != '' && $('#FBranchid').val() != '') {
                        $('#pkg_branch_id').val($('#FBranchid').val());
                        $('#pkg_branch_id').change();
                        loadPatient($('#FPatientid').val());
                    }
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#pkg_branch_id').change();
                    }
                    debugger;

                    if ($('#hndbranch').val() != null && $('#hndbranch').val() != '') {
                        $('#pkg_branch_id').val($('#hndbranch').val());
                        $('#pkg_branch_id').change();
                    }

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

            //debugger;
            //if (billing_type == 2) {
            //    if (billing_no != "" && billing_no != null) {
            //        billing_edit();
            //    }
            //    else {
            //        request_details();
            //    }
            //}
            //else if (billing_type == 3) {  // added by nandhini on 09/08/2022 for dashboard quick bill

            //    $('#hdnpatientapp').val($('#hndpatientid').val());
            //    $("input[name='optradio'][value='1']").prop('checked', true);
            //    var bill = PatientSearch($('#hdnpatientapp').val(), '1', $('#pkg_branch_id').val(), $('#hdnvisit_report_id').val());
            //    $.when(bill)
            //.then(function (data3) {
            //    var da1 = JSON.parse(data3);
            //    if (da1.msg == "Success") {
            //        console.log(data1);
            //        da1 = da1.data;
            //        $('#hdn_is_discount').val(da1[0].is_discount_authorization)
            //    }

            //});


            //    $('.pat-stripe-bgop').show();
            //    $('#billingDetailsWrap').hide();

            //    if ($('#hndentity').val() == 1 || $('#hndentity').val() == '1') {
            //        $('#div_claim').removeClass('hidden');
            //    }
            //    else {
            //        $('#div_claim').addClass('hidden');
            //    }
            //    $('#His_insurance').val($('#hndentity').val());
            //}
        }
    });
}
//Branch Change
$('#pkg_branch_id').change(function () {
    $('#txtPaitentSearch_bill').val('');
    if ($('#pkg_branch_id').val() == 0) {
        $('#txtPaitentSearch_bill').prop('disabled', true);

    }
    else {
        $('#txtPaitentSearch_bill').prop('disabled', false);
    }
    LoadDoctor();
    loadPatientsuggestion();
    //authorized_person();
    //LoadPayment_Type();
})
//LoadDoctor
function LoadDoctor() {
    var roleId = $('#hiddenRole_id').val();
    var DoctorId = $('#HiddenDoctorID').val();
    var DoctorData = {
        Dml_Indicator: "DL",
        hospital_id: $('#HospitalId').val(),
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CalendarConfiguration/HosiptalSelect',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data1 = JSON.parse(data)
            console.log(data1);
            if (data1.msg == "Success") {
                if (jQuery.isEmptyObject((data1.data))) {
                }
                else {
                    var tr = '';
                    var SelRole = '';
                    $('#SelDoctor').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>';
                        }
                        $('#SelDoctor,.txt_doctor_name').html(default_opt + SelRole);
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Load patient suggestion card
function loadPatientsuggestion() {
    debugger
    var DoctorData = {
        dml_indicator: 'SP',
        branch_id: $('#pkg_branch_id').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            $('#patient_suggestion').empty();
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var data_bind = '';
                    $.each(data1.Table, function (i, emp) {
                        data_bind = data_bind + ' <div class="suggest-box" id=pat_sug_div_' + (i + 1) + ' onclick=fetch_pat_suggestion(' + (i + 1) + ')><div class="pid" id=pat_sug_id_' + (i + 1) + ' data-id=' + emp.patientid + '>' + emp.patient_id + '</div> <div class="pname" id=pat_sug_name_' + (i + 1) + '>' + emp.first_name + '</div> <div class="p-mob" id=pat_sug_num_' + (i + 1) + '>' + emp.phone_number + '</div><div class="p-mob hide" id=pat_sug_search_' + (i + 1) + '>' + emp.SearchOption + '</div></div>';
                    })
                    $('#patient_suggestion').append(data_bind);
                }
            }
        }
    });
}
//Onclick for patient suggestion card
function fetch_pat_suggestion(id) {

    var pat_id = $('#pat_sug_id_' + id).html();
    var pat_search = $('#pat_sug_search_' + id).html();
    $('#txtPaitentSearch_bill').val(pat_search);
    $('#hdnpatientapp').val(pat_id);
}
//Entity Type change Function
$('.EntityType').click(function () {
    var id = $(this).val();
    if (id != 0) {
        $('#Entity').val(1);
        $('#ddInsuranceName').val('');
        $('#divInsuranceName').removeClass('hide');
        $('#divMultiPay').removeClass('hide');
        $('#divTPA').addClass('hide');
        $('#MPCIName').empty();
        $('#CMultiPay').prop('checked', false);
        if (id == 2) {
            $('#ins_chk_lbl').html('MultiPay');
            $('#ins_sel_lbl').html('Insurance Name<span class="red">*</span>');
        }
        else {
            $('#ins_chk_lbl').html('Indirect');
            $('#ins_sel_lbl').html('TPA<span class="red">*</span>');
        }
    }
    else {
        $('#Entity').val(0);
        $('#ddInsuranceName').val('');
        $('#divInsuranceName').addClass('hide');
        $('#divMultiPay').addClass('hide');
        $('#divTPA').addClass('hide');
        $('#CMultiPay').prop('checked', false);
        $('#HdnEntityid').val('');
        $('#MPCIName').val('');
    }

});
//Indirect or Multipay onchange
$('#CMultiPay').change(function () {
    debugger;
    this.value = this.checked ? 1 : 0;
    if (this.value == '1') {
        $('#divTPA').removeClass('hide');
    }
    else {
        $('#divTPA').addClass('hide');
        $('#MPCIName').val('');
    }
})
//Autocomplete for Insurance and corporate
$('#ddInsuranceName').autocomplete({

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

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

            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        $('#HdnEntityid').val(ui.item.id);
        Corporate_Insurance($('#HdnEntityid').val(), 0);
        $('#MPCIName').val(0);

    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }

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

    if (EntityType == 1) {
        dml = 'ITPA'
    }
    else if (EntityType == 2) {
        dml = 'CIN'
    }

    var Billingata = {
        Dml_Indicator: dml,
        insurance_id: Corporateid

    }

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

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

            }
            else {

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

                    var CInsurance;

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

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

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

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

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

}
//Tab 1 next-->
function create_visit() {
    if ($('#hdnvisit_report_id').val() == '') {
        var visit_type = $("input[name='optradio']:checked").val();
        if ($.trim($('#pkg_branch_id').val()) == "0") {
            $('#Ppkg_branch_id').show();
            $('#Ppkg_branch_id').fadeOut(8000);
            $('#Ppkg_branch_id').html('Please select the branch');
            $('#pkg_branch_id').focus();
            return false;
        }
        if ($.trim($('#txtPaitentSearch_bill').val()) == "") {
            $('#PtxtPaitentSearch_bill').show();
            $('#PtxtPaitentSearch_bill').fadeOut(8000);
            $('#PtxtPaitentSearch_bill').html('Please Select The Patient Name');
            $('#txtPaitentSearch_bill').focus();
            $('#txtPaitentSearch_bill').val('');
            return false;
        }

        if ($.trim($('#SelDoctor').val()) == "0") {
            $('#PSelDoctor').show();
            $('#PSelDoctor').fadeOut(8000);
            $('#PSelDoctor').html('Please select the doctor');
            $('#SelDoctor').focus();
            $('#PSelDoctor').val(0);
            return false;
        }
        if (visit_type == "" || visit_type == 0 || visit_type == undefined) {
            $('#Poptradio').show();
            $('#Poptradio').fadeOut(8000);
            $('#Poptradio').html('Please select type of appointment');
            $('#optradio').focus();
            return false;
        }
        if ($.trim($('#EntityType:checked').val()) != 0) {
            if ($.trim($('#HdnEntityid').val()) == '') {
                $('#PddInsuranceName').show();
                $('#PddInsuranceName').fadeOut(8000);
                $('#PddInsuranceName').html('Select Entity Name');
                $('#ddInsuranceName').focus();
                return false;
            }
            if ($('#CMultiPay').prop('checked') == true) {
                if ($.trim($('#MPCIName').val()) == '') {
                    $('#PMPCIName').show();
                    $('#PMPCIName').fadeOut(8000);
                    $('#PMPCIName').html('Select the field');
                    $('#PMPCIName').focus();
                    return false;
                }
            }

        }
        VisitReport_Creation();
    }



}
//--Tab 1 ends--//

//--Tab 2 Starts--//

//Visit Report Creation
function VisitReport_Creation() {
    var visit_type = $("input[name='optradio']:checked").val();
    var patient_id = $('#hdnpatientapp').val();
    var DoctorData = {
        doctor_id: $('#SelDoctor').val(),
        hospital_id: $('#HospitalId').val(),
        patient_id: $('#hdnpatientapp').val(),
        branch_id: $('#pkg_branch_id').val(),
        visit_type: visit_type,
        dml_indicator: 'I',
        is_entity: $('#Entity').val(),
        is_insurance: $('.EntityType:checked').val(),
        insurance_id: $('#HdnEntityid').val(),
        is_pay: $('#CMultiPay').val(),
        corporate_insuranceid: $('#MPCIName').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Billing_visit_report_creation_new',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table[0].StrMsg == "visit created") {
                        $('#hdnvisit_report_id').val(data1.Table[0].visit_report_id);
                        patient_card_load(patient_id, visit_type, $('#pkg_branch_id').val(), data1.Table[0].visit_report_id);
                        $('#bill_tab_2').addClass('active');
                        $('#right_tab_2').addClass('active in');
                        $('#bill_tab_1').removeClass('active');
                        $('#right_tab_1').removeClass('active in');
                        if (data1.Table[0].is_entity == 1) {
                            $('#div_claim').removeClass('hidden');
                        }
                        else {
                            $('#div_claim').addClass('hidden');
                        }
                        $('#His_insurance').val(data1.Table[0].is_entity);
                    }
                    else {
                        toastr.warning(data1.Table[0].StrMsg);
                        $('#txtPaitentSearch_bill').val('');
                    }
                    if (data1.Table1.length > 0) {

                    }


                }
                else {
                    console.log(data);
                }
            }
        }
    })
}
//Patient card Binding
function patient_card_load(patient_id, type, branch_id, visit_id) {
    var PatientSearchData = {
        visit_type: type,
        Dml_Indicator: 'LP',
        patient_id: patient_id,
        branch_id: branch_id,
        visit_report_id: visit_id
    }
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Request',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PatientSearchData),
        success: function (data) {
            console.log(data);
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                console.log(data1);
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    $('#txtPaitentSearch_1').val('');
                    toastr.warning('Something went wrong. Please try after sometime');
                    $('#bill_tab_1').addClass('active');
                    $('#right_tab_1').addClass('active in');
                    $('#bill_tab_2').removeClass('active');
                    $('#right_tab_2').removeClass('active in');
                    return false
                }
                else {
                    if (data1.length > 0) {
                        $('#Hbilling_class').val(data1[0].billing_class);
                        $('#Hwardid').val(data1[0].wardid);
                        $('#hdn_is_discount').val(data1[0].is_discount_authorization)
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    })
}

//Service autocomplete change function
function service_code(serive_val, id) {
    debugger;
    var indicator_id = '';
    if (serive_val == 0) {
        indicator_id = 'SMDD'
    }
    else {
        indicator_id = 'SMD'
    }

    var DoctorData = {
        price_matrix_id: serive_val,
        dml_indicator: indicator_id,
        master_service_id: id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            var data2 = JSON.parse(data);
            if (jQuery.isEmptyObject((data2.data))) {
            }
            else {
                debugger;
                console.log(data2);
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    if (data1.Table.length > 0) {
                        if (data1.Table[0].is_description == 1) {
                            $('#divRemarks').removeClass("hidden");
                        }
                        else {
                            $('#divRemarks').addClass("hidden");
                        }
                        if (data1.Table[0].base_amount_type == 4) {
                            $('#datetimepicker2').show();
                            $('.txt_quantity').prop('disabled', true);
                        }
                        else {
                            $('#datetimepicker2').hide();
                            $('.txt_quantity').val(1);
                        }
                        if (data1.Table[0].base_amount_type == 1 || data1.Table[0].base_amount_type == 3) {
                            $('.txt_unitRate').prop('disabled', false);
                            if (data1.Table[0].base_amount_type == 3) {
                                $('#Ptxt_unitRate').html("Enter the amount between " + data1.Table[0].range_min + ' - ' + data1.Table[0].range_max);
                                $('#Hrange_min').val(data1.Table[0].range_min);
                                $('#Hrange_max').val(data1.Table[0].range_max);
                            }
                        }
                        else {
                            $('#Ptxt_unitRate').html('');
                            $('.txt_unitRate').prop('disabled', true);
                        }
                        $('.txt_unitRate').val(data1.Table[0].actual_amount);
                        $('.txt_totalamt').html(data1.Table[0].actual_amount);
                        $('.master_service_id').val(data1.Table[0].master_service_id);
                        $('.package_id').val(data1.Table[0].package_id);
                        $('.price_matrix_id').val(data1.Table[0].price_matrix_id);
                        $('.is_doctor').val(data1.Table[0].is_doctor);
                        $('.base_amount_type').val(data1.Table[0].base_amount_type);
                        $('.txt_date').prop("disabled", false);
                        $('#His_tax').val(data1.Table[0].is_tax);
                        $('#Htax_percentage').val(data1.Table[0].tax_percentage);
                        if (data1.Table[0].is_doctor == 1) {
                            $('#divSelDoctor').show();
                            $('#divdocFee').show();
                            $('.txt_doctor_name').prop('disabled', false);
                            LoadDoctor();
                        }
                        else {
                            $('#divSelDoctor').hide();
                            $('#divdocFee').hide();
                            $('#doc_fee').val('');
                            $('.txt_doctor_name').val('');
                            $('.txt_doctor_name').prop('disabled', true);
                        }
                    }
                }
            }
        }
    })
}
//Individual Service Amount On change
$('.txt_unitRate').change(function () {
    debugger;
    if ($('.base_amount_type').val() == 1) {
        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
            $('#Ptxt_unitRate').show();
            $('#Ptxt_unitRate').fadeOut(8000);
            $('#Ptxt_unitRate').html('Enter the amount');
            $('.txt_unitRate').focus();
            $('.txt_unitRate').val('');
            $('.txt_totalamt').html(0.00);
            return false;
        }
    }
    if ($('.base_amount_type').val() == 3) {
        debugger;
        var range_min = $('#Hrange_min').val();
        var range_max = $('#Hrange_max').val();

        if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0 || (parseInt($('.txt_unitRate').val()) < parseInt(range_min) || parseInt($('.txt_unitRate').val()) > parseInt(range_max))) {

            $('.txt_unitRate').val(range_min)
        }
    }
    var quantity = $('.txt_quantity').val();
    var unit = $('.txt_unitRate').val();
    var total = parseFloat(unit) * parseFloat(quantity);
    $('.txt_totalamt').html(total.toFixed(2));
})
//Individual Quantity Check ( (from Request Page to Billing)(For IP only)- Checks how many quantities are used in work order and based on that edit will happen)
$('.txt_quantity').change(function () {
    debugger;
    var visit_type = $("input[name='optradio']:checked").val()

    if ($('#hdnvisit_report_id').val() != '' && visit_type == 2) {
        if ($('#btn_add').html() == 'Update') {
            if ($('#work_quantity').val() > $('.txt_quantity').val()) {
                debugger;
                //$('#Ptxt_quantity').show();
                //$('#Ptxt_quantity').fadeOut(8000);
                //$('#Ptxt_quantity').html('Quantity should be atleast ' + $('#work_quantity').val());
                //$('.txt_quantity').focus();
                //$('.txt_quantity').val($('#work_quantity').val());
                //return false;
                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>", '' + $('#work_quantity').val() + ' quantity used already.Are u sure want to edit?',
                {
                    closeButton: true,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 20000000,

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

                            quantity_check();
                        })
                        $("#confirmationRevertNo").click(function () {

                            $('.txt_quantity').val($('#work_quantity').val());
                        })
                    }
                })
            }
            else {
                quantity_check();
            }
        }
        else {
            quantity_check();
        }
    }
    else {
        quantity_check();
    }

});
function quantity_check() {
    debugger;
    var totval = '';
    var quantity = $('.txt_quantity').val();
    var unitRate = $('.txt_unitRate').val()
    var txt_discount = $('.txt_discount').val();
    var sel_discount_type = $('.sel_discount_type').val();
    totval = quantity * unitRate;
    //if (sel_discount_type==1) {
    //    totval = totval - txt_discount
    //}
    //else if (sel_discount_type == 2) {
    //    totval = totval - ((totval / 100) * txt_discount)
    //}
    //else {
    //    totval = totval;
    //}
    debugger;

    $('.txt_totalamt').html(totval.toFixed(2));
}
//DatePicker calculation for Hourly Service
$('.datetimepicker2,.datetimepicker1').on('change dp.change', function (e) {
    debugger;
    var start_date = $('.txt_date').val();
    var end_date = $('.txt_end_date').val();
    if (start_date != '' && end_date != '') {
        var quantity = 0;
        var start_date = new Date(moment($('.txt_date').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        var end_date = new Date(moment($('.txt_end_date').val(), ["DD/MM/YYYY hh:mm A"]).format('YYYY-MM-DD H:mm:ss'))
        console.log(start_date);
        console.log(end_date);
        var diff = (end_date - start_date) / 1000 / 60 / 60;
        console.log(diff);
        diff1 = diff.toString();
        var a = diff1.split('.')[0];
        if (diff != a) {
            console.log(a);
            var chk = a + '.5';
            if (parseFloat(diff) <= parseFloat(chk)) {
                quantity = parseFloat(chk);
            }
            else {
                quantity = Math.ceil(diff);
            }
        }
        else {
            quantity = diff;
        }
        console.log(quantity);
        $('.txt_quantity').val(quantity);
        $('.txt_quantity').prop("disabled", true);
        quantity_check();
    }
})
//Discount Amount Check
$('.txt_discount,.sel_discount_type').change(function () {
    debugger;
    var discount = $('.txt_discount').val();
    var tot_amt = $('.txt_totalamt').html();
    var dis_type = $('.sel_discount_type').val();
    if (dis_type == 1) {
        if (parseFloat(discount) > parseFloat(tot_amt)) {
            $('#Ptxt_discount').show();
            $('#Ptxt_discount').fadeOut(5000);
            $('#Ptxt_discount').html('Discount amount should not greater than net amount');
            $('#txt_discount').focus();
            $('.txt_discount').val(0);
            $('.sel_discount_type').val(1);
            return false;
        }
    }
    else {
        if (parseFloat(discount) > 100) {
            $('#Ptxt_discount').show();
            $('#Ptxt_discount').fadeOut(5000);
            $('#Ptxt_discount').html('Discount Percentage should not greater than 100');
            $('#txt_discount').focus();
            $('.txt_discount').val(0);
            $('.sel_discount_type').val(1);
            return false;
        }
        else {
            discount = parseFloat(tot_amt) * (parseFloat(discount) / 100);
            if (parseFloat(discount) > parseFloat(tot_amt)) {
                $('#Ptxt_discount').show();
                $('#Ptxt_discount').fadeOut(5000);
                $('#Ptxt_discount').html('Discount amount should not greater than net amount');
                $('#txt_discount').focus();
                $('.txt_discount').val(0);
                $('.sel_discount_type').val(1);
                return false;
            }
        }
    }
})
//Service Add Function Starts
$('#btn_add').click(function () {
    if ($('#btn_add').html() == 'Update') {
        serviceupdate();
    }
    else {
        serviceadd();
    }
})
//Service Add 
function serviceadd() {
    if ($('.txt_service_name').val() == "") {
        $('#Ptxt_service_name').show();
        $('#Ptxt_service_name').fadeOut(8000);
        $('#Ptxt_service_name').html('Please select The service name');
        $('.txt_service_name').focus();
        $('.txt_service_name').val('');
        return false;
    }
    if ($('.txt_unitRate').val() == '' || $('.txt_unitRate').val() == 0) {
        $('#Ptxt_unitRate').show();
        $('#Ptxt_unitRate').fadeOut(8000);
        $('#Ptxt_unitRate').html('Enter the amount');
        $('.txt_unitRate').focus();
        $('.txt_unitRate').val('');
        $('.txt_totalamt').html(0.00);
        return false;
    }
    if ($('.txt_quantity').val() == "" || $('.txt_quantity').val() == 0) {
        $('#Ptxt_quantity').show();
        $('#Ptxt_quantity').fadeOut(8000);
        $('#Ptxt_quantity').html('Please enter the quantity');
        $('.txt_quantity').focus();
        $('.txt_quantity').val('');
        return false;
    }
    //txt_doctor_name
    if ($('.is_doctor').val() == 1) {
        if ($('.txt_doctor_name').val() == 0) {
            $('#Ptxt_doctor_name').show();
            $('#Ptxt_doctor_name').fadeOut(8000);
            $('#Ptxt_doctor_name').html('Please doctor name is required.');
            $('.txt_doctor_name').focus();
            return false;
        }
        if ($('#doc_fee').val() == '') {
            $('#Pdoc_fee').show();
            $('#Pdoc_fee').fadeOut(8000);
            $('#Pdoc_fee').html('Please enter doctor fee');
            $('#doc_fee').focus();
            return false;
        }
    }
    if ($('#divRemarks').hasClass("hidden") == false) {
        if ($.trim($('#txt_remarks').val()) == "") {
            $('#Ptxt_remarks').show();
            $('#Ptxt_remarks').fadeOut(8000);
            $('#Ptxt_remarks').html('Please Enter the description');
            $('#txt_remarks').focus();
            return false;
        }
    }
    var rowCount = $('#service_tbl tbody tr').length;
    if (rowCount == 0) {
        rowCount = 1
    }
    else {
        var id = $('#service_tbl tbody tr:last').attr('id');
        id = id.split('_');
        rowCount = parseInt(id[1]) + (1);
    }
    var sel_discount_type = $('.sel_discount_type').val();
    var d_amt = ($('.txt_discount').val() == '') ? 0 : $('.txt_discount').val();
    var discount_amount = 0.0;
    if (sel_discount_type == 1) {
        sel_discount_type = '₹';
        discount_amount = parseFloat(d_amt);
    }
    else {
        sel_discount_type = '%';
        discount_amount = parseFloat($('.txt_totalamt').html()) * (parseFloat(d_amt) / 100);
    }
    var tot_net_amt = parseFloat($('.txt_totalamt').html()) - discount_amount
    var doc_name = '';
    if ($('.txt_doctor_name').val() == 0 || $('.txt_doctor_name').val() == '') {
        doc_name = ''
    }
    else {
        doc_name = $('.txt_doctor_name option:selected').text();
    }
    var ser_date = '';
    if ($('.txt_end_date').val() != '') {
        ser_date = $('.txt_date').val() + '-' + $('.txt_end_date').val();
    }
    else {
        ser_date = $('.txt_date').val()
    }
    var tax_amount = 0.0;
    if ($('#Htax_percentage').val() != 0) {
        tax_amount = Math.round(parseFloat($('.txt_totalamt').html()) * parseFloat($('#Htax_percentage').val()) / 100)
    }
    var tr = '<tr id="tr_' + rowCount + '"><td id="txt_ser_' + rowCount + '">' + $('.txt_service_name').val() + '</td><td id="txt_qty_' + rowCount + '">' + $('.txt_quantity').val() + '</td><td id="txt_rt_' + rowCount + '">' + $('.txt_unitRate').val() + '</td>'
    tr += '<td id="txt_tot_' + rowCount + '">' + $('.txt_totalamt').html() + '</td><td id="txt_dis_' + rowCount + '">' + +$('.txt_discount').val() + ' ' + sel_discount_type + '</td><td id="txt_damt_' + rowCount + '">' + discount_amount.toFixed(2) + '</td><td id="txt_per_' + rowCount + '">' + $('#Htax_percentage').val() + '%</td><td id="txt_net_' + rowCount + '">' + (parseFloat(tax_amount) + parseFloat(tot_net_amt)) + '</td><td id="txt_date_' + rowCount + '">' + ser_date + '</td><td id="txt_doc_' + rowCount + '">' + doc_name + '</td><td id="txt_des_' + rowCount + '">' + $('#txt_remarks').val() + '</td><td class="hide" id="txt_docid_' + rowCount + '">' + $('.txt_doctor_name').val() + '</td><td class="hide" id="txt_serid_' + rowCount + '">' + $('.master_service_id').val() + '</td><td class="hide" id="txt_pac_' + rowCount + '">' + $('.package_id').val() + '</td><td class="hide" id="txt_price_' + rowCount + '">' + $('.price_matrix_id').val() + '</td><td class="hide" id="txt_req_' + rowCount + '">0</td><td class="hide" id="txt_reqdet_' + rowCount + '">0</td><td class="hide" id="txt_base_' + rowCount + '">' + $('.base_amount_type').val() + '</td><td class="hide" id="txt_rmin_' + rowCount + '">' + $('#Hrange_min').val() + '</td><td class="hide" id="txt_rmax_' + rowCount + '">' + $('#Hrange_max').val() + '</td><td class="hide" id="txt_txtid_' + rowCount + '">0</td><td class="hide" id="txt_taxamt_' + rowCount + '">' + tax_amount + '</td>'
    //tr += '<td>' + $('.txt_discount').val() + ' ' + sel_discount_type + '</td><td>' + $('.txt_totalamt').html() + '</td><td>' + $('.txt_date').val() + '</td><td>' + doc_name + '</td><td class="hide">' + $('.txt_doctor_name option:selected').val() + '</td><td class="hide">' + $('.master_service_id').val() + '</td><td class="hide">' + $('.package_id').val() + '</td><td class="hide">' + $('.price_matrix_id').val() + '</td><td class="hide">0</td>'
    tr += '<td><span class="btn btn-xs btn-edit service_edit"><i class="fa fa-pencil" aria-hidden="true"></i></span><span class="btn btn-xs btn-delete service_delete" onclick="service_delete(' + rowCount + ')"><i class="fa fa-trash-o" aria-hidden="true"></i></span> </td></tr>';
    $('#service_tbl tbody').append(tr);
    $('.txt_service_name').val('');
    $('.txt_quantity').val('');
    $('.txt_unitRate').val('');
    $('.txt_discount').val(0.0);
    $('.txt_totalamt').html('');
    $('.txt_doctor_name').val(0);
    $('.master_service_id').val('');
    $('.package_id').val('');
    $('.price_matrix_id').val('');
    $('.base_amount_type').val('');
    $('.is_doctor').val('');
    $('.txt_end_date').val('');
    $('#txt_remarks').val('');
    $('#His_tax').val(0);
    $('#Htax_percentage').val(0);
    $('#div_remarks').addClass("hidden");
    $('.txt_quantity').prop('disabled', false);
    $('#divSelDoctor').hide();
    var dateNow = new Date();

    var new_date = moment(dateNow).format('DD/MM/YYYY hh:mm A')
    $('.txt_date').val(new_date);
    $('.txt_date').prop("disabled", true);
    $('#datetimepicker2').hide();
    $('.datetimepicker1').datetimepicker({
        //format: 'DD/MM/YYYY hh:mm A',
        defaultDate: new_date
    });
    $('#Ptxt_unitRate').html('');
    $('.txt_unitRate').prop('disabled', true);
    service_card();
}
//Service card binding
function service_card() {
    var overall = 0, tot_amt = 0, dis_amt = 0, tax_amt = 0, tot_net = 0;
    for (var i = 1; i <= $('#service_tbl>tbody>tr').length; i++) {
        overall++;
        tot_amt = parseFloat(tot_amt) + parseFloat($('#txt_tot_' + i).html());
        dis_amt = parseFloat(dis_amt) + parseFloat($('#txt_damt_' + i).html());
        tax_amt = parseFloat(tax_amt) + parseFloat($('#txt_taxamt_' + i).html());
        tot_net = parseFloat(tot_net) + parseFloat($('#txt_net_' + i).html());
    }
    $('#ser_all').html(overall);
    $('#ser_tl_amt').html(tot_amt);
    $('#ser_dis_amt').html(dis_amt);
    $('#ser_tax_amt').html(tax_amt);
    $("#ser_net_amt").html(tot_net);
}

