// ServiceMaster JS //
var selectedOptionText = ''
var crm_data = []
var smsflag = ''
var smsfield = ''
$(document).ready(function () {
    if ($('#EMasterServiceId').val()) {
        serviceedit('#EMasterServiceId', $('#EMasterServiceId').val())
    }
    else {
        loadservicedata(0, 1);
    }
   
    Showservicecode(0)
    //CheckCodeTemplate()
    //Showservicecode(3); medway all branch concept

    //loadtube_container()


    //loadExternal();
    var hospitalid = $('#HospitalId').val();
    //Branchdetails(hospitalid);
    $('#txtLogdate').datepicker({
        autoclose: true,
        todayHighlight: true,
        format: "dd/mm/yyyy"
        //endDate: new Date()
    });

    $('#txtLogtime').timepicker({
        showInputs: false
    });
    //datatable('service_table_list', 'Service_Master', 'Legal');


    //CheckCodeTemplate();
   

    LoadDepartment(0, 0);
    LoadCategory(0, 0);
    loadservice_type();

    SchemEntityName();

});



//CheckCodeTemplate
function CheckCodeTemplate() {
    debugger;
    var codeData = {
        //Dml_Indicator: "CT",
        Dml_Indicator: "BCT",
        hospital_id: $('#HospitalId').val(),
        //branch_id: $('#branch_id').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('' + $('#branch_id  option:selected').html() + ' Not Added Code Template. Please Add the Code Template at SetupIds'); //medway all branch concept
                alert('Not Added Code Template. Please Add the Code Template at SetupIds');
                window.location.href = "/Hospitalsetup"
            }
            else {
                //  LoadBranch()

                loadservicedata(0, 1);

                LoadDepartment(0, 0);
                LoadCategory(0, 0);
                loadservice_type();

                SchemEntityName();
            }

        }
    });
}

function Branchdetails(Hospitalid) {
    debugger;
    //document.getElementById("ldabranch_id").innerHTML = null; medway all branch concept

    //Only KinderSurge
    //var dml = ''
    //if (parseInt($('#hiddenRole_id').val()) == 1) {
    //    dml = 'DLBRAN'
    //}
    //else {
    //    dml = 'LBRAN'
    //}

    var subdepartment = {
        Dml_Indicator: "LBRAN",
        //Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            $('.branch_id').empty();
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {

                    debugger;


                    var branchname;
                    var default_opt = '<option value="0" data-id="">--Select--</option>';
                    var fil_default_opt = '<option value="0" data-id="">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        branchname = branchname + '<option value="' + emp.hospital_branch_id + '" data-id="' + emp.branch_name + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        // alert('test');
                        $('.branch_id').append(branchname);
                        $('#ldabranch_id').append(branchname);
                        CheckCodeTemplate();
                        Showservicecode($('.branch_id').val());
                        LoadDepartment($('.branch_id').val(), 0);
                        LoadCategory($('.branch_id').val(), 0);
                        loadtube_container($('.branch_id').val());
                        if ($('#typeofservicelab').val() != '' || $('#typeofserviceapporder').val() != '') {
                            loadExternal($('.branch_id').val(), 0, 0);
                        }

                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#ldabranch_id').append(branchname);
                        }
                        else {
                            $('#ldabranch_id').append(fil_default_opt + branchname);
                        }
                        $('.branch_id').append(default_opt + branchname);
                    }


                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('.branch_id').val($('#HospitalBranchID').val());
                    //    $('#ldabranch_id').val($('#HospitalBranchID').val());
                    //    CheckCodeTemplate();
                    //    Showservicecode($('#HospitalBranchID').val());
                    //    LoadDepartment($('#HospitalBranchID').val(), 0);
                    //    LoadCategory($('#HospitalBranchID').val(), 0);
                    //    loadtube_container($('#HospitalBranchID').val());
                    //    if ($('#typeofservicelab').val() != '' || $('#typeofserviceapporder').val() != '') {
                    //        loadExternal($('#HospitalBranchID').val(), 0, 0);
                    //    }
                    //}
                    //else 

                    if ($('#hiddenRole_id').val() != 2) {
                        $('.branch_id').val($('#HospitalBranchID').val());
                        $('.branch_id').attr('disabled', true);
                        $('#ldabranch_id').val($('#HospitalBranchID').val());
                        $('#ldabranch_id').attr('disabled', true);
                        CheckCodeTemplate();
                        Showservicecode($('#HospitalBranchID').val());
                        LoadDepartment($('#HospitalBranchID').val(), 0);
                        LoadCategory($('#HospitalBranchID').val(), 0);
                        loadtube_container($('#HospitalBranchID').val());
                        if ($('#typeofservicelab').val() != '' || $('#typeofserviceapporder').val() != '') {
                            loadExternal($('#HospitalBranchID').val(), 0, 0);
                        }

                    }

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


    //var Branch_data = {
    //    hospital_id: Hospitalid,
    //    Dml_Indicator: 'SIGHB'
    //}
    //$.ajax({
    //    async: true,
    //    type: 'POST',
    //    url: '/Hospitalsetup/HospitalCreation',
    //    contentType: 'application/json; charset=UTF-8',
    //    data: JSON.stringify(Branch_data),
    //    success: function (data) {
    //        debugger;
    //        var data = JSON.parse(data);
    //        console.log(data);
    //        if (data.msg == "Success") {
    //            var data1 = data.data;
    //            var tr = '', j = 1;
    //            if (jQuery.isEmptyObject((data1))) {
    //            }
    //            else {
    //                debugger;


    //                $('.branch_id').empty();
    //                var branchname;
    //                var default_opt = '<option value="0" data-id="">--Select--</option>';
    //                $.each(data1.Table, function (i, emp) {
    //                    branchname = branchname + '<option value="' + emp.hospital_branch_id + '" data-id="' + emp.branch_name + '">' + emp.branch_name + '</option>';
    //                });
    //                $('.branch_id').append(default_opt + branchname);


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




}
function LoadDepartment(val, val1) {
    debugger;
    var department = {
        Dml_Indicator: "DP",
        //branch_id: val // medway all branch concept
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(department),
        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 {
                    var Department;
                    var default_opt = '<option value="0">--Select--</option>';
                    $('#department_id').empty();
                    $.each(data1.Table, function (i, emp) {
                        Department = Department + '<option value="' + emp.master_category_department_id + '">' + emp.name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#department_id').append(Department);
                        $('#department_filter').append(Department);
                        if ($('#master_service_id').val() == '') {
                            LoadSubDepartment(data1.Table[0].master_category_department_id, 0);
                        }
                        $("#department_filter").change();
                    }
                    else {
                        $('#department_id').append(default_opt + Department);
                        $('#department_filter').append(default_opt + Department);
                        if (val1 != 0) {
                            $('#department_id').val(val1);
                        }
                    }

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


//Used for Loading the Sub Department DropDown
$("#department_id").change(function () {
    var schemedept = $(this).find('option:selected').text();
    $('#lblDepartment').html(schemedept)
    LoadSubDepartment($('#department_id').val(), 0);
})

$("#department_filter").change(function () {
    debugger;
    var dpt_filter = $("#department_filter").val()
    LoadSubDepartment(dpt_filter, 0, 0, 0, 2);
})

function LoadSubDepartment(id, val, master_service_ID, name, flag) {
    debugger;
    var val = val;
    document.getElementById("sub_department_id").innerHTML = null;
    var subdepartment = {
        Dml_Indicator: "SDP",
        Master_cd_id: id,
        // MasterSub_cd_id: master_service_ID
        name: name
    }
    $.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 {
                    var SubDepartment = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '" data-id=' + emp.work_order_enabled + '>' + emp.sub_cd_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#sub_department_id').append(SubDepartment);
                        if (flag == 2) {
                            $('#sub_department_filter').append(SubDepartment);
                        }
                        $('#sub_department_id').change();
                    }
                    else {
                        $('#sub_department_id').append(default_opt + SubDepartment);
                        if (flag == 2) {
                            $('#sub_department_filter').append(default_opt + SubDepartment);
                        }
                    }
                    if (val != 0) {
                        $('#sub_department_id').val(val);
                    }



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

$('#sub_department_id').change(function () {
    debugger
    var sub_department_id = $('#sub_department_id').val();
    //var branch_id = $('#branch_id').val();
    if ($('#master_service_id').val() == '' || $('#master_service_id').val() == 0) {
        LoadDoctor(0, sub_department_id, 0);
    }
    var schemesubdept = $(this).find('option:selected').text();
    $('#lblSubDepartment').html(schemesubdept)

})

//Loading Doctor
function LoadDoctor(branch_id, department_id, val) {

    debugger;
    //Do not remove this command.
    //P_Dml_Indicator: "HDL", use other hms hospital this 'HDL' and hide 'KINDL'
    //P_Dml_Indicator: "KINDL", use kindersurge hms hospital this 'KINDL' and hide 'HDL'

    var DoctorData = {

        //P_Dml_Indicator: "KINDL",
        P_Dml_Indicator: "HDL",
        //branch_id: branch_id, //medway all branch concept
        department_id: department_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#SelDoctor').val('0');
            $('#SelDoctor').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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


                    var tr = '';
                    var SelRole = '';

                    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].doctorid + '" data-id="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#SelDoctor').html(default_opt + SelRole);
                        if (val != 0) {
                            $('#SelDoctor').val(val);
                        }
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//$('#sub_department_id').change(function () {
//    debugger;
//    var workorderenabled = $('#sub_department_id option:selected').data('id');
//    if(workorderenabled==1)
//    {
//        $('a[data-toggle=is_workorder][data-title="1"]').addClass('active disabled ');
//        $('a[data-toggle=is_workorder][data-title="2"]').attr('disabled',true); 

//       // $('a[data-toggle=is_workorder][data-title="1"]').addClass('active');
//      //  $('a[data-toggle=is_workorder][data-title="2"]').attr('disabled',true);   
//    }
//    else {
//        $('a[data-toggle=is_workorder][data-title="1"]').removeClass('active disabled');
//        $('a[data-toggle=is_workorder][data-title="2"]').removeClass('active disabled');       
//    }
//})
//Load Category

function LoadCategory(val, val1) {

    var department = {

        Dml_Indicator: "DPC",
        //branch_id: val //medway all branch concept
    }

    $.ajax({

        async: true,

        type: 'POST',

        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',

        contentType: 'application/json; charset=UTF-8',

        data: JSON.stringify(department),

        success: function (data) {

            var data1 = JSON.parse(data);

            if (data1.msg == "Success") {
                $('#master_category_id').empty();
                var data1 = data1.data;

                console.log(data1)

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

                }

                else {

                    var Department;

                    var default_opt = '<option value="0">--Select--</option>';

                    $.each(data1.Table, function (i, emp) {

                        Department = Department + '<option value="' + emp.master_category_department_id + '">' + emp.name + '</option>';

                    });
                    if (data1.Table.length == 1) {
                        $('#master_category_id').append(Department);
                        $("#master_category_id").change();
                    }
                    else {
                        $('#master_category_id').append(default_opt + Department);
                        if (val1 != 0) {
                            $('#master_category_id').val(val1);
                        }
                    }


                }

            }

            else {

                console.log(data1);

            }



        }

    });

}

//Used for Loading the Sub Category DropDown
$("#master_category_id").change(function () {
    LoadSubCategory($('#master_category_id').val(), 0);
})
function LoadSubCategory(id, val, master_service_ID, name) {
    debugger;
    document.getElementById("master_sub_category_id").innerHTML = null;
    var subdepartment = {
        Dml_Indicator: "SDPC",
        Master_cd_id: id,
        //MasterSub_cd_id: master_service_ID
        name: name
    }
    $.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 {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '">' + emp.sub_cd_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#master_sub_category_id').append(SubDepartment);
                    }
                    else {
                        $('#master_sub_category_id').append(default_opt + SubDepartment);

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

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

//medway all branch concept
//Show service code based on branch
//$('#branch_id').change(function () {
//    CheckCodeTemplate();
//    var val = $('#branch_id').val();
//    $('#master_category_id').empty();
//    $('#master_category_id').val('0');
//    $('#master_sub_category_id').empty();
//    $('#master_sub_category_id').val('0');
//    $('#department_id').empty();
//    $('#department_id').val('0');
//    $('#sub_department_id').empty();
//    $('#sub_department_id').val('0');
//    $('#SelDoctor').val('0');
//    $('#SelDoctor').empty();

//    Showservicecode(val);
//    LoadDepartment(val, 0);
//    LoadCategory(val, 0);
//    loadtube_container(0);
//    if ($('#base_amount_type').val() == 5) {
//        WardNo($('#branch_id').val(), 0)
//    }
//    if ($('#typeofservicelab').val() != '' || $('#typeofserviceapporder').val() != '') {
//        loadExternal(0, 0, 0);
//    }
//});

//medway all branch concept
//Show service code based on branch
//$('#ldabranch_id').change(function () {
//    debugger;
//    $('#department_filter').empty();
//    $('#sub_department_filter').empty();
//    var filter_branch_val = $('#ldabranch_id').val();
//    LoadDepartment(filter_branch_val, 0);
//});


$('#btnfilter').click(function () {
    debugger;
    ///var Pbranch_id = $("#ldabranch_id").val(); //medway all branch concept
    var Pbranch_id = 0;

    //if ($.trim((Pbranch_id)) == "" || $.trim((Pbranch_id)) == '0') {
    //    $('#Pbranch_id1').show();
    //    $('#Pbranch_id1').fadeOut(8000);
    //    $('#Pbranch_id1').html('Select Branch Name');
    //    $('#ldabranch_id').focus();
    //    return false;
    //}
    //var val = $('#ldabranch_id').val(); //medway all branch concept
    var val = 0;
    var servtype = $('#servicetype_filter').val();
    var departmentid = $('#department_filter').val()
    var sub_departmentid = $('#sub_department_filter').val()
    var status = $('#status_filter').val()

    loadservicedata(val, 2, servtype, departmentid, sub_departmentid, status);
});
$('#btnclear').click(function () {

    var hospitalid = $('#HospitalId').val();
    //Branchdetails(hospitalid); // medway all branch concept
    $('#servicetype_filter').val(0);
    //$('#ldabranch_id').val(0); //medway all branch concept
    //$('#department_filter').empty(); //medway all branch concept
    $('#department_filter').val(0);
    $('#sub_department_filter').empty();
    $('#status_filter').val(0);
    $('#base_amount_type_fil').val(0);
    loadservicedata(0, 2, 0);
});

//$('#ldabranch_id').change(function () {
//    debugger;
//    $('#department_filter').empty();
//    $('#sub_department_filter').empty();
//})

$('#department_filter').change(function () {
    debugger;
    $('#sub_department_filter').empty();
})
//Show service code
function Showservicecode(val) {

    debugger;
    var servicevalues = {

        P_Dml_Indicator: "LSC",
        branch_id: val
        //branch_id: 0     //medway all branch concept
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        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") {
                    var data1 = data2.data;
                    $('#service_code').val(data1[0].service_code);
                }
                else {
                    console.log(data);
                }
            }

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

}

// laod sample type dropdown value
function loadsampletype(id) {
    var servicevalues = {
        Dml_Indicator: "STS",
        lab_type_id: $('#lab_type').val()
    }
    return $.ajax({
        async: true,
        type: 'POST',
        url: '/Template/labtest',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicevalues),
        success: function (data) {
            debugger;
            $('#sType').empty();

            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" data-id="">--Select--</option>';
                    $.each(data1, function (i, emp) {

                        Country = Country + '<option value="' + emp.sample_id + '" data-id="' + emp.sample_name + '"   data-id1="' + emp.refunitflag + '">' + emp.sample_name + '</option>';

                    });
                    $('#sType').append(default_opt + Country);
                    if (id != null && id != 0) {
                        $('#sType').val(id);
                    }
                }
                else {
                    console.log(data);
                }
            }

        }
    });
}

//load tube container
function loadtube_container(val, id) {
    debugger;
    var branch_id = 0;
    if (val == 0) {
        // branch_id = ($('#branch_id').val() == '' ? 0 : $('#branch_id').val()) //medway all branch concept
        branch_id = 0
    }
    else {
        branch_id = val;
    }
    var data = {
        P_Dml_Indicator: 'TC',
        branch_id: branch_id
    }
    $.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;
            $('#loadctubecontainer').empty();
            var data2 = JSON.parse(data);

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

            }
            else {

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


                    var sampletypetube = '';
                    var default_opt = '<option value="0" data-id="0">--Select--</option>';
                    $.each(data2.data, function (i, emp) {
                        sampletypetube = sampletypetube + '<option value="' + emp.master_servie_type_id + '" data-id="' + emp.master_servie_type_id + '" > ' + emp.master_service_name + '</option>';
                    });

                    $('#loadctubecontainer').append(default_opt + sampletypetube);


                    if (id != null && id != 0) {
                        $('#loadctubecontainer').val(id);
                    }
                }
            }
        }
    })
}

//load html table service data 
function loadservicedata(val, val1, servtype, departmentid, sub_departmentid, status) {
    debugger;
    $('#shade_slot').show();
    $('#servicedata_body').empty();
    $('#service_table_list').dataTable().fnClearTable();
    $('#service_table_list').dataTable().fnDraw();
    $('#service_table_list').dataTable().fnDestroy();
    $('#taxpercentage_div').addClass('hidden')
    var branch_id_val = ''
    if (val != '' && val != 0) {
        branch_id_val = val
    }
    else {
        branch_id_val = ($('#HospitalBranchID').val() == '' || $('#HospitalBranchID').val() == null) ? 0 : $('#HospitalBranchID').val()
    }

    var sub_dpt_id = sub_departmentid == null ? 0 : sub_departmentid;

    var servicelist = {
        P_Dml_Indicator: "L",
        //branch_id: val, 
        //branch_id: ($('#HospitalBranchID').val() == '' || $('#HospitalBranchID').val() == null) ? 0 : $('#HospitalBranchID').val(),
        //branch_id: ($('#ldabranch_id').val() == '' || $('#ldabranch_id').val() == null) ? 0 : $('#ldabranch_id').val(),  
        //  branch_id: branch_id_val,//one master_concept
        is_lab: val1,
        service_type: servtype,
        department_id: departmentid,
        sub_department_id: sub_dpt_id,
        status: status,
        base_amount_type: (!$('#base_amount_type_fil').val()) ? 0 : $('#base_amount_type_fil').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(servicelist),
        success: function (data) {
            debugger;

            if (jQuery.isEmptyObject((data))) {
                $('#servicedata_body').html('Norecord');
                $('#shade_slot').hide();
            }
            else {
                var data2 = JSON.parse(data);
                $('#shade_slot').hide();
                if (data2.msg == "Success") {
                    var data1 = data2.data;

                    if (data1[0].status == "No Record") {
                        //$('#servicedata_body').empty();
                        $('#servicedata_body').html('Norecord');

                        return false;
                    }
                    $('#divserviceReport').empty();
                    if (jQuery.isEmptyObject((data1))) {
                        $('#divserviceReport').html(Norecord);
                        return false;
                    }
                    else {

                        var status = '', j = 0;
                        var b = data1.Table;
                        $('#servicedata_body').empty();
                        $('#service_table_list').dataTable().fnClearTable();
                        $('#service_table_list').dataTable().fnDraw();
                        $('#service_table_list').dataTable().fnDestroy();
                        tr = '';
                        for (var i = 0; i < data1.length; i++) {
                            j = i + 1;
                            var favourite = '';
                            schem_mapping = '<a class="btn btn-xs btn-blue" data-id="" data-type="role_rights_function" data-nav="popup" data-name=""  data-toggle="" data-target="" href="javascript:void(0);" onclick=\'Sevice_Schemmapping(\"' + data1[i].master_service_id + '\",\"' + data1[i].branch_id + '\",\"' + data1[i].base_amount_type + '\",\"' + data1[i].service_name + '\",\"' + data1[i].department + '\",\"' + data1[i].subdeaprtmentname + '\",\"' + data1[i].base_amount_value + '\")\';><i class="	fa fa-file-text mr-5"></i>Scheme Mapping</a>';
                            if (data1[i].is_favourite == '1') {
                                favourite = '<a   title="Make Favourite!" id="servicefav_' + data1[i].master_service_id + '" class="btn btn-xs mr-10" href="javascript:void(0);"  data-id="" data-type="" data-nav="" data-name="c_details_form" onclick=servicefavourite(this,"' + data1[i].master_service_id + '") data-toggle="tooltip" data-target=""><i class="fa fa-star" style="color:green;font-size:14px" aria-hidden="true" id=fav_' + data1[i].master_service_id + '></i></a>'
                            }
                            else {
                                favourite = '<a   title="Make Favourite!" id="servicefav_' + data1[i].master_service_id + '" class="btn btn-xs mr-10" href="javascript:void(0);"  data-id="" data-type="" data-nav="" data-name="c_details_form" onclick=servicefavourite(this,"' + data1[i].master_service_id + '") data-toggle="tooltip" data-target=""><i class="fa fa-star-o" style="font-size:14px" aria-hidden="true" id=fav_' + data1[i].master_service_id + '></i></a>'
                            }
                            if (data1[i].status == "1") {
                                //status = '<span class="label label-success">Active</span>';
                                //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=serviceedit(this,"' + data1[i].master_service_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                //del = ' <a  data-toggle="tooltip" title="Delete"  id="servicedel_' + data1[i].master_service_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=servicedel(this,"' + data1[i].master_service_id + '",0)><i class="fa fa-trash" aria-hidden="true"></i></a>';
                                //active = '<a  data-toggle="tooltip" title="Make In Active!" id="servicedel_' + data1[i].master_service_id + '" class="btn btn-blue btn-xs 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=servicedel(this,"' + data1[i].master_service_id + '",2)><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</a> ';
                                //// copy = '<a   title="Copy!" id="servicecopy_' + data1[i].master_service_id + '" class="btn btn-blue btn-xs mr-10" href="javascript:void(0);"  data-id="" data-type="" data-nav="" data-name="c_details_form" onclick=servicecopy(this,"' + data1[i].master_service_id + '") data-toggle="modal" data-target="#pop_service_copy"><i class="fa fa-clipboard" aria-hidden="true"></i>Copy</a> ';
                                //copy = ''; //one master concept
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"  id=other_info_' + data1[i].master_service_id + '> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active + '</div><div class="text-left">' + copy + '</div></div></div></div>';



                                status = '<span class="label label-success">Active</span>';
                                edit = '<a title="Edit" class="edit_icon" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=serviceedit(this,"' + data1[i].master_service_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                del = ' <a title="Delete" class="delete_icon"  id="servicedel_' + data1[i].master_service_id + '"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=servicedel(this,"' + data1[i].master_service_id + '",0)><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                                active = '<a title="Make In Active!" id="servicedel_' + data1[i].master_service_id + '" class="inactive_icon" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick=servicedel(this,"' + data1[i].master_service_id + '",2)><i class="fa fa-minus-square-o" aria-hidden="true"></i></a> ';
                                // copy = '<a   title="Copy!" id="servicecopy_' + data1[i].master_service_id + '" class="" href="javascript:void(0);"  data-id="" data-type="" data-nav="" data-name="c_details_form" onclick=servicecopy(this,"' + data1[i].master_service_id + '") data-toggle="modal" data-target="#pop_service_copy"><i class="fa fa-clipboard" aria-hidden="true"></i>Copy</a> ';
                                copy = ''; //one master concept
                               // other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"  id=other_info_' + data1[i].master_service_id + '> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active + '</div><div class="text-left">' + copy + '</div></div></div></div>';
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li><li>' + active + '</li></div><li>' + copy + '</li></ul></div>';

                                //tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].service_code + '</td><td hidden>' + data1[i].master_service_id + '</td><td class="tbl-name">' + data1[i].service_name + '</td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td><span class="rup-sym">&#8377</span><span class="tbl-price">' + data1[i].base_amount_value + '</span></td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + ' </td></tr>';
                                //one master concept ----  //tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].branch_name + '</td><td>' + data1[i].service_code + '</td><td class="tbl-name">' + data1[i].service_name + '<span>' + favourite + '</span></td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td>&#8377 ' + data1[i].base_amount_value + '</td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + ' </td></tr>';
                                tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].service_code + '</td><td class="tbl-name">' + data1[i].service_name + '<span>' + favourite + '</span></td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td>&#8377 ' + data1[i].base_amount_value + '</td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + ' </td></tr>';

                            }
                            else {
                                // 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=serviceedit(this,"' + data1[i].master_service_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                                edit = ''
                                schem_mapping = ''
                                //del = ' <a  data-toggle="tooltip" title="Delete"  id="servicedel_' + data1[i].master_service_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=servicedel(this,"' + data1[i].master_service_id + '",0)><i class="fa fa-trash" aria-hidden="true"></i></a>';
                                //active = '<a  data-toggle="tooltip" title="Make Active!" id="servicedel_' + data1[i].master_service_id + '" class="btn btn-blue btn-xs 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=servicedel(this,"' + data1[i].master_service_id + '",1)><i class="fa fa-check-square-o" aria-hidden="true"></i> Active</a> ';
                                //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + active + '</div></div></div></div>';
                                del = ' <a title="Delete" class="delete_icon"  id="servicedel_' + data1[i].master_service_id + '"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=servicedel(this,"' + data1[i].master_service_id + '",0)><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                                active = '<a title="Make In Active!" id="servicedel_' + data1[i].master_service_id + '" class="active_icon" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick=servicedel(this,"' + data1[i].master_service_id + '",1)><i class="fa fa-check-square-o" aria-hidden="true"></i></a> ';
                                other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li><li>' + active + '</li></div></ul></div>';

                                status = '<span class="label label-warning">In Active</span>';

                                //tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].service_code + '</td><td hidden>' + data1[i].master_service_id + '</td><td class="tbl-name">' + data1[i].service_name + '</td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td><span class="rup-sym">&#8377</span><span class="tbl-price">' + data1[i].base_amount_value + '</span></td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + '</td></tr>';
                                //one master concept ----   //   tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].branch_name + '</td><td>' + data1[i].service_code + '</td><td class="tbl-name">' + data1[i].service_name + '<span>' + favourite + '</span></td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td>&#8377 ' + data1[i].base_amount_value + '</td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + '</td></tr>';
                                tr = tr + '<tr id="t_' + i + '"><td>' + j + '</td><td>' + data1[i].service_code + '</td><td class="tbl-name">' + data1[i].service_name + '<span>' + favourite + '</span></td><td>' + data1[i].service_type + '</td><td>' + data1[i].department + '</td><td>' + data1[i].subdeaprtmentname + '</td><td>' + data1[i].categoryname + '</td><td>' + data1[i].subcategoryname + '</td><td>&#8377 ' + data1[i].base_amount_value + '</td><td>' + data1[i].tax_percentage + '</td><td id="status_' + data1[i].master_service_id + '">' + status + '</td><td>' + other_info + '</td></tr>';

                            }
                        }
                        $('#servicedata_body').html(tr);
                        datatable('service_table_list', 'Service_Creation', 'Legal');

                        
                    }
                }
                else {
                    console.log(data);
                   datatable('service_table_list', 'Service_Creation', 'Legal');
                }
            }

        }
    });
}

function refereshform() {
    debugger;
    //$('#fasting_div').attr('disabled',false);
    //$('#fasting_div').addClass('hidden');
    $('#short_name').val('');
    $('#display_name').val('');
    $('#txt_dis_order').val('');
    $('#ward_id').attr('disabled', false);
    $("#base_amount_value").attr('disabled', false);
    //$('#branch_id').attr('disabled', false); // medway all branch concept
    $('#templateinfo').summernote('code', '')
    $('#master_category_id').attr('disabled', false);
    $('#master_sub_category_id').attr('disabled', false);
    $('#department_id').attr('disabled', false);
    $('#sub_department_id').attr('disabled', false);
    $('#service_name').attr('disabled', false);
    $('#consulting_type').attr('disabled', false);
    $('#SelDoctor').attr('disabled', false);
    $('#remarks').attr('disabled', false);
    $('#service_type').attr('disabled', false);
    $('#is_consultingdiv').attr('disabled', false);
    $('#is_activate').prop('checked', false);
    $('#activate_div').addClass('hidden');
    $('#activate_div').attr('disabled', false);
    $('#is_internaldiv').removeClass('hidden');
    $('.typeofservice').prop('checked', false);
    $('.workorderoption').attr('checked', false);
    $('.workorderapp').prop('checked', false);
    $('#nwoprocedure').attr('checked', false);
    $('#nwosurgery').attr('checked', false);
    $('#appointment_details').addClass('hidden');
    $('#consulting_details').addClass('hidden');
    $('#workorder_details').addClass('hidden');
    $('#lab_details').addClass('hidden');
    $('#other_services').removeClass('hidden');
    $('#Add_Test_record').removeClass('hidden');
    //$('#mobile_options').removeClass('hidden');
    $('#mobile_enableddiv').removeClass('hidden');
    $('#service_details').removeClass('hidden');
    $('#nonworkorder_details').addClass('hidden');
    $('.typeofservice').attr('disabled', false);
    $('.workorderoption').attr('disabled', false);
    $('.workorderapp').attr('disabled', false);
    $('.nonworkorderoption').attr('disabled', false);
    $('#is_packagediv').attr('disabled', false);
    $('#is_internaldiv').removeClass('disabled');
    $('#mobile_discount_type').attr('disabled', false);
    $('#mobile_discount_amount').attr('disabled', false);
    $('#pname').attr('disabled', false);
    $('#rvalue').attr('disabled', false);
    $('#unit').attr('disabled', false);
    $('#sType').attr('disabled', false);
    $('#lab_type').attr('disabled', false);
    $('#testNotes').attr('disabled', false);
    $('#Is_Surgerydiv').removeClass('disabled');
    $('#handle_time').hide();
    $('.counter_addon').show();
    $('#txtPatientTime').val(00);
    $('#p_time').html(' (in mins)');
    $('#mobile_discount_applicablediv').attr('disabled', false);
    $('#service_level_discount_alloweddiv').attr('disabled', false);
    $('#loayalty_earning_alloweddiv').attr('disabled', false);
    $('#doctor_name_requireddiv').attr('disabled', false);
    $('#is_loyalty_schemediv').attr('disabled', false);
    $('#lab_div').removeClass('disabled');
    $('#appointment_div').removeClass('disabled');
    $('#base_amount_type').attr('disabled', false);

    $('#divward_id').hide();
    $('#service_details').show();

    $('#is_packagediv').show();
    $('#is_doctordiv').show();
    $('#is_coupons_reversediv').show();
    $('#is_internaldiv').show();
    $('#distance_feediv').show();
    $('#is_consultingdiv').show();
    $('#mobile_enableddiv').show();
    $('#consulting_typehidden').hide();
    $('#consultion_typehidden').hide();
    $('#divSelDoctor').hide();
    $(".ranges1").hide();
    $('#consulting_typehidden').hide();
    //$("#branch_id").val('') // medway all branch concept
    $("#master_service_id").val('')
    $("#master_category_id").val('0')
    $("#master_sub_category_id").val('')
    $("#department_id").val('0')
    $("#sub_department_id").val('')
    $("#service_name").val('')
    $("#service_type").val('0')
    $("#remarks").val('')
    $("#base_amount_type").val('')
    $("#range_min").val('')
    $("#range_max").val('')
    $("#base_amount_value").val('')
    $("#pname").val('')
    $("#rvalue").val('')
    $("#unit").val('')
    $("#testNotes").val('')

    $("#ward_id").val(0)
    //$("#service_code").val('') medway all branck concept
    $("#sType").val('')
    $("#testAddTable_body").empty()
    $('#typeofserviceapporder').val('');
    $('#loadctubecontainer').val(0);

    $('#tax_percentage').val('');
    $('#taxpercentage_div').addClass('hidden');

    $('#external_lab').val('').change();
    $('#external_div').addClass('hidden');
    $('#mobile_div').addClass('hidden');

    $("#imagefile").val('')
    $("#mobile_discount_type").val('')
    $("#mobile_discount_amount").val('')
    $("#consultation_type").val('')
    $("#SelDoctor").val('')
    //$('#pgender').val(0);
    //$('#age_limit').val(0);
    //$('#resutlt_type').val(0);
    //$('#min_val').val('');
    //$('#max_val').val('');
    $('#method_name').val('');
    $("#Add_Test_record").show()
    $('#Update_Test_record').hide();
    $('#Hdn_service_image').val('')
    $('#is_coupons_reverse').val('')
    $('#is_consulting').val('')
    $('#typeofservicelab').val('');
    $('#typeofserviceapporder').val('');
    $('#lab_type').val('');

    $('a[data-toggle=is_tax][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_tax][data-title="2"]').removeClass('active');
    $('a[data-toggle=is_tax][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_tax][data-title="2"]').addClass('not-active');

    $('a[data-toggle=typeofservicelab][data-title="1"]').removeClass('active');
    $('a[data-toggle=typeofservicelab][data-title="2"]').removeClass('active');
    $('a[data-toggle=typeofservicelab][data-title="1"]').addClass('not-active');
    $('a[data-toggle=typeofservicelab][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_description][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_description][data-title="2"]').removeClass('active');
    $('a[data-toggle=is_description][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_description][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_tax][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_tax][data-title="0"]').removeClass('active');
    $('a[data-toggle=is_tax][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_tax][data-title="0"]').addClass('not-active');

    $('a[data-toggle=typeofserviceapporder][data-title="1"]').removeClass('active');
    $('a[data-toggle=typeofserviceapporder][data-title="2"]').removeClass('active');
    $('a[data-toggle=typeofserviceapporder][data-title="1"]').addClass('not-active');
    $('a[data-toggle=typeofserviceapporder][data-title="2"]').addClass('not-active');
    $('a[data-toggle=is_doctor][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_doctor][data-title="2"]').addClass('not-active');
    $('a[data-toggle=mobile_enabled][data-title="1"]').addClass('not-active');
    $('a[data-toggle=mobile_enabled][data-title="2"]').addClass('not-active');
    $('a[data-toggle=mobile_discount_applicable][data-title="1"]').addClass('not-active');
    $('a[data-toggle=mobile_discount_applicable][data-title="2"]').addClass('not-active');
    $('a[data-toggle=distance_fee][data-title="1"]').removeClass('active');
    $('a[data-toggle=distance_fee][data-title="2"]').removeClass('active');
    $('a[data-toggle=distance_fee][data-title="1"]').addClass('not-active');
    $('a[data-toggle=distance_fee][data-title="2"]').addClass('not-active');
    $('a[data-toggle=service_level_discount_allowed][data-title="1"]').addClass('not-active');
    $('a[data-toggle=service_level_discount_allowed][data-title="2"]').addClass('not-active');
    $('a[data-toggle=loayalty_earning_allowed][data-title="1"]').addClass('not-active');
    $('a[data-toggle=loayalty_earning_allowed][data-title="2"]').addClass('not-active');
    $('a[data-toggle=doctor_name_required][data-title="1"]').addClass('not-active');
    $('a[data-toggle=doctor_name_required][data-title="2"]').addClass('not-active');
    $('a[data-toggle=is_package][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_package][data-title="2"]').addClass('not-active');
    $('a[data-toggle=is_loyalty_scheme][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_loyalty_scheme][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_coupons_reverse][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_coupons_reverse][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_consulting][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_consulting][data-title="2"]').addClass('not-active');


    $('a[data-toggle=is_doctor][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_doctor][data-title="2"]').addClass('not-active');
    $('a[data-toggle=mobile_enabled][data-title="1"]').addClass('not-active');
    $('a[data-toggle=mobile_enabled][data-title="2"]').addClass('not-active');

    $('a[data-toggle=mobile_discount_applicable][data-title="1"]').addClass('not-active');
    $('a[data-toggle=mobile_discount_applicable][data-title="2"]').addClass('not-active');

    $('a[data-toggle=service_level_discount_allowed][data-title="1"]').addClass('not-active');
    $('a[data-toggle=service_level_discount_allowed][data-title="2"]').addClass('not-active');

    $('a[data-toggle=loayalty_earning_allowed][data-title="1"]').addClass('not-active');
    $('a[data-toggle=loayalty_earning_allowed][data-title="2"]').addClass('not-active');

    $('a[data-toggle=doctor_name_required][data-title="1"]').addClass('not-active');
    $('a[data-toggle=doctor_name_required][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_loyalty_scheme][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_loyalty_scheme][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_coupons_reverse][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_coupons_reverse][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_doctor][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_doctor][data-title="2"]').removeClass('active');
    $('a[data-toggle=mobile_enabled][data-title="1"]').removeClass('active');
    $('a[data-toggle=mobile_enabled][data-title="2"]').removeClass('active');

    $('a[data-toggle=mobile_discount_applicable][data-title="1"]').removeClass('active');
    $('a[data-toggle=mobile_discount_applicable][data-title="2"]').removeClass('active');

    $('a[data-toggle=service_level_discount_allowed][data-title="1"]').removeClass('active');
    $('a[data-toggle=service_level_discount_allowed][data-title="2"]').removeClass('active');

    $('a[data-toggle=loayalty_earning_allowed][data-title="1"]').removeClass('active');
    $('a[data-toggle=loayalty_earning_allowed][data-title="2"]').removeClass('active');

    $('a[data-toggle=doctor_name_required][data-title="1"]').removeClass('active');
    $('a[data-toggle=doctor_name_required][data-title="2"]').removeClass('active');

    $('a[data-toggle=is_loyalty_scheme][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_loyalty_scheme][data-title="2"]').removeClass('active');

    $('a[data-toggle=is_coupons_reverse][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_coupons_reverse][data-title="2"]').removeClass('active');

    $('a[data-toggle=is_internal][data-title="1"]').addClass('not-active');
    $('a[data-toggle=is_internal][data-title="2"]').addClass('not-active');

    $('a[data-toggle=is_internal][data-title="1"]').removeClass('active');
    $('a[data-toggle=is_internal][data-title="2"]').removeClass('active');

    $('#imagefile').val('');
    $('#photolog').empty();
    $('#Hdn_service_image').val('');
    $('#servicedocuments').val('');
    $('.mob_div').addClass('hidden');
    $("#base_amount_type option[value='4']").prop('disabled', false);
    $("#base_amount_type option[value='5']").prop('disabled', false);
    clear_external();
}
///service edit fuction
function serviceedit(event, val) {
    debugger;
    $('#shade_slot').show();
    // $('#service_table_list').hide();
    $('#service_table_list').dataTable().fnDraw();
    //$('#service_table_list').dataTable().fnDestroy();

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         $('#shade_slot').hide();
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {


                     var status = $('#status_' + val + '').html();
                     if (status == "In Active") {
                         toastr.warning("Unable to Edit the Service");
                     }
                     else {
                         var servicevalues = {
                             P_Dml_Indicator: "E",
                             master_service_id: val,
                         }
                         $.ajax({
                             async: true,
                             type: 'POST',
                             url: '/Billing/Service_Master_Ins_upd_sel',
                             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") {
                                         var data1 = data2.data;
                                         //   refereshform();
                                         if (data1[0].service_code == 'already_used') {
                                             toastr.warning('Service Already Used. Unable to Edit the Service');
                                             $('#service_creation_form').hide();
                                             return false;
                                         }
                                         $('.c_details_form').show();
                                         $('#add_new_service').hide();
                                         $('#Update_Test_record').hide();
                                         $('.progress-container').show();
                                         $('.progress-container').removeClass('hidden');
                                         //$('.box').addClass('box-with-trackbar');
                                         $('.table_view').hide();
                                         $('#add_new_serviceback').show();
                                         $('#add_new_servicebacklabel').show();
                                         $('#add_new_servicebacklist').hide();
                                         $('#add_new_servicebacklabellist').hide();
                                         $('#btnsubmit').html('Update')
                                         $("#service_code").val(data1[0].service_code)
                                         $("#master_service_id").val(data1[0].master_service_id)
                                         $("#Hdmaster_service_id").val(data1[0].master_service_id)
                                         //$("#branch_id").val(data1[0].branch_id) // medway all branch concept
                                         //LoadCategory(data1[0].branch_id, data1[0].master_category_id); //unwanted call
                                         //LoadDepartment(data1[0].branch_id, data1[0].department_id);
                                         $("#master_category_id").val(data1[0].master_category_id)
                                         $("#master_sub_category_id").val(data1[0].master_sub_category_id)
                                         $("#department_id").val(data1[0].department_id)
                                         $("#sub_department_id").val(data1[0].sub_department_id)
                                         if (data1[0].nonbillable == 1) {
                                             $('#non_billable').prop('checked', true);
                                         }
                                         else {
                                             $('#non_billable').prop('checked', false);
                                         }
                                         if (data1[0].is_consumable == 1) {
                                             $("#chkconsumable").prop('checked', true)
                                         } else {
                                             $("#chkconsumable").prop('checked',false)
                                         }

                                         var master_service_id = val
                                         var name = '1'
                                         LoadSubCategory(data1[0].master_category_id, data1[0].master_sub_category_id, master_service_id, name);
                                         LoadSubDepartment(data1[0].department_id, data1[0].sub_department_id, master_service_id, name);
                                         $("#service_name").val(data1[0].service_name)
                                         $("#method_name").val(data1[0].service_method_name)
                                         $("#duration").val(data1[0].duration)
                                         $("#service_type").val(data1[0].service_type)
                                         $('#short_name').val(data1[0].short_name);
                                         $('#display_name').val(data1[0].display_name);
                                         $("#service_description").val(data1[0].remarks)
                                         $("#base_amount_type").val(data1[0].base_amount_type)
                                         $("#Selprimarycost").val(data1[0].name)
                                         $("#HSelprimarycost").val(data1[0].PrimaryCostCentreid)
                                         $("#Selsecondarycost").val(data1[0].sub_cd_name)
                                         $("#HSelsecondarycost").val(data1[0].SecondaryCostCentreid)
                                         $("#SelLedge").val(data1[0].LedgerName)
                                         $("#HSelLedge").val(data1[0].Ledgerid)
                                         $("#HPackage_id").val(data1[0].package_id)
                                         LoadStore(data1[0].StoreId)
                                       
                                         $('#Hbase_amount_type').val(data1[0].base_amount_type);
                                         $("#base_amount_value").val(data1[0].base_amount_value)
                                        
                                         loadtube_container(data1[0].branch_id, data1[0].service_tube_container);
                                         loadAge_limit()
                                         $('#loadctubecontainer').val(data1[0].service_tube_container);
                                         $('#lab_type').val(data1[0].refunitflag);
                                         //var content = "";
                                         //content = "<p></p>";
                                         //$('#templateinfo').summernote('code', content);
                                         //content = "<p>" + data1[0].templateinfo + "</p>"; // Replace with your desired content
                                         //$('#templateinfo').summernote('code', content);
                                         //$(".dtfh-floatingparent.dtfh-floatingparenthead th").click();
                                         $("#status").val(data1[0].status);
                                       

                                         if (data1[0].is_consulting == "1") {

                                             $(".servicetype a[value='1']").removeClass("not_active").addClass("active");
                                             $(".servicetype a[value='2']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='3']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='4']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='5']").removeClass("active").addClass("not_active");

                                            // $('#Consulting').prop('checked', true);
                                             $("#consulting_type").val(data1[0].consulting_type);
                                             $("#consultation_type").val(data1[0].consultation_type);
                                             $('#div_doctor_enable').removeClass('hidden');

                                             $('#consulting').show();
                                             $('#workorder').hide();
                                             //$('#surgery').hide();
                                             //$('#misctab').hide();
                                             //$('#procedure').hide();
                                             //if (data1[0].consulting_type == 2) {
                                             //    $('#payafter').removeClass('hidden');

                                             //}
                                             //else {
                                             //    $('#payafter').addClass('hidden');

                                             //}

                                             //if (data1[0].consulting_type == 4) {
                                             //    $('#divChatValidDays').show();
                                             //}
                                             //$('#txtNoofChatValidDays').val(data1[0].chat_valid_days);

                                             //$('#consulting_typehidden').show();
                                             //$('#consultion_typehidden').show();
                                             $('#divSelDoctor').show();
                                             //$('#service_details').hide();                                         
                                             //$('#is_doctordiv').hide();
                                             $('#consulting_typehidden').show();
                                             $('#consultion_typehidden').show();
                                             $('#divSelDoctor').show();
                                             $('#mobile_enableddiv').addClass('hidden');
                                             $('#is_internaldiv').addClass('hidden');
                                             $('#external_div').addClass('hidden');
                                             $('#mobile_div').addClass('hidden');
                                             $('.mob_div').addClass('hidden');
                                             //$('#is_internaldiv').hide();
                                             //$('#distance_feediv').addClass('hidden');;
                                             $('#Is_Surgerydiv').hide();
                                             $("#consulting_typehidden").show();
                                             $("#divSelDoctor").show();
                                             //LoadDoctor(data1[0].branch_id, data1[0].sub_department_id, data1[0].doctorid);
                                             LoadDoctor(0, data1[0].sub_department_id, data1[0].doctorid);

                                         }
                                         //else {
                                         //    $('#consulting_typehidden').hide();
                                         //    $('#service_details').show();
                                         //    $('#consultion_typehidden').hide();
                                         //    $('#divSelDoctor').hide();
                                         //    $('#consulting_type').val('');
                                         //    $('#consultation_type').val('');
                                         //    $('#is_packagediv').show();
                                         //    $('#is_doctordiv').show();
                                         //    $('#mobile_enableddiv').show();
                                         //    $('#is_internaldiv').show();
                                         //    $('#distance_feediv').show();
                                         //    $('#Is_Surgerydiv').show();

                                         //}
                                         $("#Is_Surgery").val(data1[0].is_surgery)
                                         debugger;
                                         //if (data1[0].is_surgery != 1) {
                                         //$('a[data-toggle=typeofserviceapporder][data-title="' + data1[0].is_appointment + '"]').removeClass('not-active');
                                         //$('a[data-toggle=typeofserviceapporder][data-title="' + data1[0].is_appointment + '"]').addClass('active');
                                         $('#typeofserviceapporder').val(data1[0].is_appointment);
                                         if (data1[0].is_appointment == 1) {
                                             $('#div_Patienttime').show();
                                             $('#is_package').val(data1[0].is_appointment);
                                             $('#typeofserviceapporder').val(data1[0].is_appointment);
                                             $('#typeofserviceapporder').prop('checked', true);

                                             if (data1[0].service_type == 3) {
                                                 $('#p_time').html(' (in hours)');
                                                 $("#txtPatientTime").val(parseFloat(data1[0].per_patient_time) / 60);
                                             }
                                             else {
                                                 $('#p_time').html(' (in min)');
                                                 $("#txtPatientTime").val(data1[0].per_patient_time);
                                             }
                                             $('#appointment_details').removeClass('hidden');
                                             $('#handle_time').show();
                                             //$('.counter_addon').hide();
                                         }

                                         if (data1[0].base_amount_type == '3') {
                                             $("#range_min").val(data1[0].range_min)
                                             $("#range_max").val(data1[0].range_max)
                                             $(".ranges1").show();
                                             //$('#is_doctordiv').removeClass('hidden');
                                             //$('#is_internaldiv').removeClass('hidden');
                                             //$('#distance_feediv').removeClass('hidden');
                                             //$('#mobile_enableddiv').addClass('hidden');
                                             //$('.mob_div').addClass('hidden');

                                         }
                                             //else if (data1[0].base_amount_type == '1') {
                                             //    $('#mobile_enableddiv').addClass('hidden');
                                             //    $('.mob_div').addClass('hidden');
                                             //}
                                         else if ($('#base_amount_type').val() == 5) {
                                             $('#divward_id').show();
                                             //WardNo($('#branch_id').val(), data1[0].wardid) //medway all branch concept
                                             WardNo(0, data1[0].wardid)

                                             $('#service_details').hide();
                                             $('#handle_time').hide();
                                             $('#is_doctordiv').hide();
                                             $('#is_coupons_reversediv').hide();
                                             $('#is_internaldiv').hide();
                                             $('#distance_feediv').hide();
                                             $('#is_consultingdiv').hide();
                                             $('#mobile_enableddiv').hide();
                                             $('#Is_Surgerydiv').hide();
                                             $('#other_services').addClass('hidden');
                                             $('#consulting_details').addClass('hidden');
                                             $('#workorder_details').addClass('hidden');
                                             $('#mobile_options').addClass('hidden');
                                             $('#base_amount_type').attr('disabled', true);
                                             $('#div_doctor_enable').addClass('hidden');
                                             $('#external_div').addClass('hidden');
                                             $('#mobile_div').addClass('hidden');
                                             //if (parseFloat(data1[0].ward_status) > 0) {
                                             //    $('#ward_id').attr('disabled', true);
                                             //}

                                         }
                                         else if ($('#base_amount_type').val() == 4) {
                                             $('#service_details').hide();
                                             $('#is_doctordiv').show();
                                             $('#handle_time').hide();
                                             $('#is_coupons_reversediv').show();
                                             $('#is_internaldiv').show();
                                             $('#distance_feediv').hide();
                                             $('#is_consultingdiv').hide();
                                             $('#mobile_enableddiv').addClass("hidden");
                                             $('.mob_div').addClass("hidden");
                                             $('#Is_Surgerydiv').hide();
                                             $('#service_details').addClass('hidden');
                                             $('#consulting_details').addClass('hidden');
                                             $('#workorder_details').addClass('hidden');
                                             $('#base_amount_type').attr('disabled', true);
                                         }
                                         else {
                                             if (data1[0].is_consulting == "1") {
                                                 $('#divward_id').hide();
                                                 $('#service_details').show();

                                                 $('#handle_time').hide();
                                                 $('#is_doctordiv').show();
                                                 $('#is_coupons_reversediv').show();
                                                 $('#is_internaldiv').show();
                                                 $('#distance_feediv').show();
                                                 $('#is_consultingdiv').hide();
                                                 $('#mobile_enableddiv').show();
                                             }
                                             else {
                                                 var is_appointment = data1[0].is_appointment;
                                                 $('#divward_id').hide();
                                                 $('#service_details').show();

                                                 if (is_appointment == 1) {
                                                     $('#handle_time').show();
                                                 }
                                                 else {
                                                     $('#handle_time').hide();
                                                     $("#txtPatientTime").val(0);
                                                 }
                                                 $('#is_doctordiv').show();
                                                 $('#is_coupons_reversediv').show();
                                                 $('#is_internaldiv').show();
                                                 $('#distance_feediv').show();
                                                 $('#is_consultingdiv').show();
                                                 $('#mobile_enableddiv').show();
                                             }
                                         }
                                         debugger;

                                         $('#is_workorder').val(data1[0].is_workorder);


                                         var valtypeofservice = data1[0].is_workorder;
                                         if (valtypeofservice == 1) {

                                             $(".servicetype a[value='1']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='2']").removeClass("not_active").addClass("active");
                                             $(".servicetype a[value='3']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='4']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='5']").removeClass("active").addClass("not_active");

                                           //  $('#WorkOrder').prop('checked', true);
                                             $('#consulting').hide();
                                             $('#workorder').show();
                                             //$('#surgery').hide();
                                             //$('#misctab').hide();
                                             //$('#procedure').hide();
                                             //if (data1[0].is_lab == 1) {
                                             //    $('#typeofservicelab').prop('checked', true)
                                             //    $('#servicelab').show();
                                             //}
                                         }
                                         // $('.typeofservice')[valtypeofservice].checked = true;

                                         //if (valtypeofservice == 2 && $('#base_amount_type').val() != 4 && $('#base_amount_type').val() != 5) {
                                         //    $('#consulting_details').removeClass('hidden');
                                         //    $('#workorder_details').addClass('hidden');
                                         //    $('#nonworkorder_details').addClass('hidden');
                                         //    $('#other_services').removeClass('hidden');
                                         //    //if ($('#base_amount_type').val() != 3) {
                                         //    //$('#mobile_options').removeClass('hidden');
                                         //    //}
                                         //    $('#typeofserviceconsulting').prop('checked', true);
                                         //}
                                         //else if (valtypeofservice == 1) {
                                         //    $('#consulting_details').addClass('hidden');
                                         //    $('#workorder_details').removeClass('hidden');
                                         //    $('#nonworkorder_details').addClass('hidden');
                                         //    $('#typeofserviceworkorder').prop('checked', true);
                                         //    $('#other_services').removeClass('hidden');
                                         //    $('#mobile_options').removeClass('hidden');
                                         //}
                                         //else if (valtypeofservice == 3) {
                                         //    $('#consulting_details').addClass('hidden');
                                         //    $('#workorder_details').addClass('hidden');
                                         //    $('#appointment_details').addClass('hidden');
                                         //    $('#lab_details').addClass('hidden');
                                         //    $('#nonworkorder_details').removeClass('hidden');
                                         //    $('#other_services').addClass('hidden');
                                         //    $('#mobile_options').addClass('hidden');
                                         //    $('#typeofservicenone').prop('checked', true);
                                         //}

                                         var valworkorderoption = data1[0].is_lab;
                                         //$('a[data-toggle=typeofservicelab][data-title="' + valworkorderoption + '"]').removeClass('not-active');
                                         //$('a[data-toggle=typeofservicelab][data-title="' + valworkorderoption + '"]').addClass('active');
                                         if (valworkorderoption == 2 && valtypeofservice == 1) {
                                             $("#typeofservicelab").attr('checked', false);
                                             $('#servicelab').hide();
                                         }
                                         else if (valworkorderoption == 1 && valtypeofservice == 1) {
                                             $("#typeofservicelab").attr('checked', true);
                                             $('#servicelab').show();
                                         }
                                         else {
                                             $("#typeofservicelab").attr('checked', false);
                                             $('#servicelab').hide();
                                         }
                                         // $('#typeofservicelab').val(data1[0].is_lab);
                                         if (data1[0].is_internal == 2) {
                                             $("#isexternal").attr('checked', true);
                                             $('#externallab').show();
                                             //  loadExternal(0, 0, 0);
                                         }
                                         else {
                                             $("#isexternal").attr('checked', false);
                                             $('#externallab').hide();

                                         }

                                         // if (valworkorderoption == 2 && valtypeofservice == 1) {

                                         //$('#typeofserviceapporder').attr('checked', true);
                                         //$('#appointment_details').removeClass('hidden');
                                         //   $('#lab_details').addClass('hidden');

                                         // }
                                         //  else if (valworkorderoption == 1) {


                                         //$('#typeofservicelab').attr('checked', true);
                                         //$('#appointment_details').addClass('hidden');
                                         //  $('#lab_details').removeClass('hidden');
                                         //$('#fasting_div').removeClass('hidden');
                                         //$('#fasting_div').attr('disabled',true);
                                         //$('a[data-toggle=is_fasting][data-title="' + data1[0].is_fasting + '"]').removeClass('not-active');
                                         //$('a[data-toggle=is_fasting][data-title="' + data1[0].is_fasting + '"]').addClass('active');
                                         //$("#is_fasting").val(data1[0].is_fasting);
                                         //  }
                                         var valnonworkorderoption = data1[0].is_surgery;
                                         if (valnonworkorderoption == 1) {
                                           //  $('#Surgery').prop('checked', true);
                                             $('#div_doctor_enable').addClass('hidden');
                                             $('#external_div').addClass('hidden');
                                             $('#mobile_div').addClass('hidden');
                                             $('#consulting').addClass('hidden');
                                             $('#workorder').addClass('hidden');
                                             $(".servicetype a[value='1']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='2']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='3']").removeClass("not_active").addClass("active");
                                             $(".servicetype a[value='4']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='5']").removeClass("active").addClass("not_active");

                                         }
                                         else if (valnonworkorderoption == 2) {

                                             $(".servicetype a[value='1']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='2']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='3']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='4']").removeClass("not_active").addClass("active");
                                             $(".servicetype a[value='5']").removeClass("active").addClass("not_active");

                                           //  $('#misctab').prop('checked', true);
                                             $('#div_doctor_enable').removeClass('hidden');
                                             $('#external_div').addClass('hidden');
                                             $('#mobile_div').addClass('hidden');
                                             $('#consulting').addClass('hidden');
                                             $('#workorder').addClass('hidden');
                                         }
                                         else if (valnonworkorderoption == 3) {

                                             $(".servicetype a[value='1']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='2']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='3']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='4']").removeClass("active").addClass("not_active");
                                             $(".servicetype a[value='5']").removeClass("not_active").addClass("active");

                                             //$('#Procedure').prop('checked', true);
                                             $('#div_doctor_enable').removeClass('hidden');
                                             $('#external_div').addClass('hidden');
                                             $('#mobile_div').addClass('hidden');
                                             $('#consulting').addClass('hidden');
                                             $('#workorder').addClass('hidden');
                                         }

                                         //else {
                                         //    $('#is_doctordiv').addClass('hidden');
                                         //    $('#is_coupons_reversediv').addClass('hidden');
                                         //    $('#is_internaldiv').removeClass('hidden');
                                         //    $('#mobile_enableddiv').removeClass('hidden');
                                         //    $('#external_div').removeClass('hidden');
                                         //    $('#other_services').addClass('hidden');
                                         //}

                                         if (valnonworkorderoption == 2) {

                                             $('#nwoprocedure').attr('checked', true);


                                         }
                                         else if (valnonworkorderoption == 1) {

                                             $('#nwosurgery').attr('checked', true);

                                         }

                                         $("#is_doctor_enable").val(data1[0].is_doctor)
                                         //$('a[data-toggle=is_doctor][data-title="' + data1[0].is_doctor + '"]').removeClass('not-active');
                                         //$('a[data-toggle=is_doctor][data-title="' + data1[0].is_doctor + '"]').addClass('active');
                                         $("#mobile_enabled").val(data1[0].mobile_enabled)
                                        // if (data1[0].mobile_enabled == 1) {
                                             //$('.serviceuploadimg').show();
                                             $('#imagefile').val(data1[0].service_imagepath);
                                             $('#Hdn_service_image').val(data1[0].service_imagepath);
                                             $('.mob_div').removeClass('hidden');
                                             var profilephoto = data1[0].service_imagepath;
                                             var Doctor_Id = $('#myHiddenVar').val();
                                             var d, n, drloimage;
                                             d = new Date();
                                             n = d.getTime();
                                             //drinimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/' + $('#branch_id').val() + '/serviceimage/' + profilephoto + '?' + n; // medway all branch concept
                                             drinimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/serviceimage/' + profilephoto + '?' + n;

                                             if (profilephoto != null) {
                                                 $('#photolog').empty();
                                                 $('#photolog').append('<a href="' + drinimage + '" target="_blank" class="another-eye">View</a>');
                                                 var imageElement = '<img src="' + drinimage + '">';
                                                 $('.file_upload_image').html(imageElement);
                                             }
                                         //}
                                         //else {
                                         //    // $('.serviceuploadimg').hide();
                                         //    $('.mob_div').addClass('hidden');

                                         //}

                                         if ((data1[0].service_type == 1 || data1[0].service_type == 2) && data1[0].is_internal == 2) {
                                             $('.mob_div').addClass('hidden');
                                             $('#mobile_enableddiv').hide();
                                         }
                                         //if (data1[0].is_activate == 1) {
                                         //    $('#is_activate').prop('checked', true);
                                         //}
                                         //else {
                                         //    $('#is_activate').prop('checked', false);
                                         //}
                                         if ($('#base_amount_type').val() == 1 || $('#base_amount_type').val() == 3) {
                                             $('#activate_div').addClass('hidden');
                                         }

                                         if ($('#base_amount_type').val() == 1 || $('#base_amount_type').val() == 3) {
                                             $("#base_amount_value").attr('disabled', false);
                                         }
                                         else {
                                             $("#base_amount_value").attr('disabled', true);
                                         }


                                         //$('a[data-toggle=is_description][data-title="' + data1[0].is_description + '"]').removeClass('not-active');
                                         //$('a[data-toggle=is_description][data-title="' + data1[0].is_description + '"]').addClass('active');
                                         $('#billnamedesc').val(data1[0].is_description);

                                         //$('a[data-toggle=is_tax][data-title="' + data1[0].is_tax + '"]').removeClass('not-active');
                                         //$('a[data-toggle=is_tax][data-title="' + data1[0].is_tax + '"]').addClass('active');
                                         //$('#is_tax').val(data[0].is_tax);
                                      
                                         var istax = data1[0].is_tax
                                         $('#tax_applicable').val(istax)
                                         $("#tax_percentage").val(data1[0].tax_percentage)
                                         if (istax == 1) {
                                             $('#taxpercentage_div').removeClass('hidden')
                                         }
                                         else {
                                             $('#taxpercentage_div').addClass('hidden')
                                         }
                                         //if (data1[0].mobile_discount_applicable == 1) {
                                         //    $('.div_dis_applicable').removeClass('hidden');
                                         //}
                                         var valservicetype = $(".servicetype a.active").attr("value");
                                         $('#Hdservice_type_id').val(valservicetype)
                                         if (valservicetype == 1) {
                                             $('.crmservicetype').html('Consulting')
                                         }
                                         else if (valservicetype == 2) {
                                             $('.crmservicetype').html('Work Order')
                                         }
                                         else if (valservicetype == 3) {
                                             $('.crmservicetype').html('Surgery')
                                         }
                                         else if (valservicetype == 4) {
                                             $('.crmservicetype').html('Misc')
                                         }
                                         else if (valservicetype == 5) {
                                             $('.crmservicetype').html('Procedure')
                                         }                                    

                                         //$('a[data-toggle=mobile_enabled][data-title="' + data1[0].mobile_enabled + '"]').removeClass('not-active');
                                         //$('a[data-toggle=mobile_enabled][data-title="' + data1[0].mobile_enabled + '"]').addClass('active');
                                         $("#mobile_discount_applicable").val(data1[0].mobile_discount_applicable)
                                         $('a[data-toggle=mobile_discount_applicable][data-title="' + data1[0].mobile_discount_applicable + '"]').removeClass('not-active');
                                         $('a[data-toggle=mobile_discount_applicable][data-title="' + data1[0].mobile_discount_applicable + '"]').addClass('active');
                                         $("#mobile_discount_type").val(data1[0].mobile_discount_type)
                                         $("#mobile_discount_amount").val(data1[0].mobile_discount_amount)
                                         $("#service_level_discount_allowed").val(data1[0].service_level_discount_allowed)
                                         $('a[data-toggle=service_level_discount_allowed][data-title="' + data1[0].service_level_discount_allowed + '"]').removeClass('not-active');
                                         $('a[data-toggle=service_level_discount_allowed][data-title="' + data1[0].service_level_discount_allowed + '"]').addClass('active');
                                         $("#loayalty_earning_allowed").val(data1[0].loayalty_earning_allowed)
                                         $('a[data-toggle=loayalty_earning_allowed][data-title="' + data1[0].loayalty_earning_allowed + '"]').removeClass('not-active');
                                         $('a[data-toggle=loayalty_earning_allowed][data-title="' + data1[0].loayalty_earning_allowed + '"]').addClass('active');
                                         $("#doctor_name_required").val(data1[0].doctor_name_required)
                                         $('a[data-toggle=doctor_name_required][data-title="' + data1[0].doctor_name_required + '"]').removeClass('not-active');
                                         $('a[data-toggle=doctor_name_required][data-title="' + data1[0].doctor_name_required + '"]').addClass('active');
                                         $("#is_loyalty_scheme").val(data1[0].is_loyalty_scheme)
                                         $('a[data-toggle=is_loyalty_scheme][data-title="' + data1[0].is_loyalty_scheme + '"]').removeClass('not-active');
                                         $('a[data-toggle=is_loyalty_scheme][data-title="' + data1[0].is_loyalty_scheme + '"]').addClass('active');
                                         $("#refund_scenario").val(data1[0].is_coupons_reverse)
                                         //$('a[data-toggle=is_coupons_reverse][data-title="' + data1[0].is_coupons_reverse + '"]').removeClass('not-active');
                                         //$('a[data-toggle=is_coupons_reverse][data-title="' + data1[0].is_coupons_reverse + '"]').addClass('active');
                                         $("#is_internal").val(data1[0].is_internal)
                                         $('a[data-toggle=is_internal][data-title="' + data1[0].is_internal + '"]').removeClass('not-active');
                                         $('a[data-toggle=is_internal][data-title="' + data1[0].is_internal + '"]').addClass('active');
                                         $("#distance_fee").val(data1[0].distance_fee)
                                         $('a[data-toggle=distance_fee][data-title="' + data1[0].distance_fee + '"]').removeClass('not-active');
                                         $('a[data-toggle=distance_fee][data-title="' + data1[0].distance_fee + '"]').addClass('active');
                                         $('#testAddTable_body').val('');
                                         $('#testAddTable_body').empty('');
                                         $('#testAddTable_body').append('');
                                         $('#testTableRowCount').val('');
                                         if ($('#is_internal').val() == 2 && valtypeofservice == 1) {
                                             $('#external_div').removeClass('hidden');
                                         }
                                         var external = loadExternal(data1[0].branch_id, data1[0].is_lab, data1[0].is_appointment);
                                         $.when(external)
                                        .then(function (data) {
                                            //  if ($('#is_internal').val() == 2 && valtypeofservice == 1) {
                                            //$('#external_div').removeClass('hidden');

                                            if (data1[0].labtranid != null) {
                                                var s = data1[0].labtranid.split(',');
                                                var s1 = data1[0].labtranidamt.split(',');
                                                var labtranstatus = data1[0].labtranstatus.split(',');
                                                var labname = data1[0].labname.split(',');
                                                var labstatus = data1[0].labstatus.split(',');
                                                var labbranch = data1[0].labbranch.split(',');
                                                $('#tbl_external_lab tbody').empty();
                                                //var arr = [];
                                                var trow = '';
                                                for (var i = 0; i < s.length; i++) {
                                                    //arr[i] = $.trim(s[i]);
                                                    if (labstatus[i] == 1) {
                                                        if ($.trim(labtranstatus[i]) == '1') {
                                                            trow = '<tr id=lab_' + (i + 1) + ' data-id=' + $.trim(labbranch[i]) + '><td id=ex_lab_' + (i + 1) + ' data-id=' + s[i] + '>' + $.trim(labname[i]) + '<td id=ex_lab_amt_' + (i + 1) + '>' + $.trim(s1[i]) + '<td id="external_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick=external_lab_chk(' + (i + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue btn-xs" title="Make Inactive" onclick=external_lab_chk(' + (i + 1) + ',2) ><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></span></td></tr>'
                                                        }
                                                        else {
                                                            trow = '<tr id=lab_' + (i + 1) + ' data-id=' + $.trim(labbranch[i]) + '><td id=ex_lab_' + (i + 1) + ' data-id=' + s[i] + '>' + $.trim(labname[i]) + '<td id=ex_lab_amt_' + (i + 1) + '>' + $.trim(s1[i]) + '<td id="external_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick=external_lab_chk(' + (i + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue  btn-xs" title="Make Active" onclick=external_lab_chk(' + (i + 1) + ',1) ><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></span></td></tr>'
                                                        }
                                                    }
                                                    else {
                                                        trow = '<tr id=lab_' + (i + 1) + ' data-id=' + $.trim(labbranch[i]) + '><td id=ex_lab_' + (i + 1) + ' data-id=' + s[i] + '>' + $.trim(labname[i]) + '<td id=ex_lab_amt_' + (i + 1) + '>' + $.trim(s1[i]) + '<td id="external_action_' + (i + 1) + '"><span class="label label-warning">Lab Inactived</span></td></tr>'
                                                    }
                                                    $("#tbl_external_lab tbody").append(trow);


                                                }
                                                //$('#external_lab').val(arr).change();
                                            }
                                            //$('#external_lab').prop('disabled', true);
                                            //  }
                                        })



                                         serviceconsunabledit()

                                         //if (data1[0].ServiceId != null) {
                                           
                                         //    $('#isconsumables').prop('checked', true);
                                         //    $('#consumables').show();
                                         //    var ServiceId = data1[0].ServiceId.split(',');
                                         //    var ItemId = data1[0].ItemId.split(',');
                                         //    var ItemCode = data1[0].ItemCode.split(',');
                                         //    var ItemName = data1[0].ItemName.split(',');
                                         //    var Quantity = data1[0].Quantity.split(',');
                                         //    var Tax = data1[0].Tax.split(',');
                                         //    var Mrp = data1[0].Mrp.split(',');
                                         //    var sts = data1[0].consumablests.split(',');
                                         //    $('#tbl_consumables tbody').empty();
                                         //    //var arr = [];
                                         //    var trow = '';
                                         //    for (var i = 0; i < ServiceId.length; i++) {
                                         //        //arr[i] = $.trim(s[i]);
                                         //        if (sts[i] == 1) {
                                         //            if ($.trim(sts[i]) == '1') {

                                         //                trow = '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId[i]) + '><td id=ex_lab_' + (i + 1) + '>' + $.trim(ItemId[i]) + '<td id=con_hsn_' + (i + 1) + '>' + $.trim(ItemCode[i]) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName[i]) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity[i]) + '<td id="consumables_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (i + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue btn-xs" title="Make Inactive" onclick=consumables_chk(' + (i + 1) + ',2) ><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></span></td></tr>'
                                         //            }
                                         //            else {
                                         //                trow = '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId[i]) + '><td id=ex_lab_' + (i + 1) + '>' + $.trim(ItemId[i]) + '<td id=con_hsn_' + (i + 1) + '>' + $.trim(ItemCode[i]) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName[i]) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity[i]) + '<td id="consumables_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (i + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue  btn-xs" title="Make Active" onclick=consumables_chk(' + (i + 1) + ',1) ><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></span></td></tr>'
                                         //            }
                                         //        }
                                         //        else {
                                         //            trow = '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId[i]) + '><td id=ex_lab_' + (i + 1) + '>' + $.trim(ItemId[i]) + '<td id=con_hsn_' + (i + 1) + '>' + $.trim(ItemCode[i]) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName[i]) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity[i]) + '<td id="consumables_action_' + (i + 1) + '"><span class="label label-warning">Consumable Inactived</span></td></tr>'
                                         //        }
                                         //        $("#tbl_consumables tbody").append(trow);


                                         //    }

                                         //}





                                         if (parseFloat(data1[0].lab_param_count) > 0) {
                                             $('#Add_Test_record').addClass('hidden');
                                         }

                                         var sampletype = data1[0].sample_id;
                                         loadsampletype(sampletype);
                                         for (var i = 0; i < data1.length; i++) {
                                             var ParNamechk = data1[i].parameter_name;
                                             if (ParNamechk != null) {
                                                 var sess_key;
                                                 var rowcount = $.trim($('#testTableRowCount').val());
                                                 var tot_row = (Number(rowcount) + 1);
                                                 var ikey = '';
                                                 var ParName, RefValue, Unit, SampleType, parameter_id, display_order;
                                                 if (data1[i].parameter_name == "" || data1[i].parameter_name == null) ParName = '';
                                                 else ParName = data1[i].parameter_name;
                                                 if (data1[i].reference_value == "" || data1[i].reference_value == null) RefValue = '';
                                                 else RefValue = data1[i].reference_value;
                                                 if (data1[i].unit == "" || data1[i].unit == null) Unit = '';
                                                 else Unit = data1[i].unit;
                                                 if (data1[i].display_order == "" || data1[i].display_order == null) display_order = '';
                                                 else display_order = data1[i].display_order;
                                                 if (data1[i].sample_type == "" || data1[i].sample_type == null) SampleType = '';
                                                 else SampleTypeval = data1[i].sample_type;
                                                 if (data1[i].sample_id == "" || data1[i].sample_id == null) sample_id = '';
                                                 else SampleType = data1[i].sample_id;

                                                 if (data1[i].parameter_id == "" || data1[i].parameter_id == null) parameter_id = '';
                                                 else parameter_id = data1[i].parameter_id;
                                                 var Instructions = data1[i].parameter_instructions;
                                                 if (Instructions == '' || Instructions == null) {
                                                     Instructions = '';
                                                 }
                                                 var form_id = data1[i].form_id
                                                 var form_name = data1[i].Form_Name

                                                 ikey = i + 1;

                                                 //var gender = (data1[i].gender == 0) ? '-' : $('#pgender option[value=' + (data1[i].gender) + ']').text();
                                                 //var age_limit = (data1[i].age_limit == 0) ? '-' : $('#age_limit option[value=' + (data1[i].age_limit) + ']').text();

                                                 //  var value = "<tr id='t_" + ikey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-danger  btn-sm btn-add' onclick='labdelete_pan(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                                                 //  if (ParName == "") {
                                                 // var value = "";
                                                 //   }
                                                 // else {
                                                 // var value = "<tr  class='tr_input number' data-id='" + ikey + "'id='t_" + ikey + "'><td>" + ParName + "</td><td>" + RefValue + "</td><td>" + Unit + "</td><td>" + SampleTypeval + "</td><td>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                                                 //var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='res_" + ikey + "' data-val='" + data1[i].result_type + "'>" + $("#result_type option[value=" + (data1[i].result_type) + "]").text() + "</td><td id='gender_" + ikey + "' data-val=" + data1[i].gender + ">" + gender + "</td><td id='age_" + ikey + "' data-val=" + data1[i].age_limit + ">" + age_limit + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='min_" + ikey + "'>" + (data1[i].min_value) + "</td><td id='max_" + ikey + "'>" + (data1[i].max_value) + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
                                                 // var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='tubecontainerid_" + ikey + "' hidden>" + data1[i].tube_id + "</td><td id='tubecontainerval_" + ikey + "'>" + data1[i].master_service_name + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='Method_" + ikey + "'>" + data1[i].method_name + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";


                                                 //last change
                                                 // var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='btn btn-xs btn-edit mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-xs btn-delete mr-10' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button><button class='btn btn-xs btn-edit' data-toggle='modal' data-target='#pop_range' onclick='range_pop_click(" + parameter_id + ",\"" + SampleTypeval + "\",\"" + ParName + "\")'><i class='fa fa-bars' aria-hidden='true'></i></button></td></tr>";
                                                 debugger;
                                                 if ($('#lab_type').val() == 1) {
                                                     $('#form_name_header').hide()
                                                     $('#param_name_header').show()
                                                     $('#div_param_name').show()
                                                     $('#div_form_name').hide()

                                                     $('#rvalue').attr('disabled', false)
                                                     $('#unit').attr('disabled', false)
                                                     $('#txt_dis_order').attr('disabled', false)
                                                     $('#testNotes').attr('disabled', false)

                                                     var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='btn btn-xs btn-edit mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-xs btn-delete mr-10' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button><button class='btn btn-xs btn-edit' data-toggle='modal' data-target='#pop_range' onclick='range_pop_click(" + parameter_id + ",\"" + SampleTypeval + "\",\"" + ParName + "\")'><i class='fa fa-bars' aria-hidden='true'></i></button></td></tr>";
                                                 }
                                                 else {
                                                     if ($('#HFormbuilder_id').val() == 1) {
                                                         $('#form_name_header').show()
                                                         $('#param_name_header').hide()
                                                         $('#div_param_name').hide()
                                                         $('#div_form_name').show()

                                                         $('#rvalue').attr('disabled', true)
                                                         $('#unit').attr('disabled', true)
                                                         $('#txt_dis_order').attr('disabled', true)
                                                         $('#testNotes').attr('disabled', true)
                                                         load_form_names()

                                                         var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='form_id_" + ikey + "' style='display:none'>" + form_id + "</td><td id='form_name_" + ikey + "'>" + form_name + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='btn btn-xs btn-edit mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-xs btn-delete mr-10' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button><button class='btn btn-xs btn-edit' data-toggle='modal' data-target='#pop_range' onclick='range_pop_click(" + parameter_id + ",\"" + SampleTypeval + "\",\"" + ParName + "\")'><i class='fa fa-bars' aria-hidden='true'></i></button></td></tr>";
                                                     }
                                                     else {
                                                         $('#form_name_header').hide()
                                                         $('#param_name_header').show()
                                                         $('#div_param_name').show()
                                                         $('#div_form_name').hide()

                                                         $('#rvalue').attr('disabled', false)
                                                         $('#unit').attr('disabled', false)
                                                         $('#txt_dis_order').attr('disabled', false)
                                                         $('#testNotes').attr('disabled', false)

                                                         var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + data1[i].refunitflag + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='btn btn-xs btn-edit mr-10' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-xs btn-delete mr-10' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button><button class='btn btn-xs btn-edit' data-toggle='modal' data-target='#pop_range' onclick='range_pop_click(" + parameter_id + ",\"" + SampleTypeval + "\",\"" + ParName + "\")'><i class='fa fa-bars' aria-hidden='true'></i></button></td></tr>";
                                                     }
                                                 }

                                                 // var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id='SampleTypeval_" + ikey + "'>" + SampleTypeval + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td></td></tr>";


                                                 //<td id='tubecontainerid_" + ikey + "' hidden>" + tubecontainerid + "</td><td id='tubecontainerval_" + ikey + "'>" + tubecontainerval + "</td>
                                                 // }
                                                 $('#AddTestTable > tbody:last').append(value);
                                                 $('#testTableRowCount').val(tot_row);

                                                 //$("#base_amount_value").attr('disabled', true);
                                                 $('#lab_type').attr('disabled', true);
                                                 $('#sType').attr('disabled', true);
                                                 //$('#branch_id').attr('disabled', true); //medway all branch concept
                                                 $('#master_category_id').attr('disabled', true);
                                                 $('#master_sub_category_id').attr('disabled', true);
                                                 $('#department_id').attr('disabled', true);
                                                 $('#sub_department_id').attr('disabled', true);
                                                 // $('#service_name').attr('disabled', true);
                                                 $('#consulting_type').attr('disabled', true);
                                                 $('#SelDoctor').attr('disabled', true);
                                                 $('#service_type').attr('disabled', true);
                                                 $('#is_consultingdiv').attr('disabled', true);
                                                 $('.typeofservice').addClass('disabled');
                                                 $('#typeofserviceapporder').attr('disabled', true);
                                                 $('#txtPatientTime').attr('disabled', true);
                                                 $('#typeofservicelab').attr('disabled', true);
                                                 $('.workorderoption').attr('disabled', true);
                                                 $('.workorderapp').attr('disabled', true);
                                                 $('.nonworkorderoption').attr('disabled', true);
                                                 $('#is_internaldiv').addClass('disabled');
                                                 //$('#mobile_discount_type').attr('disabled',true);
                                                 //$('#mobile_discount_amount').attr('disabled',true);
                                                 //$('#mobile_discount_applicablediv').attr('disabled',true);
                                                 $('#service_level_discount_alloweddiv').attr('disabled', true);
                                                 $('#loayalty_earning_alloweddiv').attr('disabled', true);
                                                 $('#doctor_name_requireddiv').attr('disabled', true);
                                                 $('#is_loyalty_schemediv').attr('disabled', true);
                                                 $('#Is_Surgerydiv').addClass('disabled');
                                                 $('#lab_div').addClass('disabled');
                                                 $('#appointment_div').addClass('disabled');
                                                 //$('#activate_div').attr('disabled',true);

                                             }
                                             else {
                                                 //$("#base_amount_value").attr('disabled', true);
                                                 //$('#branch_id').attr('disabled', true); // medway all branch concept
                                                 $('#master_category_id').attr('disabled', true);
                                                 $('#master_sub_category_id').attr('disabled', true);
                                                 $('#department_id').attr('disabled', true);
                                                 $('#sub_department_id').attr('disabled', true);
                                                 //$('#service_name').attr('disabled', true);
                                                 $('#consulting_type').attr('disabled', true);
                                                 $('#SelDoctor').attr('disabled', true);
                                                 $('#service_type').attr('disabled', true);
                                                 $('#is_consultingdiv').attr('disabled', true);
                                                 $('.typeofservice').addClass('disabled');
                                                 $('.workorderoption').attr('disabled', true);
                                                 $('.workorderapp').attr('disabled', true);
                                                 $('.nonworkorderoption').attr('disabled', true);
                                                 $('#is_internaldiv').addClass('disabled');
                                                 //$('#mobile_discount_type').attr('disabled',true);
                                                 //$('#mobile_discount_amount').attr('disabled',true);
                                                 //$('#mobile_discount_applicablediv').attr('disabled',true);
                                                 $('#service_level_discount_alloweddiv').attr('disabled', true);
                                                 $('#loayalty_earning_alloweddiv').attr('disabled', true);
                                                 $('#doctor_name_requireddiv').attr('disabled', true);
                                                 $('#is_loyalty_schemediv').attr('disabled', true);
                                                 $('#Is_Surgerydiv').addClass('disabled');
                                                 $('#lab_div').addClass('disabled');
                                                 $('#appointment_div').addClass('disabled');
                                                 //$('#activate_div').attr('disabled',true);
                                             }
                                         }
                                         $('#mobile_options').show();
                                         $('#discount_allowed').show();
                                         //}
                                         //else {


                                         //    $('#service_details').hide();
                                         //    $('#is_internaldiv').hide();
                                         //    $('#is_doctordiv').hide();
                                         //    $('#is_coupons_reversediv').hide();
                                         //    $('#is_packagediv').hide();
                                         //    $('#mobile_enableddiv').hide();
                                         //    $('#distance_feediv').hide();
                                         //    $('#mobile_options').hide();
                                         //    $('#discount_allowed').hide();
                                         //    $('#lab_enabled').hide();
                                         //    $('#Is_Surgerydiv').attr('disabled',true);
                                         //}

                                         LoadFormmappingTable(1)
                                         table_package()
                                         LoadCRMmappingTable()
                                         loadCampaigndata();
                                         editSales();
                                         schem_mappingTable($("#Hdmaster_service_id").val())
                                         $('#lblServiceName').html(data1[0].service_name)
                                         $('#lblDepartment').html(data1[0].name)
                                         $('#lblSubDepartment').html(data1[0].sub_cd_name)
                                         $('#lblBaseAmount').html(data1[0].base_amount_value)
                                     }
                                     else {
                                         console.log(data);
                                     }
                                 }

                             }
                         });
                        
                         $('#service_creation_form').show();
                         $('#add_new_service').hide();
                         $("html, body").animate({ scrollTop: 0 }, 2000);
                     }

                 }
             }
         }
     });

}
// delete service
function servicedel(event, val, flag) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {


                     var status = "";
                     if (flag == 0) {
                         status = "Are You Sure, You Want to Delete the Service?";
                     }
                     else if (flag == 2) {
                         status = "Are You Sure, You Want to In-Activate the Service?";
                     }
                     else if (flag == 1) {

                         status = "Are You Sure,You Want to Activate the Service?";
                     }
                     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 = {
                                           P_Dml_Indicator: "D",
                                           master_service_id: val,
                                           is_package: flag

                                       }
                                       $.ajax({
                                           async: true,
                                           type: 'POST',
                                           url: '/Billing/Service_Master_Ins_upd_sel',
                                           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") {
                                                       if (flag == 0 || flag == 2) {
                                                           var data1 = data2.data;
                                                           if (data1[0].status == 'Mapped Package Service Delete') {
                                                               toastr.warning("<button type='button' id='confirmationRevertYes1' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo1' class='btn btn-warning btn-xs mt20'>No</button>", 'You Can delete this service,this service mapped on the some other package',

                                                               {

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

                                                                   onShown: function (toast) {
                                                                       debugger;
                                                                       $("#confirmationRevertYes1").click(function () {
                                                                           debugger;
                                                                           var master_data_type = {
                                                                               P_Dml_Indicator: 'DD',
                                                                               master_service_id: val,
                                                                               is_package: flag
                                                                           }
                                                                           $.ajax({
                                                                               async: true,
                                                                               type: 'POST',
                                                                               url: '/Billing/Service_Master_Ins_upd_sel',
                                                                               contentType: 'application/json; charset=UTF-8',
                                                                               data: JSON.stringify(master_data_type),
                                                                               success: function (data) {
                                                                                   debugger;
                                                                                   var data1 = JSON.parse(data)
                                                                                   if (data1.msg == "Success") {
                                                                                       var data2 = data1.data;
                                                                                       toastr.success('Deleted successfully');
                                                                                       //location.reload();
                                                                                       loadservicedata(0, 1);
                                                                                   }
                                                                                   else {
                                                                                       console.log(data2)
                                                                                   }
                                                                               }
                                                                           })
                                                                       })
                                                                   }
                                                               })
                                                           }

                                                           else if (data1[0].status != 'deleted') {

                                                               toastr.warning(data1[0].status);
                                                               return false;
                                                           }
                                                           else if (flag == 0) {
                                                               $("#servicedel_" + val + "").hide();
                                                               $("#status_" + val + "").html('Active');

                                                               toastr.success("Service Deleted Successfully");
                                                               loadservicedata(0, 1);
                                                           }
                                                           else {
                                                               $("#servicedel_" + val + "").hide();
                                                               $("#status_" + val + "").html('Deleted');
                                                               //sessionStorage.removeItem(val);
                                                               toastr.success("Service Inactivated Successfully");
                                                               loadservicedata(0, 1);
                                                           }
                                                       }                                                       
                                                       else {
                                                           $("#servicedel_" + val + "").hide();
                                                           $("#status_" + val + "").html('Active');

                                                           toastr.success("Service Activated Successfully");
                                                           loadservicedata(0, 1);
                                                       }

                                                       //$('#t_' + val).remove();
                                                   }
                                               }
                                           }
                                       });
                                   });
                               }
                           });

                 }
             }
         }
     });
}


//insert and update function
$("#btnsubmit").click(function () {
    insertupdateservice();
})

function insertupdateservice() {
    debugger;

    var service_status = $('#status').val();
    var service_name = $("#service_name").val();
    var display_name = $('#display_name').val();
    var remark = $('#service_description').val();
    var Pdepartment_id = $("#department_id").val();
    var Psub_department_id = $("#sub_department_id").val();
    var Pmaster_category_id = $("#master_category_id").val();
    var Pmaster_sub_category_id = $("#master_sub_category_id").val();
    var Pservice_type = $("#service_type").val();
    var Pbase_amount_type = $("#base_amount_type").val();
    var Pis_consulting = "0";
    var Pbillnamedesc = $("#billnamedesc").val();
    var is_internal
    if ($('#isexternal').is(":checked")) {
        is_internal = 2
    }
    else {
        is_internal = 1
    }
    var store_id = ''
    if ($('#store_name').val() == '' || $('#store_name').val() == undefined) {
        store_id = 0
    }
    else {
        store_id = $('#store_name').val()
    }
    var Pis_surgery = 0;
    var is_workorder = "";
    // var is_lab = $("#typeofservicelab").val();
    var is_lab
    if ($("#typeofservicelab").prop("checked")) {
        is_lab = 1
    } else {
        is_lab = 2
    }
    var is_consumables
    if ($("#chkconsumable").prop("checked")) {
        is_consumables = 1
    } else {
        is_consumables = 0
    }
    var appointmentbooking = $('#typeofserviceapporder').val();
    var Pis_doctor = $("#is_doctor_enable").val();
    var Pmobile_enabled = $("#mobile_enabled").val();
    // var is_internal = $('#isexternal').val();
    // var distance_fee = $('#distance_fee').val();
    var Pstatus = $("#status").val();
    var is_description = $('#billnamedesc').val();
    var is_tax = $('#tax_applicable').val();
    var is_activate = $('#is_activate').val();
    var refund_scenario = $('#refund_scenario').val();
     var short_name = $('#short_name').val();
    var external_lab = 0;
    //   var cg_hms = $('#cg_hms').val();

    if (!service_name) {
        $('#Pservice_name').show();
        $('#Pservice_name').fadeOut(8000);
        $('#Pservice_name').html('Enter Service Name');
        $('#service_name').focus();
        return false;
    }
    if ($.trim((Pdepartment_id)) == "" || $.trim((Pdepartment_id)) == 0) {
        $('#Pdepartment_id').show();
        $('#Pdepartment_id').fadeOut(8000);
        $('#Pdepartment_id').html('Select Department Name');
        $('#department_id').focus();
        return false;
    }
    if ($.trim((Psub_department_id)) == "" || $.trim((Psub_department_id)) == 0) {
        $('#Psub_department_id').show();
        $('#Psub_department_id').fadeOut(8000);
        $('#Psub_department_id').html('Select Sub Department Name');
        $('#sub_department_id').focus();
        return false;
    }
    if ($.trim((Pservice_type)) == "" || $.trim((Pservice_type)) == 0) {
        $('#Pservice_type').show();
        $('#Pservice_type').fadeOut(8000);
        $('#Pservice_type').html('Select Service Type');
        $('#service_type').focus();
        return false;
    }

    if ($.trim((Pmaster_category_id)) == "" || $.trim((Pmaster_category_id)) == 0) {
        $('#Pmaster_category_id').show();
        $('#Pmaster_category_id').fadeOut(8000);
        $('#Pmaster_category_id').html('Select Category Name');
        $('#master_category_id').focus();
        return false;
    }
    if ($.trim((Pmaster_sub_category_id)) == "" || $.trim((Pmaster_sub_category_id)) == 0) {
        $('#Pmaster_sub_category_id').show();
        $('#Pmaster_sub_category_id').fadeOut(8000);
        $('#Pmaster_sub_category_id').html('Select Sub Category Name');
        $('#master_sub_category_id').focus();
        return false;
    }
    if ($('#Selprimarycost').val() == "" || $('#HSelprimarycost').val() == '' || $('#HSelprimarycost').val() == 0) {
        $('#PSelprimarycost').show();
        $('#PSelprimarycost').fadeOut(8000);
        $('#PSelprimarycost').html('Choose primary Cost Centre');
        $('#master_sub_category_id').focus();
        $('#PSelprimarycost')[0].scrollIntoView(true);
        return false;
    }
    if ($('#Selsecondarycost').val() == "" || $('#HSelsecondarycost').val() == '' || $('#HSelsecondarycost').val() == 0) {
        $('#PSelsecondarycost').show();
        $('#PSelsecondarycost').fadeOut(8000);
        $('#PSelsecondarycost').html('Choose Secondary Cost Centre');
        $('#PSelsecondarycost')[0].scrollIntoView(true);
        return false;
    }
    if ($('#SelLedge').val() == "" || $('#HSelLedge').val() == '' || $('#HSelLedge').val() == 0) {
        $('#PSelLedge').show();
        $('#PSelLedge').fadeOut(8000);
        $('#PSelLedge').html('Choose Ledger');
        $('#PSelLedge')[0].scrollIntoView(true);
        return false;
    }
    $('#shade_slot_submit').show();

    if ($.trim((Pbase_amount_type)) == "" || $.trim((Pbase_amount_type)) == 0) {
        $('#Pbase_amount_type').show();
        $('#Pbase_amount_type').fadeOut(8000);
        $('#Pbase_amount_type').html('Select Base Amount Type');
        $('#base_amount_type')[0].scrollIntoView(true);
        return false;
    }
    var Prange_min = $("#range_min").val();
    var Prange_max = $("#range_max").val();

    if ($.trim((is_description)) == "") {
        is_description = 2;
    }
    if ($.trim((Pbase_amount_type == "4"))) {
        Pmobile_enabled = 2;
    }

    if ($.trim((Pbase_amount_type)) == "3") {

        if ($.trim((Prange_min)) == "") {
            $('#Prange_min').show();
            $('#Prange_min').fadeOut(8000);
            $('#Prange_min').html('Enter Range Min');
            $('#range_min')[0].scrollIntoView(true);
            return false;
        }
        if ($.trim((Prange_max)) == "") {
            $('#Prange_max').show();
            $('#Prange_max').fadeOut(8000);
            $('#Prange_max').html('Enter Range Max');
            $('#range_max')[0].scrollIntoView(true);
            return false;
        }
    }
    if ($.trim((Pbase_amount_type)) == "5") {
        if ($('#ward_id').val() == '' || $('#ward_id').val() == 0 || $('#ward_id').val() == null) {
            $('#Pward_id').show();
            $('#Pward_id').fadeOut(8000);
            $('#Pward_id').html('Select Ward No');
            $('#ward_id')[0].scrollIntoView(true);
            return false;
        }
    }
    if ($('#base_amount_value').val() == '') {
        $('#Pbase_amount_value').show();
        $('#Pbase_amount_value').fadeOut(8000);
        $('#Pbase_amount_value').html('Enter base amount value');
        $('#base_amount_value')[0].scrollIntoView(true);
        return false;
    }
    if ($.trim((Pbillnamedesc)) == "" || $.trim((Pbillnamedesc)) == 0) {
        $('#Pbillnamedesc').show();
        $('#Pbillnamedesc').fadeOut(8000);
        $('#Pbillnamedesc').html('Select Billing Name Description');
        $('#billnamedesc').focus();
        return false;
    }

    var is_tax = ($('#tax_applicable').val() == '') ? 2 : $('#tax_applicable').val();
    if (is_tax == 1) {
        if ($('#tax_percentage').val() == '') {
            $('#Ptax_percentage').show();
            $('#Ptax_percentage').fadeOut(8000);
            $('#Ptax_percentage').html('Enter Percentage');
            $('#tax_percentage')[0].scrollIntoView(true);
            return false;
        }
    }
    if (short_name == '') {
        $('#Pshort_name').show();
        $('#Pshort_name').fadeOut(8000);
        $('#Pshort_name').html('Enter Short Name');
        $('#short_name')[0].scrollIntoView(true);
        return false;
    }
    if (display_name == '') {
        $('#Pdisplay_name').show();
        $('#Pdisplay_name').fadeOut(8000);
        $('#Pdisplay_name').html('Enter Display Name');
        $('#display_name')[0].scrollIntoView(true);
        return false;
    }

    var Pconsulting_type = $("#consulting_type").val();
    if ($.trim(($("input[name='typeofservice']:checked").val())) == "1") {
        if ($.trim((Pconsulting_type)) == "" || $.trim((Pconsulting_type)) == 0) {
            $('#Pconsulting_type').show();
            $('#Pconsulting_type').fadeOut(8000);
            $('#Pconsulting_type').html('Select Is Consulting Type');
            $('#consulting_type')[0].scrollIntoView(true);
            return false;
        }

        var Pconsultion_type = $("#consultation_type").val();
        if ($.trim((Pconsultion_type)) == "" || $.trim((Pconsultion_type)) == 0) {
            $('#Pconsultion_type').show();
            $('#Pconsultion_type').fadeOut(8000);
            $('#Pconsultion_type').html('Select Is Consultion Type');
            $('#consultation_type')[0].scrollIntoView(true);
            return false;
        }

        if ($('#consulting_type').val() == 4 || $('#consulting_type').val() == "4") {
            if ($('#txtNoofChatValidDays').val() == "" || $('#txtNoofChatValidDays').val() == null) {
                $('#PtxtNoofChatValidDays').show();
                $('#PtxtNoofChatValidDays').fadeOut(8000);
                $('#PtxtNoofChatValidDays').html('Enter Chat Valid Days');
                $('#txtNoofChatValidDays')[0].scrollIntoView(true);
                return false;
            }
        }

        var PSelDoctor = $("#SelDoctor").val();
        if ($.trim((PSelDoctor)) == "" || $.trim((PSelDoctor)) == 0) {
            $('#PSelDoctor').show();
            $('#PSelDoctor').fadeOut(8000);
            $('#PSelDoctor').html('Select Doctor Name');
            $('#SelDoctor')[0].scrollIntoView(true);
            return false;
        }
    }

    if ((Pservice_type == 1 || Pservice_type == 2) && $('#is_internal').val() == 2) {
        Pmobile_enabled = 2
    }
    var valtypeofservice = 0;
    var valworkorderoption;
    var vallab = ''
    if ($('#typeofservicelab').prop("checked")) {
        vallab = 1
    }
    else {
        vallab = 2
    }
    valtypeofservice = $(".servicetype a.active").attr("value");
    $('#Hdservice_type_id').val(valtypeofservice);
    if ($('#base_amount_type').val() != 5 && $('#base_amount_type').val() != 4) {

        if (valtypeofservice == 1) {
            Pis_consulting = 1
            is_workorder = 2
            valworkorderoption = vallab;
        }
        else if (valtypeofservice == 2) {
            Pis_consulting = 2
            is_workorder = 1
            valworkorderoption = vallab;
            valworkapp = $('#typeofserviceapporder').val();
        }
        else if (valtypeofservice == 3) {
            Pis_consulting = 2
            is_workorder = 3
            valworkorderoption = 3;
        }
        else if (valtypeofservice == 4) {
            Pis_consulting = 2
            is_workorder = 4
            valworkorderoption = vallab;
        }
        else if (valtypeofservice == 5) {
            Pis_consulting = 2
            is_workorder = 5
            valworkorderoption = vallab;
        }
       
    }
    else {
        is_lab = 2;
        is_workorder = 2;
        Pis_consulting = 2;

        Pis_doctor = 2
        distance_fee = 2;
        if ($('#base_amount_type').val() == 5) {
            Pmobile_enabled = 2;
            is_internal = 1;
        }
    }

    if (valtypeofservice == 2) {

        if (valworkorderoption == '') {
            $('#Ptypeofservicelab').show();
            $('#Ptypeofservicelab').fadeOut(8000);
            $('#Ptypeofservicelab').html('Select Lab');
            $('#Ptypeofservicelab')[0].scrollIntoView(true);
            return false;
        }
        else if (valworkapp == '') {
            $('#Ptypeofserviceapporder').show();
            $('#Ptypeofserviceapporder').fadeOut(8000);
            $('#Ptypeofserviceapporder').html('Select Appointment Booking');
            $('#Ptypeofserviceapporder')[0].scrollIntoView(true);
            return false;
        }
        else if (valworkorderoption == 2 && valworkapp == 2) {
            $('#Ptypeofservicelab').show();
            $('#Ptypeofservicelab').fadeOut(8000);
            $('#Ptypeofservicelab').html('Select Lab or Appointment Booking to Yes');
            $('#Ptypeofservicelab')[0].scrollIntoView(true);
            return false;
        }
        else if ($('#typeofservicelab').val() == 1) {
            if ($('#duration').val() == '' || $('#duration').val() == null) {
                $('#Pduration').show();
                $('#Pduration').fadeOut(8000);
                $('#Pduration').html('Enter Duration');
                $('#Pduration')[0].scrollIntoView(true);
                return false;
            }
        }
        else {
            //if ($('#typeofservicelab').prop('checked')) {
            //    is_lab = 1
            //}
            //else {
            //    is_lab = 2
            //}
            if (valworkorderoption == 1) {
                is_lab = 1
                //appointmentbooking = 2
            }
            else if (valworkorderoption == 3) {
                is_lab = 2
                //appointmentbooking = 2
            }
            else {
                is_lab = 2
            }
        }
    }

    if (valtypeofservice == 3) {
        Pis_surgery = 1
    }
    else if (valtypeofservice == 4) {
        Pis_surgery = 2
    }
    else if (valtypeofservice == 5) {
        Pis_surgery = 3
    }

    if ($.trim((Pbase_amount_type)) == 5) {
        if ($('#ward_id').val() == '' || $('#ward_id').val() == 0 || $('#ward_id').val() == null) {
            $('#Pward_id').show();
            $('#Pward_id').fadeOut(8000);
            $('#Pward_id').html('Select Ward No');
            $('#ward_id')[0].scrollIntoView(true);
            return false;
        }
        if ($('#base_amount_value').val() == '') {
            $('#Pbase_amount_value').show();
            $('#Pbase_amount_value').fadeOut(8000);
            $('#Pbase_amount_value').html('Enter base_amount_value');
            $('#base_amount_value')[0].scrollIntoView(true);
            return false;
        }

    }
    else if ($.trim((Pbase_amount_type)) == 4) {
        if ($('#base_amount_value').val() == '') {
            $('#Pbase_amount_value').show();
            $('#Pbase_amount_value').fadeOut(8000);
            $('#Pbase_amount_value').html('Enter base_amount_value');
            $('#base_amount_value')[0].scrollIntoView(true);
            return false;
        }
        var Pmobile_enabled = $("#mobile_enabled").val();
        if ($.trim((Pmobile_enabled)) == "") {
            $('#Pmobile_enabled').show();
            $('#Pmobile_enabled').fadeOut(8000);
            $('#Pmobile_enabled').html('Select Is Mobile Enabled');
            $('#Pmobile_enabled')[0].scrollIntoView(true);
            return false;
        }
    }

    if ($.trim((is_lab)) == "1") {
        var tot_rowM = $('#AddTestTable >tbody >tr').length;
        if (tot_rowM == 0) {

            toastr.warning('Please Add Lab Parameters');
            return false;
        }
    }

    if ($.trim((appointmentbooking)) == "1") {
        if ($.trim(($('#txtPatientTime').val())) == "" || $.trim(($('#txtPatientTime').val())) == 00) {
            $('#PtxtPatientTime').show();
            $('#PtxtPatientTime').fadeOut(8000);
            $('#PtxtPatientTime').html('Select Patient handling time');
            $('#txtPatientTime')[0].scrollIntoView(true);
            return false;
        }
    }

    if (valtypeofservice != 3) {
        if ($.trim((Pis_doctor)) == "" || $.trim((Pis_doctor)) == 0) {
            $('#Pis_doctor_enable').show();
            $('#Pis_doctor_enable').fadeOut(8000);
            $('#Pis_doctor_enable').html('Select Is Doctor');
            $('#Pis_doctor_enable')[0].scrollIntoView(true);
            return false;
        }
    }

    if (is_workorder == "") {
        is_workorder = 0;
    }
    if (is_lab == "") {
        is_lab = 0;
    }

    var Dml_Indicator;
    var master_service_id = $("#master_service_id").val()
    if (master_service_id != '' || $('#btnsubmit').html() == 'Update') {
        Dml_Indicator = 'U'
        Dml_Indicator_P = 'UP'
    }
    else {

        Dml_Indicator = 'I'
        Dml_Indicator_P = 'IP'
    }
    var service_id = ($("#master_service_id").val() == '') ? 0 : $("#master_service_id").val();
    var base_amount_type = ($("#base_amount_type").val() == '') ? 0 : $("#base_amount_type").val();
    var range_min = ($("#range_min").val() == '') ? 0 : $("#range_min").val();
    var range_max = ($("#range_max").val() == '') ? 0 : $("#range_max").val();
    var base_amount_value = ($("#base_amount_value").val() == '') ? 0 : $("#base_amount_value").val();
    var tex_percentage = ($("#tax_percentage").val() == '') ? 0 : $("#tax_percentage").val();
    //var mobile_discount_applicable = ($("#mobile_discount_applicable").val() == '') ? 2 : $("#mobile_discount_applicable").val();
    //var mobile_discount_amount = ($("#mobile_discount_amount").val() == '') ? 0 : $("#mobile_discount_amount").val();
    //var service_level_discount_allowed = ($("#service_level_discount_allowed").val() == '') ? 2 : $("#service_level_discount_allowed").val();
    //var loayalty_earning_allowed = ($("#loayalty_earning_allowed").val() == '') ? 2 : $("#loayalty_earning_allowed").val();
    //var doctor_name_required = ($("#doctor_name_required").val() == '') ? 2 : $("#doctor_name_required").val();
    //var is_loyalty_scheme = ($("#is_loyalty_scheme").val() == '') ? 2 : $("#is_loyalty_scheme").val();
    var is_coupons_reverse = ($('#refund_scenario').val() == '' || $('#refund_scenario').val() == null) ? 2 : $('#refund_scenario').val();
    // var doctor_name_required = ($("#doctor_name_required").val() == '') ? 0 : $("#doctor_name_required").val();
    var Ppatient_per_time = ($('#txtPatientTime').val() == '') ? 0 : $('#txtPatientTime').val();
    //is_internal = ($('#isexternal').val() == '') ? 2 : $('#isexternal').val();
    var distance_fee = ($('#distance_fee').val() == '') ? 2 : $('#distance_fee').val();
    //  var ward_id = ($('#ward_id').val() == '') ? 0 : $('#ward_id').val();
    Pconsulting_type = ($('#consulting_type').val() == '' || $('#consulting_type').val() == null) ? 0 : $('#consulting_type').val();
    var consultation_type = ($('#consultation_type').val() == '' || $('#consultation_type').val() == null) ? 0 : $('#consultation_type').val();
    var doctorid = ($('#SelDoctor').val() == null) ? 0 : $('#SelDoctor').val();
    var doctor_id = ($('#SelDoctor option:selected').data('id') == '') ? 0 : $('#SelDoctor option:selected').data('id');
    is_workorder = (is_workorder == null || is_workorder == 0 || is_workorder == '') ? 2 : is_workorder;
    is_lab = (is_lab == null || is_lab == 0 || is_lab == '') ? 2 : is_lab;
    Pmobile_enabled = ($('#mobile_enabled').val() == '' || $('#mobile_enabled').val() == null) ? 0 : $('#mobile_enabled').val();
    is_doctor = ($('#is_doctor_enable').val() == '' || $('#is_doctor_enable').val() == null) ? 0 : $('#is_doctor_enable').val();
    //appointmentbooking = (appointmentbooking == null || appointmentbooking == 0 || appointmentbooking == '') ? 2 : appointmentbooking;
    //is_fasting=($('#is_fasting').val()=='')?2:$('#is_fasting').val();
    if ($('#service_type').val() == 3) {
        Ppatient_per_time = Math.floor(parseFloat(Ppatient_per_time) * 60);
    }

    var non_billable
    if ($("#non_billable").prop("checked")) {
        non_billable = 1;
    } else {
        non_billable = 0
    }

    var hnpackage = ''
    if ($('#HPackage_id').val() != '') {
        hnpackage = $('#HPackage_id').val()
    }
    else {
        hnpackage = 0
    }
    var Consunables_data = [];
    var tot_len = $('#tbl_consumables>tbody>tr').length;
    for (var i = 1; i <= tot_len; i++) {
        var con_lab = {};
        con_lab.Id = 0,
         //con_lab.Id = $('#con_id_' + i).html(),
        con_lab.ItemName = $('#con_name_' + i).html(),    
        con_lab.ItemId = $('#item_id_' + i).html(),
        con_lab.Quantity = $('#con_quan_' + i).html(),
        con_lab.CreatedBy = $('#hiddenUser_id' + i).html(),
        //con_lab.Hospitalid = $('#HospitalId' + i).html(),
        //con_lab.Branchid = $('#HospitalBranchID' + i).html(0),
        //con_lab.ServiceId = data1[0].master_service_id
        Consunables_data.push(con_lab);

    }
    var servicevalues = {

        P_Dml_Indicator: Dml_Indicator
        //, branch_id: $("#branch_id").val() medway all branch concept
        , branch_id: "0"
      , master_service_id: service_id
      , master_category_id: $("#master_category_id").val()
      , master_sub_category_id: $("#master_sub_category_id").val()
      , department_id: $("#department_id").val()
      , sub_department_id: $("#sub_department_id").val()
      , service_name: $("#service_name").val()
      , service_type: $("#service_type").val()
      , remarks: $("#service_description").val()
      , base_amount_type: base_amount_type
      , range_min: range_min
      , range_max: range_max
      , base_amount_value: base_amount_value
      , is_workorder: is_workorder
      , is_lab: is_lab
      , is_doctor: $("#is_doctor_enable").val()
      , mobile_enabled: ($("#mobile_enabled").val() == '' || $("#mobile_enabled").val() == null) ? 2 : $("#mobile_enabled").val()
        // , mobile_discount_applicable: mobile_discount_applicable
        //, mobile_discount_type: ($("#mobile_discount_type").val() == '') ? 0 : $("#mobile_discount_type").val()
        // , mobile_discount_amount: mobile_discount_amount
        //, service_level_discount_allowed: service_level_discount_allowed
        // , loayalty_earning_allowed: loayalty_earning_allowed
        //  , doctor_name_required: doctor_name_required
      , is_package: appointmentbooking
      , is_loyalty_scheme: Pstatus
      , service_imagepath: $('#Hdn_service_image').val()
      , is_coupons_reverse: is_coupons_reverse
      , is_consulting: Pis_consulting
      , consulting_type: Pconsulting_type
      , per_patient_time: Ppatient_per_time
      , is_internal: is_internal
        // , ward_id: ward_id
      , doctorid: doctorid
      , consultation_type: consultation_type
      , doctor_id: doctor_id
        //, distance_fee: distance_fee
      , is_surgery: Pis_surgery
      , is_description: is_description
      , is_activate: is_activate
        , external_lab: external_lab
        , is_tax: is_tax
            , tax_percentage: tex_percentage
      , tube_container: ($('#loadctubecontainer').val() == '' || $('#loadctubecontainer').val() == null ? 0 : $('#loadctubecontainer').val())
     , method_name: $('#method_name').val()
        // , duration: $('#duration').val()
        , short_name: short_name
        //, cg_hms: cg_hms
      , display_name: display_name
        //, chat_valid_days: $('#txtNoofChatValidDays').val()
        , PrimaryCostCentreid: $('#HSelprimarycost').val()
        , SecondaryCostCentreid: $('#HSelsecondarycost').val()
         , Ledgerid: $('#HSelLedge').val()
        , templateinfo: $('#templateinfo').summernote('code')
        , PackageId: hnpackage
        , nonbillable: non_billable
        , is_consumable: is_consumables
        , StoreId: store_id
        , itemlist: Consunables_data
        //, is_fasting: is_fasting
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        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") {

                    var data1 = data2.data;
                    $('#Hdmaster_service_id').val(data1[0].master_service_id)
                    if (data1[0].service_code == 'consulationalready') {
                        $('#shade_slot_submit').hide();
                        toastr.warning("The service Name and Base Amount Value Already Exist, Please Change the Base Amount Value");
                        return false;
                    }

                    else if (data1[0].service_code == 'consultation_type_already_exists') {
                        $('#shade_slot_submit').hide();
                        toastr.warning("Consultation Service already exists for this appointment mode");
                        return false;
                    }
                    else if (data1[0].service_code == 'already_used') {
                        $('#shade_slot_submit').hide();
                        toastr.warning("Service already used");
                        return false;
                    }
                    else if (data1[0].service_code == 'ward_charge_already_added') {
                        $('#shade_slot_submit').hide();
                        toastr.warning("Charges already created for this ward");
                        return false;
                    }
                    var schemeSevice = $("#service_name").val()
                    var schemebaseamount = $("#base_amount_value").val()
                    $('#lblServiceName').html(schemeSevice)
                    $('#lblBaseAmount').html(schemebaseamount);
                    debugger;
                    var ward_data = [];
                    if ($.trim((Pbase_amount_type)) == "5") {
                        var wardid_split = $('#ward_id').val();
                        for (var a = 0; a < wardid_split.length; a++) {
                            var ward_obj = {}
                            ward_obj.master_service_id = data1[0].master_service_id,
                            ward_obj.ward_id = wardid_split[a],
                               ward_obj.created_by = $('#hiddenUser_id').val();
                            ward_data.push(ward_obj);
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Billing/Service_Ward_Mapping',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(ward_data),
                            success: function (data) {

                            }
                        });
                    }
                    var lab_data = new Array();
                    //  if (is_internal == 2) {
                    var tot_len = $('#tbl_external_lab>tbody>tr').length;
                    if (tot_len > 0) {
                        for (var i = 1; i <= tot_len; i++) {
                            var ext_lab = {};
                            ext_lab.master_service_id = data1[0].master_service_id,
                            ext_lab.external_lab = $('#ex_lab_' + i).attr('data-id'),
                            ext_lab.base_amount_value = $('#ex_lab_amt_' + i).html(),
                            ext_lab.branch_id = $('#lab_' + i).attr('data-id'),
                            ext_lab.P_Dml_Indicator = Dml_Indicator
                            lab_data.push(ext_lab);

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

                            }
                        });
                    }
                    // }
                    var customers = new Array();
                    //  var tot_rowM = $.trim($('#testTableRowCount').val());
                    if ($.trim((is_lab)) == "1") {
                        var tot_rowM = $('#AddTestTable >tbody >tr').length;
                        if (tot_rowM > 0) {
                            var L = 0;
                            for (j = 1; j <= tot_rowM; j++) {
                                var customer = {};
                                var data = ($('#RefValue_' + j).html() == '') ? 0 : ($('#RefValue_' + j).html());
                                var tempElement = document.createElement('div');
                                tempElement.innerHTML = data;
                                var decodedData = tempElement.textContent || tempElement.innerText;

                                debugger;
                                customer.test_id = data1[0].master_service_id,
                                customer.parameter_name = $('#ParName_' + j).html(),
                                // customer.reference_value = ($('#RefValue_' + j).html() == '') ? 0 : $('#RefValue_' + j).html(),
                                customer.reference_value = decodedData,
                                customer.unit = $('#Unit_' + j).html(),
                                customer.parameter_instructions = $('#Instructions_' + j).html(),
                                customer.Dml_Indicator = Dml_Indicator_P,
                                customer.sample_type = $('#SampleTypeval_' + j).html(),
                                //customer.tube_container = $('#tubecontainerid_' + j).html(),
                                customer.sample_id = $('#sampltypeid_' + j).html(),
                                customer.parameter_id = $('#paramerterid_' + j).html(),
                                customer.display_order = $('#display_order_' + j).html()
                                customer.form_id = $('#form_id_' + j).html()

                                //customer.method_name = $('#Method_' + j).html()
                                //customer.gender = $('#gender_' + j).attr('data-val'),
                                //customer.age_limit = $('#age_' + j).attr('data-val'),
                                //customer.min_value = ($('#min_' + j).html() == '-' ? 0 : $('#min_' + j).html()),
                                //customer.max_value = ($('#max_' + j).html() == '-' ? 0 : $('#max_' + j).html()),
                                //customer.result_type=$('#res_'+j).attr('data-val')
                                customers.push(customer);
                            }

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

                                }
                            });
                            //if (Dml_Indicator == 'U') {
                            //    $('#shade_slot_submit').hide();
                            //    toastr.success("Lab Updated Successfully ");
                            //}
                            //else if (Dml_Indicator == 'I') {
                            //    $('#shade_slot_submit').hide();
                            //    toastr.success("Lab Created Successfully ");
                            //}
                            //  location.reload();

                        }
                    }
                    var Consunables_data1 = [];
                    var tot_len = $('#tbl_consumables>tbody>tr').length;
                    if (tot_len > 0) {
                      
                        for (var i = 1; i <= tot_len; i++) {
                            var con_lab1 = {};
                            con_lab1.Dml_Indicator = 'I',
                            con_lab1.ItemName = $('#con_name_' + i).html(),
                            con_lab1.ItemCode = $('#con_hsn_' + i).html(),
                            con_lab1.ItemId = $('#item_id_' + i).html(),
                            con_lab1.Mrp = $('#con_mrp_' + i).html(),
                            con_lab1.Tax = $('#con_tax_' + i).html(),
                            con_lab1.Quantity = $('#con_quan_' + i).html(),
                            con_lab1.Createdby = $('#hiddenUser_id' + i).html(),
                            con_lab1.Hospitalid = $('#HospitalId' + i).html(),
                            con_lab1.Branchid = $('#HospitalBranchID' + i).html(0),
                            con_lab1.ServiceId = data1[0].master_service_id
                            Consunables_data1.push(con_lab1);
                        }
                        $.ajax({
                            async: true,
                            type: 'POST',
                            url: '/Billing/ServiceConsumables_Ins_upd_sel',
                            contentType: 'application/json; charset=UTF-8',
                            data: JSON.stringify(Consunables_data1),
                            success: function (data) {

                            }
                        });
                        //if (Dml_Indicator == 'U') {
                        //    toastr.success("Consumable Updated Successfully ");
                        //}
                        //else if (Dml_Indicator == 'I') {
                        //    toastr.success("Consumable Created Successfully ");

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

                    if (Dml_Indicator == 'U') {
                        toastr.success("Service Updated Successfully ");
                    }
                    else if (Dml_Indicator == 'I') {
                        toastr.success("Service Created Successfully ");
                    }

                    if ($('#Hdmaster_service_id').val() != '' || $('#btnsubmit').html() == 'Update') {
                        Servicenext(1);
                    }
                    else {
                        toastr.warning("Sorry, there is no service created.");
                    }
                    //location.reload();
                }
              
            }
        },
        error: function (data) {
            toastr.warning("Error Occured");
        }
    });
}
// service image upload
$('#servicedocuments').change(function () {
    serviceimageUpload();
});

function serviceimageUpload() {
    debugger;
    var uploadpath = $('#servicedocuments').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#servicedocuments").get(0);
        var files = fileUpload.files;
        if (files[0].size > 5e+6) {
            //alert("up to 5 MB per file!");
            toastr.warning('Upto 5 MB Per File!');
            return false;
        };
        var filePath = fileUpload.value;

        // Allowing file type
        var allowedExtensions =
                /(\.jpg|\.jpeg)$/i;

        if (!allowedExtensions.exec(filePath)) {
            toastr.warning('Invalid File Type, It should be JPG or JPEG');
            fileInput.value = '';
            return false;
        }
        $.when(checkimagedimensionvalidation(fileUpload.files[0], 512, 512)).
        done(function (Results) {
            if (Results == 'Success') {
                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: '/Billing/UploadPhotoFiles?branch_id=' + $('#branch_id').val() + '', //medway all branch concept
                    url: '/Billing/UploadPhotoFiles',
                    type: "POST",
                    contentType: false, // Not to set any content header
                    processData: false, // Not to process data
                    data: fileData,
                    success: function (result) {
                        console.log(result);
                        $.each(result, function (i, emp) {
                            $('#Hdn_service_image').val(emp);
                            $('#imagefile').val(emp);
                            var filepath = $('#hdnfilepath1').val();
                            var profilephoto = $('#Hdn_service_image').val();
                            var Doctor_Id = $('#myHiddenVar').val();
                            var d, n, drloimage;
                            d = new Date();
                            n = d.getTime();
                            //drinimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/' + $('#branch_id').val() + '/serviceimage/' + profilephoto + '?' + n; //medway all branch concept
                            drinimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/serviceimage/' + profilephoto + '?' + n;

                            var imageElement = '<img src="' + drinimage + '">';
                            $('.file_upload_image').html(imageElement);

                            $('#photolog').empty();
                            $('#photolog').append('<a href="' + drinimage + '" target="_blank" class="another-eye">View</a>');
                        });
                    }
                });
            }

            else {
                $('#Hdn_service_image').val('');
                $('#imagefile').val('');
                $('#photolog').empty();
            }
            //this code is executed when all ajax calls are done
        });
    }
}

//add lab test parameter table value
$('#Add_Test_record').click(function () {
    debugger;
    var ParName = $("#pname").val();
    var RefValue = $("#rvalue").val();
    var Unit = $("#unit").val();
    var SampleType = $("#sType").val();
    var tubecontainer = $('#loadctubecontainer').val();
    var parameter_id = $("#hdn_parameter_id").val();
    var SampleTypeval = $("#sType option:selected").html();
    var tubecontainerval = ($("#loadctubecontainer option:selected").val() == 0 ? '-' : $("#loadctubecontainer option:selected").text());
    var tubecontainerid = $("#loadctubecontainer option:selected").val();
    var refunitflag = $("#sType option:selected").data('id1');
    var method_name = $("#method_name").val();
    var display_order = $('#txt_dis_order').val();
    var form_id = $('#form_name').val();
    var form_name = $('#form_name option:selected').html();
    //var gender =($('#pgender').val()==0)?'-': $('#pgender option:selected').text();
    //var age_limit = ($('#age_limit').val() == 0) ? '-' : $('#age_limit option:selected').text();
    //var min_value = $('#minvalue').val();
    //var max_value = $('#maxvalue').val();
    //var result_type = $('#result_type').val();
    if (($('#lab_type').val()) == "") {
        $('#Plab_type').show();
        $('#Plab_type').fadeOut(8000);
        $('#Plab_type').html('Enter Lab Type');
        $('#lab_type').focus();
        return false;
    }

    if ($.trim((SampleType)) == "" || SampleType == 0) {
        $('#PsType').show();
        $('#PsType').fadeOut(8000);
        $('#PsType').html('Enter Sample Type');
        $('#sType').focus();
        return false;
    }

    var Instructions = $('#testNotes').val();

    if ($('#lab_type').val() == 1) {
        if ($.trim((ParName)) == "") {
            $('#PName').show();
            $('#PName').fadeOut(8000);
            $('#PName').html('Enter Parameter Name');
            $('#Name').focus();
            return false;
        }
    }
    else {
        if ($('#HFormbuilder_id').val() == 1) {
            if ($.trim((form_id)) == "0") {
                $('#Pform_name').show();
                $('#Pform_name').fadeOut(8000);
                $('#Pform_name').html('Select Form Name');
                $('#form_name').focus();
                return false;
            }
        }
        else {
            if ($.trim((ParName)) == "") {
                $('#PName').show();
                $('#PName').fadeOut(8000);
                $('#PName').html('Enter Parameter Name');
                $('#Name').focus();
                return false;
            }
        }
    }

    //if (result_type == '' || result_type==0) {
    //    $('#Presult_type').show();
    //    $('#Presult_type').fadeOut(8000);
    //    $('#Presult_type').html('Select Result Type');
    //    $('#result_type').focus();
    //    return false;
    //}
    //if (refunitflag == 1) {

    //    if ($.trim((RefValue)) == "") {
    //        $('#PrValue').show();
    //        $('#PrValue').fadeOut(8000);
    //        $('#PrValue').html('Enter Reference Value');
    //        $('#rValue').focus();
    //        return false;
    //    }
    //    if ($.trim((Unit)) == "") {
    //        $('#Punit').show();
    //        $('#Punit').fadeOut(8000);
    //        $('#Punit').html('Enter unit');
    //        $('#unit').focus();
    //        return false;
    //    }

    //}
    if ($('#lab_type').val() == 1) {
        if ($.trim((display_order)) == "") {
            $('#Ptxt_dis_order').show();
            $('#Ptxt_dis_order').fadeOut(8000);
            $('#Ptxt_dis_order').html('Enter Display Order');
            $('#txt_dis_order').focus();
            return false;
        }
    }

    var ikey = "0";
    var rowcount = $('#AddTestTable >tbody >tr').length;
    if (rowcount == 0) {
        var ikey = 1
    }
    else {

        var max = 0;

        $('.number').each(function () {

            var value = parseInt($(this).data('id'));

            max = (value > max) ? value : max;

        });
        var ikey = Number(max) + 1;
    }

    var reference_value = ''
    if ($('#rvalue').val() == '') {
        reference_value = '-'
    }
    else {
        reference_value = $('#rvalue').val()
    }
    var test = 0;
    $("#AddTestTable tbody tr").each(function () {
        var columndisplayorder = ($(this).find("td").eq(4).html() == '' ? 0 : $(this).find("td").eq(4).html())
        if (display_order == columndisplayorder) {
            test = 1;
        }
    });
    if (test == 1) {
        toastr.warning('Display Order already exist');
        $('#txt_dis_order').val('');
        return false;
    }

    //var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='"+$('#lab_type').val()+"'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='Method_"+ikey+"'>"+method_name+"</td><td id='res_"+ikey+"' data-val='"+$('#result_type').val()+"'>"+$('#result_type option:selected').text()+"</td><td id='gender_" + ikey + "' data-val=" + $('#pgender').val() + ">" + gender + "</td><td id='age_" + ikey + "' data-val=" + $('#age_limit').val() + ">" + age_limit + "</td><td id='RefValue_" + ikey + "'>" + RefValue + "</td><td id='min_" + ikey + "'>" + ((min_value == '') ? '-' : min_value) + "</td><td id='max_" + ikey + "'>" + ((max_value == '') ? '-' : max_value) + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    //var value = "< tr class='tr_input number' data-id='" + ikey + "' id='t_" + ikey + "'>< td id='SampleTypeval_" + ikey + "' data-val='" + $('#lab_type').val() + "'>" + SampleTypeval + "< td id='tubecontainerid_" + ikey + "' hidden>" + tubecontainerid + "< td id='tubecontainerval_" + ikey + "'>" + tubecontainerval + "< td id='ParName_" + ikey + "'>" + ParName + "< td id='Method_" + ikey + "'>" + method_name + "< td id='RefValue_" + ikey + "'>" + RefValue + "< td id='Unit_" + ikey + "'>" + Unit + "< td id='Instructions_" + ikey + "'>" + Instructions + "< td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "< td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "< td>< button class='edit btn btn-primaryuse btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'>< i class='fa fa-pencil' aria-hidden='true'> < button class='btn btn-danger btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'>< i class='fa fa-trash' aria-hidden='true'>";
    //var value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + $('#lab_type').val() + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + reference_value + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    var value = '';
    if ($('#lab_type').val() == 1) {
        $('#form_name_header').hide();
        $('#param_name_header').show();

        value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + $('#lab_type').val() + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + reference_value + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
    }
    else {
        if ($('#HFormbuilder_id').val() == 1) {

            $('#form_name_header').show();
            $('#param_name_header').hide();
            value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + $('#lab_type').val() + "'>" + SampleTypeval + "</td><td style='display:none' id='form_id_" + ikey + "'>" + form_id + "</td><td id='form_name_" + ikey + "'>" + form_name + "</td><td id='RefValue_" + ikey + "'>" + reference_value + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }
        else {
            $('#form_name_header').hide();
            $('#param_name_header').show();

            value = "<tr class='tr_input number' data-id='" + ikey + "'  id='t_" + ikey + "'><td id='SampleTypeval_" + ikey + "' data-val='" + $('#lab_type').val() + "'>" + SampleTypeval + "</td><td id='ParName_" + ikey + "'>" + ParName + "</td><td id='RefValue_" + ikey + "'>" + reference_value + "</td><td id='Unit_" + ikey + "'>" + Unit + "</td><td id=display_order_" + ikey + ">" + display_order + "</td><td id='Instructions_" + ikey + "'>" + Instructions + "</td><td hidden id='paramerterid_" + ikey + "'>" + parameter_id + "</td><td hidden id='sampltypeid_" + ikey + "'>" + SampleType + "</td><td><button class='edit btn btn-primaryuse  btn-sm btn-add' onclick='labedit(\"" + ikey + "\")'><i class='fa fa-pencil' aria-hidden='true'></i></button>&nbsp;<button class='btn btn-danger  btn-sm btn-add' onclick='labdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";
        }

    }


    $('#AddTestTable > tbody:last').append(value);
    $('#lab_type').attr('disabled', true);
    if ($('#lab_type').val() == 1) {
        $('#div_param_name').show()
        $('#div_form_name').hide()
    }
    else {
        if ($('#HFormbuilder_id').val() == 1) {
            $('#div_param_name').hide()
            $('#div_form_name').show()
            $('#form_name').val(0);
        }
        else {
            $('#div_param_name').show()
            $('#div_form_name').hide()
        }
    }
    //$('#pgender').val(0);
    //$('#age_limit').val(0);
    //$('#result_type').val(0);
    //$('#minvalue').val('');
    //$('#maxvalue').val('');
    $('#pname').val('');
    $('#rvalue').val('');
    $('#unit').val('');
    $('#sType').attr('disabled', true);
    //$('#loadctubecontainer').val(0);
    //$('#method_name').val('');
    $('#testNotes').val('');
    $(".select2-selection__rendered").empty();
    //$("#sType").select2("val", " ");
    //$("#loadctubecontainer").select2("val", " ");
    $('#hdn_parameter_id').val('');
    $('#txt_dis_order').val('');
});

// edit lab parameter

function labedit(val) {
    debugger;

    $('#Add_Test_record').hide();
    $('#Update_Test_record').show();
    $('#hdn_test_id').val(val);
    $('#rowid').val(val);

    var data = ($('#RefValue_' + val).html());
    var tempElement = document.createElement('div');
    tempElement.innerHTML = data;
    var decodedData = tempElement.textContent || tempElement.innerText;

    $('#lab_type').val($('#SampleTypeval_' + val).attr('data-val'));
    var sample = loadsampletype();
    $.when(sample)
   .then(function (data) {
       $("#sType").val($('#sampltypeid_' + val).html());
   })
    var tid = $.trim($('#tubecontainerid_' + val).html());
    //$('#loadctubecontainer').val($('#tubecontainerid_' + val).html());
    $('#pname').val($('#ParName_' + val).html());

    $('#form_name').val($('#form_id_' + val).html())
    //  $('#rvalue').val($('#RefValue_' + val).html());
    $('#rvalue').val(decodedData);
    $('#unit').val($('#Unit_' + val).html());
    //$('#method_name').val($('#Method_' + val).html());
    $('#hdn_parameter_id').val($('#paramerterid_' + val).html());
    $("#testNotes").val($('#Instructions_' + val).html());

    $('#txt_dis_order').val($('#display_order_' + val).html());
    //$('#pgender').val($('#gender_' + val).attr('data-val'));
    //$('#age_limit').val($('#age_' + val).attr('data-val'));
    //$('#result_type').val($("#res_" + val).attr('data-val'));
    //$('#minvalue').val($('#min_' + val).html());
    //$('#maxvalue').val($('#max_' + val).html());
    var ins = $('#Instructions_' + val).html();
    var master_service_id = $('#master_service_id').val();
    if (master_service_id != '') {
        $("#sType").attr('disabled', true);
        $('#lab_type').attr('disabled', true);
    }
    //else {
    //    $("#sType").attr('disabled',false);
    //    $('#lab_type').attr('disabled',false);
    //}
    //if (ins != '')
    //{
    //    $('#testNotesToggle')(val);
    //}

    var abc = '';



    // $("#sType").select2("val", val1)
    //var val1 = row_data_split[3].split(',');

    //let abcdata = row_data_split[5].split(',');
    //$("#sType").select2("val", [abcdata]);
    //$('#testNotes').val(row_data_split[4]);




}
// delete parameter
function labdelete(val) {
    debugger;
    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>", 'Are You Sure Do You Want Delete This Parameter?',
    {

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

        onShown: function (toast) {

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

                var paraid = $("#paramerterid_" + val + "").html();
                if (paraid != "") {

                    var servicevalues = {
                        P_Dml_Indicator: "DLP",
                        master_service_id: paraid

                    }
                    $.ajax({
                        async: true,
                        type: 'POST',
                        url: '/Billing/Service_Master_Ins_upd_sel',
                        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") {
                                    sessionStorage.removeItem(val);
                                    var data1 = data2.data;
                                    if (data1[0].status != 'deleted') {

                                        toastr.warning(data1[0].status);
                                        return false;
                                    }
                                    else {
                                        $('#t_' + val).remove();
                                        var a = $.trim($('#testTableRowCount').val());
                                        var a = (a) - (1);
                                        $('#testTableRowCount').val(a);
                                        toastr.success("Removed Successfully");
                                        if ($('#testAddTable_body tr').length == 0) {
                                            $("#sType").attr('disabled', false);
                                            $('#lab_type').attr('disabled', false);
                                        }
                                    }
                                }
                            }
                        }
                    });
                }

                else {
                    // sessionStorage.removeItem(val);
                    $('#t_' + val).remove();
                    var a = $.trim($('#testTableRowCount').val());
                    var a = (a) - (1);
                    $('#testTableRowCount').val(a);
                    toastr.success("Removed Successfully");
                    if ($('#testAddTable_body tr').length == 0) {
                        $("#sType").attr('disabled', false);
                        $('#lab_type').attr('disabled', false);
                    }

                }
            });
        }
    });
}
// update lab parameter

$('#Update_Test_record').click(function () {
    var table_id = $('#hdn_test_id').val();
    $("#sType").attr('disabled', false);
    var ParName = $("#pname").val();
    var RefValue = $("#rvalue").val();
    var Unit = $("#unit").val();
    var SampleType = $("#sType").val();
    var Instructions = $('#testNotes').val();
    var parameter_id = $("#hdn_parameter_id").val();
    var SampleTypeval = $("#sType option:selected").html();
    var display_order = $('#txt_dis_order').val()
    //var tubecontainer =($("#loadctubecontainer option:selected").val()==0?'-': $.trim($("#loadctubecontainer option:selected").text()));
    //var tubecontainerid = $.trim($("#loadctubecontainer option:selected").val());
    var refunitflag = $("#sType option:selected").data('id1');
    //var gender = ($('#pgender').val() == 0) ? '-' : $('#pgender option:selected').text();
    //var age_limit = ($('#age_limit').val() == 0) ? '-' : $('#age_limit option:selected').text();
    //var min_value = $('#minvalue').val();
    //var max_value = $('#maxvalue').val();
    //var result_type = $('#result_type').val();
    //var SampleTypeval = $("#sType option:selected").data('id');

    var form_id = $('#form_name').val();
    var form_name = $('#form_name option:selected').html();

    if ($.trim((SampleType)) == "") {
        $('#PsType').show();
        $('#PsType').fadeOut(8000);
        $('#PsType').html('Select Sample Type');
        $('#sType').focus();
        return false;
    }
    //if ($.trim((ParName)) == "") {
    //    $('#PName').show();
    //    $('#PName').fadeOut(8000);
    //    $('#PName').html('Enter Parameter Name');
    //    $('#Name').focus();
    //    return false;
    //}

    if ($('#lab_type').val() == 1) {
        if ($.trim((ParName)) == "") {
            $('#PName').show();
            $('#PName').fadeOut(8000);
            $('#PName').html('Enter Parameter Name');
            $('#Name').focus();
            return false;
        }
    }
    else {
        if ($('#HFormbuilder_id').val() == 1) {
            if ($.trim((form_id)) == "0") {
                $('#Pform_name').show();
                $('#Pform_name').fadeOut(8000);
                $('#Pform_name').html('Select Form Name');
                $('#form_name').focus();
                return false;
            }
        }
        else {
            if ($.trim((ParName)) == "") {
                $('#PName').show();
                $('#PName').fadeOut(8000);
                $('#PName').html('Enter Parameter Name');
                $('#Name').focus();
                return false;
            }
        }
    }
    //if (result_type == '' || result_type == 0) {
    //    $('#Presult_type').show();
    //    $('#Presult_type').fadeOut(8000);
    //    $('#Presult_type').html('Select Result Type');
    //    $('#result_type').focus();
    //    return false;
    //}
    //if (refunitflag == 1) {
    //    if ($.trim((RefValue)) == "") {
    //        $('#PrValue').show();
    //        $('#PrValue').fadeOut(8000);
    //        $('#PrValue').html('Enter Reference Value');
    //        $('#rValue').focus();
    //        return false;
    //    }
    //    if ($.trim((Unit)) == "") {
    //        $('#Punit').show();
    //        $('#Punit').fadeOut(8000);
    //        $('#Punit').html('Enter unit');
    //        $('#unit').focus();
    //        return false;
    //    }
    //}
    if ($('#lab_type').val() == 1) {
        if ($.trim((display_order)) == "") {
            $('#Ptxt_dis_order').show();
            $('#Ptxt_dis_order').fadeOut(8000);
            $('#Ptxt_dis_order').html('Enter Display Order');
            $('#txt_dis_order').focus();
            return false;
        }
    }

    $('#Add_Test_record').show();
    $('#Update_Test_record').hide();
    var rowid = $('#rowid').val();

    debugger;
    //var test1 = 0;
    //$("#AddTestTable tbody tr").each(function () {

    //        var columndisplayorder = ($(this).find("td").eq(4).html())
    //    if (display_order == columndisplayorder) {
    //        test1 = 1;
    //    }
    //});
    //if (test1 == 1) {
    //    toastr.warning('Display Order already exist');
    //    $('#txt_dis_order').val('');
    //    return false;
    //}   

    $('#lab_type').attr('disabled', true);
    $('#SampleTypeval_' + rowid).attr('data-val', $('#lab_type').val());
    $('#ParName_' + rowid).html(ParName);
    $('#RefValue_' + rowid).html(RefValue);
    $('#Unit_' + rowid).html(Unit);
    $('#sampltypeid_' + rowid).html(SampleType);
    $('#SampleTypeval_' + rowid).html(SampleTypeval);
    //$('#tubecontainerval_' + rowid).html(tubecontainer);
    //$('#tubecontainerid_' + rowid).html(tubecontainerid);
    $('#paramerterid_' + rowid).html(parameter_id);
    $('#Instructions_' + rowid).html(Instructions);
    $('#display_order_' + rowid).html($('#txt_dis_order').val());

    $('#form_id_' + rowid).html(form_id);
    $('#form_name_' + rowid).html(form_name);
    //$('#Method_' + rowid).html($('#method_name').val());
    //$('#gender_' + rowid).html(gender);
    //$('#gender_' + rowid).attr('data-val', $('#pgender').val());
    //$('#age_' + rowid).attr('data-val', $('#age_limit').val());
    //$('#age_' + rowid).html(age_limit);
    //$('#min_' + rowid).html(min_value);
    //$('#max_' + rowid).html(max_value);
    //$('#res_' + rowid).attr('data-val', result_type);
    //$('#res_' + rowid).html($('#result_type option:selected').text());

    //$('#lab_type').val('');
    //$('#result_type').val(0);
    //$('#pgender').val(0);
    //$('#age_limit').val(0);
    //$('#minvalue').val('');
    //$('#maxvalue').val('');
    $('#pname').val('');
    if ($('#lab_type').val() == 1) {
        $('#div_param_name').show()
        $('#div_form_name').hide()
    }
    else {
        if ($('#HFormbuilder_id').val() == 1) {
            $('#div_param_name').hide()
            $('#div_form_name').show()
            $('#form_name').val(0);
        }
        else {
            $('#div_param_name').show()
            $('#div_form_name').hide()
        }
    }

    $('#rvalue').val('');
    $('#unit').val('');
    $('#txt_dis_order').val('');
    //$('#loadctubecontainer').val(0);
    $('#testNotes').val('');

    //$('#method_name').val('');
    $("#sType").select2("val", " ");
    $('#sType').attr('disabled', false);
    $("#loadctubecontainer").select2("val", " ");
    $('#hdn_parameter_id').val('');

});

//Load Ward No when base amount type -->Daywise
function WardNo(branch_id, wardid) {
    debugger;
    var Warddata = {
        Dml_Indicator: "WNS",
        branchid: branch_id
    }

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

            }
            else {

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

                    var WardNo;

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

                        WardNo = WardNo + '<option value="' + emp.wardid + '">' + emp.ward_id + "/" + emp.ward_name + '</option>';

                    });
                    $('#ward_id').append(default_opt + WardNo);
                    if (wardid != 0) {
                        $('#divward_id').show();
                        wardid = wardid.split(',').map(item => item.trim()).join(',');
                        $('#ward_id').val(wardid.split(',')).change();
                    }
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

$('#consulting_type').change(function () {
    debugger;
    var consulting_type = $('#consulting_type').val();
    $('#divChatValidDays').hide();
    if (consulting_type == 1) {
        $('#payafter').removeClass('hidden');
        $('#postpaid').removeClass('hidden');

    }
    else if (consulting_type == 4) {
        $('#payafter').addClass('hidden');
        $('#postpaid').addClass('hidden');
        $('#divChatValidDays').show();
    }
    else {
        $('#payafter').addClass('hidden');
        $('#postpaid').removeClass('hidden');

    }
})
//service type change function
$('#service_type').change(function () {
    debugger;
    var is_internal = $('#is_internal').val();
    var base_amount_type = $('#base_amount_type').val();
    if ($('#service_type').val() == 3) {
        $('#p_time').html(' (in hours)');
    }
    else {
        $('#p_time').html(' (in mins)');
        $('#txtPatientTime').val(00);
    }
    if ((($('#service_type').val() == 1 || $('#service_type').val() == 2) && is_internal == 2) || $('input[name="typeofservice"]:checked').val() == 1 || (($('#service_type').val() == 1 || $('#service_type').val() == 2) && $('#base_amount_type').val() == 4) || $('input[name="typeofservice"]:checked').val() == 3) {
        mobile_clear();
        $('#mobile_enableddiv').addClass('hidden');
    }
    else {
        //if (base_amount_type != 3 && base_amount_type != 1) {
        //$('#mobile_options').removeClass('hidden');
        $('#mobile_enableddiv').removeClass('hidden');
        //$('#mobile_enabled').val(2);
        //$('a[data-toggle=mobile_enabled][data-title="1"]').removeClass('active');
        //$('a[data-toggle=mobile_enabled][data-title="2"]').removeClass('active');

        //$('a[data-toggle=mobile_enabled][data-title="1"]').addClass('not-active');
        //$('a[data-toggle=mobile_enabled][data-title="2"]').addClass('not-active');
        //}
    }
    if ($('#service_type').val() == 3) {
        if ($('#base_amount_type').val() == 4 || $('#base_amount_type').val() == 5) {
            $('#base_amount_type').val('').change()
        }
        $("#base_amount_type option[value='4']").prop('disabled', true);
        $("#base_amount_type option[value='5']").prop('disabled', true);

    }
    else if ($('#service_type').val() == 2) {
        if ($('#base_amount_type').val() == 5) {
            $('#base_amount_type').val('').change()
        }
        $("#base_amount_type option[value='5']").prop('disabled', true);
        $("#base_amount_type option[value='4']").prop('disabled', false);

    }
    else {
        $("#base_amount_type option[value='4']").prop('disabled', false);
        $("#base_amount_type option[value='5']").prop('disabled', false);

    }
})

//Base amount value change function for range based service
$('#base_amount_value').change(function () {
    debugger;
    if ($('#base_amount_type').val() == 3) {
        var range_min = $('#range_min').val();
        var range_max = $('#range_max').val();
        var base_value = $('#base_amount_value').val();
        if ($.trim((range_min)) == "") {
            $('#Prange_min').show();
            $('#Prange_min').fadeOut(8000);
            $('#Prange_min').html('Enter Range Min');
            $('#base_amount_value').val('');
            //$('#range_min')[0].scrollIntoView(true);
            return false;
        }
        if ($.trim((range_max)) == "") {
            $('#Prange_max').show();
            $('#Prange_max').fadeOut(8000);
            $('#Prange_max').html('Enter Range Max');
            $('#base_amount_value').val('');
            //$('#range_max')[0].scrollIntoView(true);
            return false;
        }
        else {
            if (parseFloat(base_value) >= parseFloat(range_min) && parseFloat(base_value) <= parseFloat(range_max)) {

            }
            else {
                $('#Pbase_amount_value').show();
                $('#Pbase_amount_value').fadeOut(8000);
                $('#Pbase_amount_value').html('Enter amount  between ' + range_min + ' and ' + range_max + ' ');
                //$('#base_amount_value')[0].scrollIntoView(true);
                $('#base_amount_value').val('');
                return false;
            }

        }
    }

})

//
//$('#sType').change(function () {
//    var refcheck = $("#sType option:selected").data('id1');
//    if(refcheck==0)
//    {
//        $('.req').hide();
//    }
//    else {
//        $('.req').show();
//    }
//})

//load Age limit
function loadAge_limit() {
    var data = {
        P_Dml_Indicator: 'AL'
    }
    $.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") {
                    $('#age_limit').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.age_limit_id + " data-min=" + emp.min_value + " data-max=" + emp.max_value + ">" + emp.min_value + "-" + emp.max_value + "</option>"
                    })
                    $('#age_limit').append(default_option + option);
                }
            }
        }
    })
}

//Activate from now 
$('#is_activate').on('change', function () {
    this.value = this.checked ? 1 : 2;

}).change();
//load external lab --multiselect
function loadExternal(val, is_lab, is_appointment) {
    debugger
    //var branch_id = 0;
    //if (val == 0) {
    //    //branch_id = ($('#branch_id').val() == '' ? 0 : $('#branch_id').val()) //Medway all branch concept
    //    branch_id = 0
    //}
    //else {
    //    branch_id = val;
    //} // one master concept
    //if (is_lab == 0 && is_appointment == 0) {
    //    is_lab = ($('#isexternal').val() == '' ? true : $('#isexternal').val())
    //    is_appointment = ($('#typeofserviceapporder').val() == '' ? 2 : $('#typeofserviceapporder').val());
    //}
    var external_lab = 0;
    if (is_lab != '' || is_lab == 0) {
        debugger;

        $('#duration_div').show();
        external_lab = '1,3';
    }
    else {
        $('#duration_div').hide();
    }
    if (is_appointment == 1 && is_lab == 2) {
        $('#duration_div').hide();
        external_lab = '2,3';
    }

    var data = {
        P_Dml_Indicator: 'EL',
        // branch_id: branch_id,//one master concept
        external_lab: external_lab
    }
    return $.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;
            $('#external_lab').empty();
            var data2 = JSON.parse(data);

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

            }
            else {

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

                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.labtranid + " data-id=" + emp.branchid + ">" + emp.lab_name + "</option>"
                    })
                    $('#external_lab').append(default_option + option);
                }
            }
        }
    })
}
// lab/non-lab change function
$('#lab_type').change(function () {
    debugger;
    if ($('lab_type').val() != '') {
        loadsampletype();
    }

    if ($('#lab_type').val() == '0') {
        if ($('#HFormbuilder_id').val() == 1) {
            load_form_names()
            $('#div_param_name').hide();
            $('#div_form_name').show();

            $('#rvalue').attr('disabled', true)
            $('#unit').attr('disabled', true)
            $('#txt_dis_order').attr('disabled', true)
            $('#testNotes').attr('disabled', true)
        }
        else {
            $('#form_name').empty();
            $('#div_param_name').show();
            $('#div_form_name').hide();

            $('#rvalue').attr('disabled', false)
            $('#unit').attr('disabled', false)
            $('#txt_dis_order').attr('disabled', false)
            $('#testNotes').attr('disabled', false)
        }
    }
    else {
        $('#form_name').empty();
        $('#div_param_name').show();
        $('#div_form_name').hide();

        $('#rvalue').attr('disabled', false)
        $('#unit').attr('disabled', false)
        $('#txt_dis_order').attr('disabled', false)
        $('#testNotes').attr('disabled', false)
    }
})

$('#typeofservicelab').change(function () {
    debugger;
    if ($('#typeofservicelab').prop('checked')) {
        $('#servicelab').show();
    }
    else {
        $('#servicelab').hide();
    }
    $('#form_name').empty();
    $('#Update_Test_record').hide();
})

function load_form_names() {
    debugger;

    var data = {
        P_Dml_Indicator: 'SFN'
    }
    $.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 {
                $('#form_name').empty();
                if (data2.msg == "Success") {
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.Formid + " >" + emp.Form_Name + "</option>"
                    })
                    $('#form_name').append(default_option + option);
                }
                else {
                    console.log(data2);
                }
            }
        }
    })
}

$('#tax_applicable').change(function () {
    debugger;
    $('#tax_percentage').val('')
    if ($('#tax_applicable').val() == 1) {
        $('#taxpercentage_div').removeClass('hidden')
    }
    else {
        $('#taxpercentage_div').addClass('hidden')
    }
});

$("#tax_percentage").on('keyup', function () {
    var tax_perc = $(this).val();
    if (tax_perc > 100) {
        toastr.warning('Please enter a value less than 100');
        $(this).val('');
    }
});

//external lab edit check

$('#external_lab').on('select2:unselect', function (e) {
    debugger;
    var data = e.params.data.id;
    if ($('#master_service_id').val() != '') {
        external_lab_chk(data);
    }
    //var arr = $('#external_lab').val();


});


//Mobile discount Applicable on change
$('#mobile_discount_applicable').change(function () {
    var value = $('#mobile_discount_applicable').val();
    if (value == 1) {
        $('.div_dis_applicable').removeClass('hidden');
    }
    else {
        $('.div_dis_applicable').addClass('hidden');
        $('#mobile_discount_amount').val('');
        $('#mobile_discount_type').val(0);
    }
})
// discount type change function
$('#mobile_discount_type').change(function () {
    $('#mobile_discount_amount').val('');
})
// discount-->percentange discount restriction -->less than 100
$('#mobile_discount_amount').keyup(function () {
    if ($('#mobile_discount_type').val() == 0) {
        $('#Pmobile_discount_amount').show();
        $('#Pmobile_discount_amount').fadeOut(8000);
        $('#Pmobile_discount_amount').html('Please Select Mobile Discount Type');
        $('#mobile_discount_amount').focus();
        $('#mobile_discount_type').focus();
        $('#mobile_discount_amount').val('');
    }
    if ($('#mobile_discount_type').val() == 1) {
        sixcomotwo(this.id);
        two_zero_validation(this);
        if ($.trim($('#mobile_discount_amount').val()) > 100 || $.trim($('#mobile_discount_amount').val()) < 0) {
            $('#Pmobile_discount_amount').show();
            $('#Pmobile_discount_amount').fadeOut(8000);
            $('#Pmobile_discount_amount').html('Enter Discount less than 100');
            $('#mobile_discount_amount').focus();
            $('#mobile_discount_amount').val('');
        }
    }
    else {
        numeric_only(this.id);
        first_zero_validation(this);
        if (parseFloat($(this).val()) > parseFloat($('#base_amount_value').val())) {
            $('#Pmobile_discount_amount').show();
            $('#Pmobile_discount_amount').fadeOut(8000);
            $('#Pmobile_discount_amount').html('Enter Discount Amount less than Service amount');
            $('#mobile_discount_amount').focus();
            $('#mobile_discount_amount').val('');
        }
    }
})
$('#mobile_discount_amount').on('input', function () {
    if ($('#mobile_discount_type').val() == 1) {
        validate(this);
    }
})
//Mobile clear
function mobile_clear() {
    $('.mob_div').addClass('hidden');
    $('#mobile_enabled').val(2);
    $('a[data-toggle=mobile_enabled][data-title="1"]').removeClass('active');
    $('a[data-toggle=mobile_enabled][data-title="2"]').removeClass('active');

    $('a[data-toggle=mobile_enabled][data-title="1"]').addClass('not-active');
    $('a[data-toggle=mobile_enabled][data-title="2"]').addClass('not-active');
    $('#imagefile').val('');
    $('#photolog').empty();
    $('#Hdn_service_image').val('');
    $('#servicedocuments').val('');
    $('#distance_fee').val('');
    $('a[data-toggle=distance_fee][data-title="2"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=distance_fee][data-title="1"]').removeClass('active').addClass('not-active');
    $('#mobile_discount_applicable').val('');
    $('a[data-toggle=mobile_discount_applicable][data-title="2"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=mobile_discount_applicable][data-title="1"]').removeClass('active').addClass('not-active');
    $('.div_dis_applicable').addClass('hidden');
    $('#mobile_discount_type').val(0);
    $('#mobile_discount_amount').val('');
}
//External lab add
$('#add_lab').click(function () {
    debugger
    var base_amount_value = (($('#base_amount_value').val() == '') ? 0 : $('#base_amount_value').val());
    var external_amount = $('#external_amount').val();
    if ($('#external_lab').val() == "" || $('#external_lab').val() == 0) {
        $('#Pexternal_lab').show();
        $('#Pexternal_lab').fadeOut(8000);
        $('#Pexternal_lab').html('Please Select The External lab');
        $('#Pexternal_lab').focus();
        $('#external_lab').val('');
        return false;
    }
    if ($('#external_amount').val() == "" || $('#external_amount').val() == 0) {
        $('#Pexternal_amount').show();
        $('#Pexternal_amount').fadeOut(8000);
        $('#Pexternal_amount').html('Please enter the amount');
        $('#external_amount').focus();
        $('#external_amount').val('');
        return false;
    }


    else {
        if ($('#tbl_external_lab tbody').length > 0) {
            var labid = $('#external_lab').val();
            var arr = [];
            for (var i = 1; i <= $('#tbl_external_lab>tbody>tr').length; i++) {
                arr.push($('#ex_lab_' + i).attr('data-id') + '_' + $('#lab_' + i).attr('data-id'));
            }
            var combinedkey = labid + '_' + $('#external_lab option:selected').attr('data-id')
            if ($.inArray(combinedkey, arr) != -1) {
                $('#Pexternal_lab').show();
                $('#Pexternal_lab').fadeOut(8000);
                $('#Pexternal_lab').html('Selected Already');
                $('#Pexternal_lab').focus();
                $('#external_lab').val(0);
                return false;
            }
        }
        var c = $('#tbl_external_lab>tbody>tr').length
        //for (var i = 0; i < $('#tbl_external_lab>tbody>tr').length; i++) {
        var trow = '<tr id=lab_' + (c + 1) + ' data-id=' + $('#external_lab option:selected').attr('data-id') + '><td id=ex_lab_' + (c + 1) + ' data-id=' + $('#external_lab option:selected').val() + '>' + $('#external_lab option:selected').text() + '<td id=ex_lab_amt_' + (c + 1) + '>' + $('#external_amount').val() + '<td><span class="btn deleteicon-btn btn-xs" onclick=external_lab_chk(' + (c + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span></td></tr>'
        $("#tbl_external_lab tbody:last").append(trow);
        //    c = c + 1;
        //}
        $('#external_lab').val(0);
        $('#external_amount').val('');

    }
})
//External lab delete 
function external_lab_chk(id, flag) {
    debugger;
    if ($('#master_service_id').val() == '') {
        $('#lab_' + id).remove();
    }
    else {
        var status = "";
        if (flag == 0) {
            status = "Are You Sure, You Want to Delete the Lab?";
        }
        else if (flag == 2) {
            status = "Are You Sure, You Want to In-Activate the Lab?";
        }
        else if (flag == 1) {

            status = "Are You Sure,You Want to Activate the Lab?";
        }
        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 () {
                          var data = {
                              P_Dml_Indicator: 'ELC',
                              is_workorder: $('#ex_lab_' + id).attr('data-id'),
                              master_service_id: $('#master_service_id').val(),
                              status: flag,
                              branch_id: $('#lab_' + id).attr('data-id')
                          }
                          return $.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[0];
                                          var tr = ''
                                          if (data1.status == 'success') {
                                              if (flag == 0) {
                                                  $('#lab_' + id).remove();
                                              }
                                              else if (flag == 2) {
                                                  $('#external_action_' + id).empty();
                                                  tr = '<span class="btn deleteicon-btn btn-xs" onclick=external_lab_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue  btn-xs" title="Make Active" onclick=external_lab_chk(' + (id) + ',1) ><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></span>'
                                                  $('#external_action_' + id).append(tr);
                                              }
                                              else {
                                                  $('#external_action_' + id).empty();
                                                  tr = '<span class="btn deleteicon-btn btn-xs" onclick=external_lab_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn  btn-blue  btn-xs" title="Make Inactive" onclick=external_lab_chk(' + (id) + ',2) ><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></span>'
                                                  $('#external_action_' + id).append(tr);
                                              }
                                          }
                                          else {
                                              toastr.warning('User Mapped already');
                                              //var arr = $('#external_lab').val();
                                              //arr.push(id);
                                              //$('#external_lab').val(arr).change();
                                          }

                                      }
                                  }
                              }
                          })
                      })
                  }
              })

    }
}
//External amount onchange
$('#external_amount').on('keyup',function () {
    var base_amount_value = (($('#base_amount_value').val() == '') ? 0 : $('#base_amount_value').val());
    var external_amount = $('#external_amount').val();
    if (parseFloat(external_amount) > parseFloat(base_amount_value)) {
        $('#Pexternal_amount').show();
        $('#Pexternal_amount').fadeOut(8000);
        $('#Pexternal_amount').html('Please enter the amount less than base amount');
        $('#external_amount').focus();
        $('#external_amount').val('');
        return false;
    }

})
//external_lab clear function
function clear_external() {
    $('#external_lab').val(0);
    $('#external_amount').val('');
    $('#tbl_external_lab tbody').empty();
}

//Copy Service to Other Branch Concept started

//Loading branches ,category,ward,department,tube container
function servicecopy(e, master_service_id) {
    $('#HCmaster_service_id').val(master_service_id);
    var data = {
        P_Dml_Indicator: 'CSL',
        master_service_id: master_service_id,
        hospital_id: $('#HospitalId').val()
    }
    $.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") {
                    $('#tbl_service_copy tbody').empty();
                    var trow = '', btndisable = '', btndisable2 = '', btndisable3 = '';
                    $('#cpy_ser_name').html(data2.data[0].service_name);
                    $('#cpy_ser_type').html(data2.data[0].service_type_name);
                    $('#cpy_ser_btype').html(data2.data[0].base_type_name);
                    $('#cpy_ser_amt').html(data2.data[0].base_amount);
                    $('#cpy_ser_wtype').html(data2.data[0].work_type);
                    $.each(data2.data, function (i, emp) {
                        $('#HCbase_amount_type').val(emp.base_amount_type);
                        $('#HCisworkorder').val(emp.is_workorder);
                        $('#HCislab').val(emp.is_lab);
                        if (emp.base_amount_type != '5') {
                            btndisable = 'style="display:none;"';
                            $('#th_ward').hide();
                        }
                        else {
                            $('#th_ward').show();
                        }
                        if (emp.is_lab != '1') {
                            btndisable2 = 'style="display:none;"';
                            $('#th_tube').hide();
                        }
                        else {
                            $('#th_tube').show();
                        }
                        if (emp.is_workorder == '2' && emp.base_amount_type != '5') {
                            $('#th_doc_name').show();
                        }
                        else {
                            btndisable3 = 'style="display:none;"';
                            $('#th_doc_name').hide();
                        }
                        trow = trow + '<tr id=cop_ser_' + i + '><td id=cop_ser_bch_' + i + ' data-id=' + emp.hospital_branch_id + '>' + emp.branch_name + '</td><td id=cop_ser_cate_' + i + '><select name="cars" id="sel_cop_cate_' + i + '" class="form-control" onchange=copy_subcat_load("sel_cop_cate_' + i + '",' + i + ')></select><p id="Psel_cop_cate_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_subcate_' + i + '><select name="cars" id="sel_cop_subcate_' + i + '" class="form-control"></select><p id="Psel_cop_subcate_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_dep_' + i + ' onchange=copy_subdep_load("sel_cop_dep_' + i + '",' + i + ')><select name="cars" id="sel_cop_dep_' + i + '" class="form-control"></select><p id="Psel_cop_dep_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_subdep_' + i + '><select name="cars" id="sel_cop_subdep_' + i + '" class="form-control" onchange=load_cop_doc("sel_cop_subdep_' + i + '",' + i + ');></select><p id="Psel_cop_subdep_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_ward_' + i + ' ' + btndisable + '><select name="cars" id="sel_cop_ward_' + i + '" class="form-control"></select><p id="Psel_cop_ward_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_tube_' + i + ' ' + btndisable2 + '><select name="cars" id="sel_cop_tube_' + i + '" class="form-control"></select><p id="Psel_cop_tube_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_ser_doc_' + i + ' ' + btndisable3 + '><select name="cars" id="sel_cop_doc_' + i + '" class="form-control" onchange=cop_consult_chk(' + master_service_id + ',' + i + ')></select><p id="Psel_cop_doc_' + i + '" class="validate_errup60" style="color:red"></p></td><td id=cop_chk_' + i + '><input type="checkbox" id=sel_cop_chk_' + i + ' name="is_activate" value="2" onchange=check_onchange(this) style="width:16px; height:16px;"><p id="Psel_cop_chk__' + i + '" class="validate_errup60" style="color:red"></p></td></tr>'

                    })
                    $('#tbl_service_copy tbody').append(trow);
                    var default_option = '<option value=0>--Select</option>';
                    $.each(data2.data, function (i, emp) {
                        if (emp.category != null && emp.category != '') {
                            $('#sel_cop_cate_' + i).append(default_option);
                            var category = emp.category.split(',');
                            for (var j = 0; j < category.length; j++) {
                                var s1 = $.trim(category[j]).split('/');
                                var option = '<option value=' + s1[0] + '>' + s1[1] + '</option>';
                                $('#sel_cop_cate_' + i).append(option);
                            }
                        }
                        if (emp.department != null && emp.department != '') {
                            $('#sel_cop_dep_' + i).append(default_option);
                            var department = emp.department.split(',');
                            for (var k = 0; k < department.length; k++) {
                                var s1 = $.trim(department[k]).split('/');
                                var option = '<option value=' + s1[0] + '>' + s1[1] + '</option>';
                                $('#sel_cop_dep_' + i).append(option);
                            }
                        }

                        if (emp.base_amount_type == '5') {
                            if (emp.ward != null && emp.ward != '') {
                                $('#sel_cop_ward_' + i).append(default_option);
                                var ward = emp.ward.split(',');
                                for (var l = 0; l < ward.length; l++) {
                                    var s1 = $.trim(ward[l]).split('/');
                                    var option = '<option value=' + s1[0] + '>' + s1[1] + '</option>';
                                    $('#sel_cop_ward_' + i).append(option);
                                }
                            }
                        }
                        if (emp.is_lab == '1') {
                            if (emp.tube != null && emp.tube != '') {
                                $('#sel_cop_tube_' + i).append(default_option);
                                var tube = emp.tube.split(',');
                                for (var m = 0; m < tube.length; m++) {
                                    var s1 = $.trim(tube[m]).split('/');
                                    var option = '<option value=' + s1[0] + '>' + s1[1] + '</option>';
                                    $('#sel_cop_tube_' + i).append(option);
                                }
                            }
                        }


                    })



                }
            }
        }
    })
}
//Subcategory load
function copy_subcat_load(id, rowid) {
    debugger
    var subdepartment = {
        Dml_Indicator: "SDPC",
        Master_cd_id: $('#' + id).val(),
        //MasterSub_cd_id: master_service_ID
        name: name
    }
    $.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);
                $('#sel_cop_subcate_' + rowid).empty();
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '">' + emp.sub_cd_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#sel_cop_subcate_' + rowid).append(SubDepartment);
                    }
                    else {
                        $('#sel_cop_subcate_' + rowid).append(default_opt + SubDepartment);

                    }


                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Subdepartment load
function copy_subdep_load(id, rowid) {
    var subdepartment = {
        Dml_Indicator: "SDP",
        Master_cd_id: $('#' + id).val(),
        // MasterSub_cd_id: master_service_ID
        name: name
    }
    $.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);
                $('#sel_cop_subdep_' + rowid).empty();
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment = '';
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '" data-id=' + emp.work_order_enabled + '>' + emp.sub_cd_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#sel_cop_subdep_' + rowid).append(SubDepartment);
                        load_cop_doc("sel_cop_subdep_" + rowid, rowid)

                    }
                    else {
                        $('#sel_cop_subdep_' + rowid).append(default_opt + SubDepartment);

                    }




                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Load doctor for consulting
function load_cop_doc(id, rowid) {
    var DoctorData = {
        P_Dml_Indicator: "DL",
        branch_id: $('#cop_ser_bch_' + rowid).attr('data-id'),
        department_id: $('#' + id).val()
    }

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

            $('#sel_cop_doc_' + rowid).empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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


                    var tr = '';
                    var SelRole = '';

                    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].doctorid + '" data-id="' + data1.data[i].doctor_id + '">' + data1.data[i].first_name + '</option>';
                        }
                        $('#sel_cop_doc_' + rowid).html(default_opt + SelRole);

                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
function cop_consult_chk(master_service_id, id) {
    var DoctorData = {
        P_Dml_Indicator: "CSDC",
        master_service_id: master_service_id,
        doctorid: $('#sel_cop_doc_' + id).val(),
        branch_id: $('#cop_ser_bch_' + id).attr('data-id')
    }

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


            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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

                    var data2 = data1.data;
                    if (data2[0].stringmsg == 'Success') {

                    }
                    else {
                        toastr.warning('Consultation already exists');
                        $('#sel_cop_doc_' + id).val(0);
                    }


                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//  
function check_onchange(e) {
    debugger;
    e.value = e.checked ? 1 : 2;

}
//Service Copy submit
$('#service_copy_submit').click(function () {
    var service = new Array();
    var count = 0;
    for (var i = 0; i < $('#tbl_service_copy>tbody>tr').length; i++) {
        if ($('#sel_cop_chk_' + i).val() == 1) {
            count += 1;
            if ($('#sel_cop_cate_' + i).val() == 0 || $('#sel_cop_cate_' + i).val() == null) {
                $('#Psel_cop_cate_' + i).show();
                $('#Psel_cop_cate_' + i).fadeOut(8000);
                $('#Psel_cop_cate_' + i).html('Please select the Category');
                $('#sel_cop_cate_' + i).focus();
                $('#sel_cop_cate_' + i).val('');
                return false;
            }
            if ($('#sel_cop_subcate_' + i).val() == 0 || $('#sel_cop_subcate_' + i).val() == null) {
                $('#Psel_cop_subcate_' + i).show();
                $('#Psel_cop_subcate_' + i).fadeOut(8000);
                $('#Psel_cop_subcate_' + i).html('Please select the Subcategory');
                $('#sel_cop_subcate_' + i).focus();
                $('#sel_cop_subcate_' + i).val('');
                return false;
            }
            if ($('#sel_cop_dep_' + i).val() == 0 || $('#sel_cop_dep_' + i).val() == null) {
                $('#Psel_cop_dep_' + i).show();
                $('#Psel_cop_dep_' + i).fadeOut(8000);
                $('#Psel_cop_dep_' + i).html('Please select the Department');
                $('#sel_cop_dep_' + i).focus();
                $('#sel_cop_dep_' + i).val('');
                return false;
            }
            if ($('#sel_cop_subdep_' + i).val() == 0 || $('#sel_cop_subdep_' + i).val() == null) {
                $('#Psel_cop_subdep_' + i).show();
                $('#Psel_cop_subdep_' + i).fadeOut(8000);
                $('#Psel_cop_subdep_' + i).html('Please select the Subdepartment');
                $('#sel_cop_subdep_' + i).focus();
                $('#sel_cop_subdep_' + i).val('');
                return false;
            }
            if ($('#HCbase_amount_type').val() == '5') {
                if ($('#sel_cop_ward_' + i).val() == 0 || $('#sel_cop_ward_' + i).val() == null) {
                    $('#Psel_cop_ward_' + i).show();
                    $('#Psel_cop_ward_' + i).fadeOut(8000);
                    $('#Psel_cop_ward_' + i).html('Please select the ward');
                    $('#sel_cop_ward_' + i).focus();
                    $('#sel_cop_ward_' + i).val('');
                    return false;
                }
            }
            if ($('#HCisworkorder').val() == '2' && $('#HCbase_amount_type').val() != '5') {
                if ($('#sel_cop_doc_' + i).val() == 0 || $('#sel_cop_doc_' + i).val() == null) {
                    $('#Psel_cop_doc_' + i).show();
                    $('#Psel_cop_doc_' + i).fadeOut(8000);
                    $('#Psel_cop_doc_' + i).html('Please select the doctor');
                    $('#sel_cop_doc_' + i).focus();
                    $('#sel_cop_doc_' + i).val('');
                    return false;
                }
            }

            var service_data = {};
            service_data.branch_id = $('#cop_ser_bch_' + i).attr('data-id');
            service_data.master_category_id = $('#sel_cop_cate_' + i).val();
            service_data.department_id = $('#sel_cop_dep_' + i).val();
            service_data.master_sub_category_id = $('#sel_cop_subcate_' + i).val();
            service_data.sub_department_id = $('#sel_cop_subdep_' + i).val();
            service_data.master_service_id = $('#HCmaster_service_id').val();

            if ($('#HCbase_amount_type').val() == '5') {
                service_data.ward_id = $('#sel_cop_ward_' + i).val()
            }
            if ($('#HCisworkorder').val() == '2' && $('#HCbase_amount_type').val() != '5') {
                service_data.doctorid = $('#sel_cop_doc_' + i).val();

            }
            if ($('#HCislab').val() == '1') {
                service_data.tube_container = ($('#sel_cop_tube_' + i).val() == '' || $('#sel_cop_tube_' + i).val() == null) ? 0 : $('#sel_cop_tube_' + i).val();
            }

            service.push(service_data);

        }

    }
    if (count == '0') {
        toastr.warning('Please select any of the checkbox to copy the service');
        return false;
    }
    else {
        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/Service_Master_Copy_Ins_upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(service),
            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[0].stringmsg == 'Success') {
                            toastr.success('Service copied successfully');
                            $('#pop_service_copy').modal('toggle');
                            loadservicedata(0, 1);
                        }

                    }
                }
            }
        })
    }
})
//Copy service concepts end
//Service Favorite
function servicefavourite(e, master_service_id) {
    var val = 0;
    if ($('#fav_' + master_service_id).css("color") != "rgb(0, 128, 0)") {
        $('#fav_' + master_service_id).removeClass('fa-star-o').addClass('fa-star');
        $('#fav_' + master_service_id).css("color", "green");
        val = 1;
    }
    else {
        $('#fav_' + master_service_id).addClass('fa-star-o').removeClass('fa-star');
        $('#fav_' + master_service_id).attr('style', 'font-size:14px');

    }
    var DoctorData = {
        P_Dml_Indicator: "SF",
        master_service_id: master_service_id,
        is_loyalty_scheme: val
    }

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


            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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

                    var data2 = data1.data;
                    if (data2[0].stringmsg == 'Success') {

                    }


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

$('#cg_hms').on('change', function () {
    this.value = this.checked ? 1 : 2;
}).change();

//Lab Parameter-Range Concept
function range_pop_click(param_id, sample_type, param_name) {
    debugger
    $('#hdnrange_param_id').val(param_id);
    $('#span_sample').html(sample_type);
    $('#span_parameter').html(param_name);
    range_clr_popup();
    var DoctorData = {
        P_Dml_Indicator: "LRL",
        master_service_id: param_id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(DoctorData),
        success: function (data) {
            $('#sel_range').val(1);
            debugger;
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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

                    var data2 = data1.data;
                    var tbl_id = '', flag = '';
                    if (data2.length > 0) {
                        var len = (data2.length == 1) ? '' : 'disabled';
                        for (var i = 0; i < data2.length; i++) {

                            if (i == 0) {
                                //$('#sel_range').val(data2[i].type_of_range);
                                //$('#sel_range').attr('disabled', true);
                                if (data2[i].type_of_range == 1) {
                                    $('#range_div_1').removeClass('hidden');
                                    $('#range_tbl_1 tbody').empty();
                                    tbl_id = 'range_tbl_1';
                                    flag = '1';
                                }
                                else if (data2[i].type_of_range == 2) {
                                    $('#range_div_2').removeClass('hidden');
                                    $('#range_tbl_2 tbody').empty();
                                    tbl_id = 'range_tbl_2'
                                    flag = '2';
                                }
                            }
                            var no = '' + flag + '_' + (i + 1) + '';
                            var tr = '', del_button = '';
                            tr = tr + '<tr id=range_td_' + no + ' data-id=' + data2[i].param_range_id + '><td class="hide">' + (i + 1) + '</td>'
                            if (flag == '1') {
                                if (i == 0) {
                                    tr = tr + '<td><select name="cars" id="sel_ran_gen_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + (i + 1) + ')" ' + len + '><option value="0">--Select--</option><option value="1">Male</option><option value="2">Female</option><option value="3">Others</option></select><p id="Psel_ran_gen_' + no + '" class="validate_errup60" style="color:red"></p></td>'
                                }
                                else {
                                    if (data2[0].gender != 4) {
                                        tr = tr + '<td><select name="cars" id="sel_ran_gen_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + (i + 1) + ')" ' + len + '><option value="0">--Select--</option><option value="1">Male</option><option value="2">Female</option><option value="3">Others</option></select><p id="Psel_ran_gen_' + no + '" class="validate_errup60" style="color:red"></p></td>'
                                    }
                                    else {
                                        tr = tr + '<td><select name="cars" id="sel_ran_gen_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + (i + 1) + ')" ' + len + '><option value="0">--Select--</option><option value="4">Neutral</option></select><p id="Psel_ran_gen_' + no + '" class="validate_errup60" style="color:red"></p></td>'
                                    }
                                }
                                tr = tr + '<td><select name="cars" id="sel_ran_age_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + (i + 1) + ')" ' + len + '><option value="0">--Select--</option><option value="1">Year</option><option value="2">Month</option><option value="3">Days</option></select><p id="Psel_ran_age_' + no + '" class="validate_errup60" style="color:red"></p></td> <td><input id="sel_age_frm_' + no + '" class="form-control" value="' + data2[i].age_from + '" onkeyup="numeric_dot(this.id)"  oninput="validate(this)" onchange="age_validation(this.id,' + (i + 1) + ')" /><p id="Psel_age_frm_' + no + '" class="validate_errup60" style="color:red"></p></td> <td><input id="sel_age_to_' + no + '" class="form-control" value=' + data2[i].age_to + ' onkeyup="numeric_dot(this.id)" oninput="validate(this)" onchange="age_validation(this.id,' + (i + 1) + ')"  /><p id="Psel_age_to_' + no + '" class="validate_errup60" style="color:red"></p></td>'

                            }
                            if (i != 0) {
                                del_button = '<button class="btn btn-sm btn-delete mr-10" onclick=range_delete("' + $.trim(no) + '",' + flag + ') id=sel_del_' + no + '><i class="fa fa-trash" aria-hidden="true"></i></button>'

                            }
                            tr = tr + '<td><textarea id="sel_notes_' + no + '" class="table-textarea" value="' + data2[i].notes + '">' + data2[i].notes + '</textarea><p id="Psel_notes_' + no + '" class="validate_errup60" style="color:red"></p></td><td><select name="cars" id="sel_condition_' + no + '" class="table-inputtype" onchange="range_condition(this.id,' + (i + 1) + ',' + flag + ')"><option value="0">--Select--</option><option value="1">></option><option value="2"><</option><option value="3">>=</option><option value="4"><=</option><option value="5">Between</option></select><p id="Psel_condition_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + '<td><input id="sel_lv_' + no + '" class="table-inputtype" value=' + data2[i].low_value + ' onkeyup="numeric_hypen_only(this.id); " oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_lv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + ' <td><input id="sel_hv_' + no + '" class="table-inputtype" value=' + data2[i].high_value + ' onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_hv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + '<td><input id="sel_nv_' + no + '" class="table-inputtype" value="' + ((data2[i].normal_value == '-9999') ? '' : data2[i].normal_value) + '" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" /><p id="Psel_nv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + '<td><input id="sel_cl_' + no + '" class="table-inputtype" value="' + ((data2[i].critical_low == '-9999') ? '' : data2[i].critical_low) + '" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_cl_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + '  <td><input id="sel_ch_' + no + '" class="table-inputtype" value=' + data2[i].critical_high + ' onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_ch_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        + ' <td class="disp_if"><a href="javascript:void(0);" class="btn btn-xs btn-primaryuse  mt5 mr-10" id="sel_Add_' + no + '" onclick=range_add(this.id,' + (i + 1) + ',' + flag + ',"' + $.trim(no) + '")><i class="fa fa-plus-circle" aria-hidden="true"></i></a>' + del_button + '</td></tr>'
                            $('#' + tbl_id).append(tr);
                            if (flag == 1) {
                                $('#sel_ran_gen_' + no + '').val(data2[i].gender);
                                $('#sel_ran_age_' + no + '').val(data2[i].type_of_age);
                            }
                            $('#sel_condition_' + no + '').val(data2[i].condition);
                            range_condition('sel_condition_' + no + '', (i + 1), 3)
                            //if (data2[i].condition == 5) {
                            //    $('#sel_lv_' + no + '').removeClass('hidden');
                            //    $('#sel_hv_' + no + '').removeClass('hidden');
                            //}
                            //else {
                            //    $('#sel_hv_' + no + '').removeClass('hidden');
                            //}

                        }
                    }
                    else {
                        $('#sel_range').change();
                    }


                }
            }
            else {
                $('#sel_range').change();
                console.log(data1);
            }
        }
    });
}
$('#sel_range').change(function () {
    var val = $('#sel_range').val();
    if (val == 1) {

        //$('#range_tbl_1').dataTable().fnDraw();
        //$('#range_tbl_1').dataTable().fnDestroy();
        $("#range_tbl_1").find("tr:gt(1)").remove();
        $('#range_div_1').removeClass('hidden');
        $('#range_div_2').addClass('hidden');
        $('#sel_ran_gen_1_1,#sel_ran_age_1_1,#sel_condition_1_1').val('0');
        $('#sel_age_frm_1_1,#sel_age_to_1_1,#sel_notes_1_1,#sel_lv_1_1,#sel_hv_1_1,#sel_nv_1_1,#sel_cl_1_1,#sel_ch_1_1').val('');
        //$('#sel_lv_1_1,#sel_hv_1_1').addClass('hidden');
        $('#sel_ran_gen_1_1').attr('disabled', false);
        //datatable('range_tbl_1', 'Service_Range', 'Legal');
    }
    if (val == 2) {

        //$('#range_tbl_2').dataTable().fnDraw();
        //$('#range_tbl_2').dataTable().fnDestroy();
        $("#range_tbl_2").find("tr:gt(1)").remove();
        $('#range_div_2').removeClass('hidden');
        $('#range_div_1').addClass('hidden');
        $('#sel_condition_2_1').val('0');
        $('#sel_notes_2_1,#sel_lv_2_1,#sel_hv_2_1,#sel_nv_2_1,#sel_cl_2_1,#sel_ch_2_1').val('');
        $('#sel_lv_2_1,#sel_hv_2_1').addClass('hidden');
        //datatable('range_tbl_2', 'Service_Range', 'Legal');
    }
})
//Range Condition Onchange(for both table age based and others) used flag to separate two tables
function range_condition(id, row_no, flag) {
    debugger;
    var val = $('#' + id).val();
    if (flag != 3) {
        $('#sel_lv_1_' + row_no).val('');
        $('#sel_ch_1_' + row_no).val('');
        $('#sel_hv_1_' + row_no).val('');
        $('#sel_cl_1_' + row_no).val('');
    }
    if (val == '5') {
        $('#sel_lv_1_' + row_no).removeClass('hidden');
        $('#sel_hv_1_' + row_no).removeClass('hidden');
        $('#sel_cl_1_' + row_no).removeClass('hidden');
        $('#sel_ch_1_' + row_no).removeClass('hidden');
    }
    else if (val == '1' || val == '3') {
        $('#sel_lv_1_' + row_no).addClass('hidden');

        $('#sel_ch_1_' + row_no).addClass('hidden');

        $('#sel_hv_1_' + row_no).removeClass('hidden');
        $('#sel_cl_1_' + row_no).removeClass('hidden');
    }
    else {
        $('#sel_hv_1_' + row_no).addClass('hidden');

        $('#sel_cl_1_' + row_no).addClass('hidden');

        $('#sel_lv_1_' + row_no).removeClass('hidden');
        $('#sel_ch_1_' + row_no).removeClass('hidden');
    }
    //if (flag == '1') {
    //    if (val == '5') {
    //        $('#sel_lv_1_' + row_no).removeClass('hidden');
    //        $('#sel_hv_1_' + row_no).removeClass('hidden');
    //    }
    //    else {
    //        $('#sel_lv_1_' + row_no).addClass('hidden');
    //        $('#sel_hv_1_' + row_no).removeClass('hidden');
    //    }
    //}
    //else {
    //    if (val == '5') {
    //        $('#sel_lv_2_' + row_no).removeClass('hidden');
    //        $('#sel_hv_2_' + row_no).removeClass('hidden');
    //    }
    //    else {
    //        $('#sel_lv_2_' + row_no).addClass('hidden');
    //        $('#sel_hv_2_' + row_no).removeClass('hidden');
    //    }
    //}

}
//Range Add (For both table) based on flags 1-age based table ,2-t=others table
function range_add(id, row_no, flag) {
    debugger
    var no = (flag == 1) ? '1_' + row_no : '2_' + row_no;
    if (flag == 1) {
        if ($('#sel_ran_gen_1_' + row_no).val() == 0 || $('#sel_ran_gen_1_' + row_no).val() == null) {
            $('#Psel_ran_gen_1_' + row_no).show();
            $('#Psel_ran_gen_1_' + row_no).fadeOut(8000);
            $('#Psel_ran_gen_1_' + row_no).html('Please select the Gender');
            $('#sel_ran_gen_1_' + row_no).focus();
            $('#sel_ran_gen_1_' + row_no).val(0);
            return false;
        }
        if ($('#sel_ran_age_1_' + row_no).val() == 0 || $('#sel_ran_age_1_' + row_no).val() == null) {
            $('#Psel_ran_age_1_' + row_no).show();
            $('#Psel_ran_age_1_' + row_no).fadeOut(8000);
            $('#Psel_ran_age_1_' + row_no).html('Please select the age');
            $('#sel_ran_age_1_' + row_no).focus();
            $('#sel_ran_age_1_' + row_no).val(0);
            return false;
        }
        if (!($('#sel_age_frm_1_' + row_no).val())) {
            $('#Psel_age_frm_1_' + row_no).show();
            $('#Psel_age_frm_1_' + row_no).fadeOut(8000);
            $('#Psel_age_frm_1_' + row_no).html('Please Enter the Age From');
            $('#sel_age_frm_1_' + row_no).focus();
            $('#sel_age_frm_1_' + row_no).val('');
            return false;
        }
        if (!($('#sel_age_to_1_' + row_no).val())) {
            $('#Psel_age_to_1_' + row_no).show();
            $('#Psel_age_to_1_' + row_no).fadeOut(8000);
            $('#Psel_age_to_1_' + row_no).html('Please Enter the Age to');
            $('#sel_age_to_1_' + row_no).focus();
            $('#sel_age_to_1_' + row_no).val('');
            return false;
        }
    }
    if (!($('#sel_notes_' + no).val())) {
        $('#Psel_notes_' + no).show();
        $('#Psel_notes_' + no).fadeOut(8000);
        $('#Psel_notes_' + no).html('Please Enter the Notes');
        $('#sel_notes_' + no).focus();
        $('#sel_notes_' + no).val('');
        return false;
    }
    if ($('#sel_condition_' + no).val() == 0 || $('#sel_condition_' + no).val() == null) {
        $('#Psel_condition_' + no).show();
        $('#Psel_condition_' + no).fadeOut(8000);
        $('#Psel_condition_' + no).html('Please select the Condition');
        $('#sel_condition_' + no).focus();
        $('#sel_condition_' + no).val(0);
        return false;
    }
    if ($('#sel_condition_' + no).val() == 5) {
        if (!($('#sel_lv_' + no).val())) {
            err_msg('sel_lv_' + no + '', 'Please Enter the Low Value')
            return false;
        }
        else if (!($('#sel_hv_' + no).val())) {
            err_msg('sel_hv_' + no + '', 'Please Enter the high Value')
            return false;
        }
        else if (!($('#sel_cl_' + no).val())) {
            err_msg('sel_cl_' + no + '', 'Please Enter the Critical low')
            return false;
        }
        else if (!($('#sel_ch_' + no).val())) {
            err_msg('sel_ch_' + no + '', 'Please Enter the Critical high')
            return false;
        }
    }
    if ($('#sel_condition_' + no).val() == 1 || $('#sel_condition_' + no).val() == 3) {
        if (!($('#sel_hv_' + no).val())) {
            err_msg('sel_hv_' + no + '', 'Please Enter the high Value')
            return false;
        }
        else if (!($('#sel_cl_' + no).val())) {
            err_msg('sel_cl_' + no + '', 'Please Enter the Critical low')
            return false;
        }
    }
    if ($('#sel_condition_' + no).val() == 2 || $('#sel_condition_' + no).val() == 4) {
        if (!($('#sel_lv_' + no).val())) {
            err_msg('sel_lv_' + no + '', 'Please Enter the Low Value')
            return false;
        }
        else if (!($('#sel_ch_' + no).val())) {
            err_msg('sel_ch_' + no + '', 'Please Enter the Critical high')
            return false;
        }
    }
    //if ($('#sel_condition_' + no).val() == 5) {
    //    if (!($('#sel_lv_' + no).val())) {
    //        $('#Psel_lv_' + no).show();
    //        $('#Psel_lv_' + no).fadeOut(8000);
    //        $('#Psel_lv_' + no).html('Please Enter the Low Value');
    //        $('#sel_lv_' + no).focus();
    //        $('#sel_lv_' + no).val('');
    //        return false;
    //    }
    //}
    //if (!($('#sel_hv_' + no).val())) {
    //    $('#Psel_hv_' + no).show();
    //    $('#Psel_hv_' + no).fadeOut(8000);
    //    $('#Psel_hv_' + no).html('Please Enter the High Value');
    //    $('#sel_hv_' + no).focus();
    //    $('#sel_hv_' + no).val('');
    //    return false;
    //}
    //if (!($('#sel_nv_' + no).val())) {
    //    $('#Psel_nv_' + no).show();
    //    $('#Psel_nv_' + no).fadeOut(8000);
    //    $('#Psel_nv_' + no).html('Please Enter the Normal Value');
    //    $('#sel_nv_' + no).focus();
    //    $('#sel_nv_' + no).val('');
    //    return false;
    //}
    //if (!($('#sel_cl_' + no).val())) {
    //    $('#Psel_cl_' + no).show();
    //    $('#Psel_cl_' + no).fadeOut(8000);
    //    $('#Psel_cl_' + no).html('Please Enter the Critical Low');
    //    $('#sel_cl_' + no).focus();
    //    $('#sel_cl_' + no).val('');
    //    return false;
    //}
    //if (!($('#sel_ch_' + no).val())) {
    //    $('#Psel_ch_' + no).show();
    //    $('#Psel_ch_' + no).fadeOut(8000);
    //    $('#Psel_ch_' + no).html('Please Enter the Critical High');
    //    $('#sel_ch_' + no).focus();
    //    $('#sel_ch_' + no).val('');
    //    return false;
    //}
    var tr = ''
    var count = parseInt($('#range_tbl_' + flag + '>tbody>tr').length) + 1;
    no = (flag == 1) ? '1_' + count : '2_' + count;
    tr = tr + '<tr id=range_td_' + no + ' data-id=0><td class="hide">' + count + '</td>'
    if (flag == '1') {
        if ($('#sel_ran_gen_1_1').val() != '4') {
            tr = tr + '<td><select name="cars" id="sel_ran_gen_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + count + ');" ><option value="0">--Select--</option><option value="1">Male</option><option value="2">Female</option><option value="3">Others</option></select><p id="Psel_ran_gen_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        }
        else {
            tr = tr + '<td><select name="cars" id="sel_ran_gen_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + count + ');"><option value="0">--Select--</option><option value="4">Neutral</option></select><p id="Psel_ran_gen_' + no + '" class="validate_errup60" style="color:red"></p></td>'
        }
        tr = tr + '<td><select name="cars" id="sel_ran_age_' + no + '" class="table-inputtype" onchange="age_validation(this.id,' + count + ');"><option value="0">--Select--</option><option value="1">Year</option><option value="2">Month</option><option value="3">Days</option></select><p id="Psel_ran_age_' + no + '" class="validate_errup60" style="color:red"></p></td> <td><input id="sel_age_frm_' + no + '" class="table-inputtype" onkeyup="numeric_dot(this.id)" oninput="validate(this)" onchange="age_validation(this.id,' + count + ');"/><p id="Psel_age_frm_' + no + '" class="validate_errup60" style="color:red"></p></td> <td><input id="sel_age_to_' + no + '" class="table-inputtype" onkeyup="numeric_dot(this.id)" oninput="validate(this)" onchange="age_validation(this.id,' + count + ');"/><p id="Psel_age_to_' + no + '" class="validate_errup60" style="color:red"></p></td>'
    }
    tr = tr + '<td><textarea id="sel_notes_' + no + '" class="table-textarea"></textarea><p id="Psel_notes_' + no + '" class="validate_errup60" style="color:red"></p></td><td><select name="cars" id="sel_condition_' + no + '" class="table-inputtype" onchange="range_condition(this.id,' + count + ',' + flag + ')"><option value="0">--Select--</option><option value="1">></option><option value="2"><</option><option value="3">>=</option><option value="4"><=</option><option value="5">Between</option></select><p id="Psel_condition_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + '<td><input id="sel_lv_' + no + '" class="table-inputtype" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_lv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + ' <td><input id="sel_hv_' + no + '" class="table-inputtype" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_hv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + '<td><input id="sel_nv_' + no + '" class="table-inputtype" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)"/><p id="Psel_nv_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + '<td><input id="sel_cl_' + no + '" class="table-inputtype" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_cl_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + '  <td><input id="sel_ch_' + no + '" class="table-inputtype" onkeyup="numeric_hypen_only(this.id);" oninput="validate(this)" onchange=\'value_change(this.id,"' + $.trim(no) + '")\'/><p id="Psel_ch_' + no + '" class="validate_errup60" style="color:red"></p></td>'
         + ' <td><a href="javascript:void(0);" class="btn btn-xs btn-primaryuse  mt5 mr-10" id="sel_Add_' + no + '" onclick=range_add(this.id,' + count + ',' + flag + ',"' + $.trim(no) + '")><i class="fa fa-plus-circle" aria-hidden="true"></i></a><button class="btn btn-xs btn-delete mr-10" onclick=range_delete("' + no + '",' + flag + ') id=sel_del_' + no + '><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'

    $('#range_tbl_' + flag + ' tbody:last').append(tr);
    //if (flag == 1 && row_no == 1) {
    //    $('#sel_ran_gen_1_1').attr('disabled', true);
    //}
}
//Range Submit click function
$('#range_submit').click(function () {
    debugger;
    var range_type = $('#sel_range').val();
    var tbl_id = '', no = '';
    if (range_type == 1) {
        tbl_id = 'range_tbl_1';
        no = '1';
    }
    else if (range_type == 2) {
        tbl_id = 'range_tbl_2';
        no = '2';
    }

    for (var j = 1; j <= $('#' + tbl_id + '>tbody>tr').length; j++) {
        var id = $('#' + tbl_id).find("tr").eq(j).prop("id");
        id = id.split('_');
        id = id[2] + '_' + id[3]
        if (range_type == 1) {
            if ($('#sel_ran_gen_' + id + '').val() == 0 || $('#sel_ran_gen_' + id + '').val() == null) {
                $('#Psel_ran_gen_' + id + '').show();
                $('#Psel_ran_gen_' + id + '').fadeOut(8000);
                $('#Psel_ran_gen_' + id + '').html('Please select the Gender');
                $('#sel_ran_gen_' + id + '').focus();
                $('#sel_ran_gen_' + id + '').val(0);
                return false;
            }
            if ($('#sel_ran_age_' + id + '').val() == 0 || $('#sel_ran_age_' + id + '').val() == null) {
                $('#Psel_ran_age_' + id + '').show();
                $('#Psel_ran_age_' + id + '').fadeOut(8000);
                $('#Psel_ran_age_' + id + '').html('Please select the age');
                $('#sel_ran_age_' + id + '').focus();
                $('#sel_ran_age_' + id + '').val(0);
                return false;
            }
            if (!($('#sel_age_frm_' + id + '').val())) {
                $('#Psel_age_frm_' + id + '').show();
                $('#Psel_age_frm_' + id + '').fadeOut(8000);
                $('#Psel_age_frm_' + id + '').html('Please Enter the Age From');
                $('#sel_age_frm_' + id + '').focus();
                $('#sel_age_frm_' + id + '').val('');
                return false;
            }
            if (!($('#sel_age_to_' + id + '').val())) {
                $('#Psel_age_to_' + id + '').show();
                $('#Psel_age_to_' + id + '').fadeOut(8000);
                $('#Psel_age_to_' + id + '').html('Please Enter the Age to');
                $('#sel_age_to_' + id + '').focus();
                $('#sel_age_to_' + id + '').val('');
                return false;
            }
        }
        if (!($('#sel_notes_' + id + '').val())) {
            $('#Psel_notes_' + id + '').show();
            $('#Psel_notes_' + id + '').fadeOut(8000);
            $('#Psel_notes_' + id + '').html('Please Enter the Notes');
            $('#sel_notes_' + id + '').focus();
            $('#sel_notes_' + id).val('');
            return false;
        }
        if ($('#sel_condition_' + id).val() == 0 || $('#sel_condition_' + id).val() == null) {
            $('#Psel_condition_' + id).show();
            $('#Psel_condition_' + id).fadeOut(8000);
            $('#Psel_condition_' + id).html('Please select the Condition');
            $('#sel_condition_' + id).focus();
            $('#sel_condition_' + id).val(0);
            return false;
        }
        if ($('#sel_condition_' + id).val() == 5) {
            if (!($('#sel_lv_' + id).val())) {
                err_msg('sel_lv_' + id + '', 'Please Enter the Low Value')
                return false;
            }
            else if (!($('#sel_hv_' + id).val())) {
                err_msg('sel_hv_' + id + '', 'Please Enter the high Value')
                return false;
            }
            else if (!($('#sel_cl_' + id).val())) {
                err_msg('sel_cl_' + id + '', 'Please Enter the Critical low')
                return false;
            }
            else if (!($('#sel_ch_' + id).val())) {
                err_msg('sel_ch_' + id + '', 'Please Enter the Critical high')
                return false;
            }
        }
        if ($('#sel_condition_' + id).val() == 1 || $('#sel_condition_' + id).val() == 3) {
            if (!($('#sel_hv_' + id).val())) {
                err_msg('sel_hv_' + id + '', 'Please Enter the high Value')
                return false;
            }
            else if (!($('#sel_cl_' + id).val())) {
                err_msg('sel_cl_' + id + '', 'Please Enter the Critical low')
                return false;
            }
        }
        if ($('#sel_condition_' + id).val() == 2 || $('#sel_condition_' + id).val() == 4) {
            if (!($('#sel_lv_' + id).val())) {
                err_msg('sel_lv_' + id + '', 'Please Enter the Low Value')
                return false;
            }
            else if (!($('#sel_ch_' + id).val())) {
                err_msg('sel_ch_' + id + '', 'Please Enter the Critical high')
                return false;
            }
        }
        //if ($('#sel_condition_' + id).val() == 5) {
        //    if (!($('#sel_lv_' + id).val())) {
        //        $('#Psel_lv_' + id).show();
        //        $('#Psel_lv_' + id).fadeOut(8000);
        //        $('#Psel_lv_' + id).html('Please Enter the Low Value');
        //        $('#sel_lv_' + id).focus();
        //        $('#sel_lv_' + id).val('');
        //        return false;
        //    }
        //}
        //if (!($('#sel_hv_' + id).val())) {
        //    $('#Psel_hv_' + id).show();
        //    $('#Psel_hv_' + id).fadeOut(8000);
        //    $('#Psel_hv_' + id).html('Please Enter the High Value');
        //    $('#sel_hv_' + id).focus();
        //    $('#sel_hv_' + id).val('');
        //    return false;
        //}
        //if (!($('#sel_nv_' + id).val())) {
        //    $('#Psel_nv_' + id).show();
        //    $('#Psel_nv_' + id).fadeOut(8000);
        //    $('#Psel_nv_' + id).html('Please Enter the Normal Value');
        //    $('#sel_nv_' + id).focus();
        //    $('#sel_nv_' + id).val('');
        //    return false;
        //}
        //if (!($('#sel_cl_' + id).val())) {
        //    $('#Psel_cl_' + id).show();
        //    $('#Psel_cl_' + id).fadeOut(8000);
        //    $('#Psel_cl_' + id).html('Please Enter the Critical Low');
        //    $('#sel_cl_' + id).focus();
        //    $('#sel_cl_' + id).val('');
        //    return false;
        //}
        //if (!($('#sel_ch_' + id).val())) {
        //    $('#Psel_ch_' + id).show();
        //    $('#Psel_ch_' + id).fadeOut(8000);
        //    $('#Psel_ch_' + id).html('Please Enter the Critical High');
        //    $('#sel_ch_' + id).focus();
        //    $('#sel_ch_' + id).val('');
        //    return false;
        //}

    }
    var service = new Array();
    var range_array = new Array();
    if (range_type == 1) {
        for (var j = 1; j <= $('#range_tbl_1>tbody>tr').length; j++) {
            var range_json = {};
            var i = $('#' + tbl_id).find("tr").eq(j).prop("id");
            i = i.split('_');
            i = i[3]
            range_json.gender_id = $('#sel_ran_gen_1_' + i).val();
            range_json.gender = $("#sel_ran_gen_1_" + i + " option[value='" + $.trim($('#sel_ran_gen_1_' + i).val()) + "']").text()
            range_json.age_id = $('#sel_ran_age_1_' + i).val();
            range_json.type_of_age = $("#sel_ran_age_1_" + i + " option[value='" + $.trim($('#sel_ran_age_1_' + i).val()) + "']").text()
            range_json.age_from = $('#sel_age_frm_1_' + i).val();
            range_json.age_to = $('#sel_age_to_1_' + i).val();
            range_json.notes = $('#sel_notes_1_' + i).val();
            range_json.condition_id = $('#sel_condition_1_' + i).val();
            range_json.condition = $("#sel_condition_1_" + i + " option[value='" + $.trim($('#sel_condition_1_' + i).val()) + "']").text()
            range_json.low_value = ($('#sel_lv_1_' + i).val() == '') ? '-' : $('#sel_lv_1_' + i).val();
            range_json.high_value = ($('#sel_hv_1_' + i).val() == '') ? '-' : $('#sel_hv_1_' + i).val();
            range_json.normal_value = ($('#sel_nv_1_' + i).val() == '') ? '-' : $('#sel_nv_1_' + i).val();
            range_json.critical_low = ($('#sel_cl_1_' + i).val() == '') ? '-' : $('#sel_cl_1_' + i).val();
            range_json.critical_high = ($('#sel_ch_1_' + i).val() == '') ? '-' : $('#sel_ch_1_' + i).val();
            range_array.push(range_json);
        }

        for (var j = 1; j <= $('#range_tbl_1>tbody>tr').length; j++) {
            var service_data = {}
            var i = $('#' + tbl_id).find("tr").eq(j).prop("id");
            i = i.split('_');
            i = i[3]
            service_data.range_type = range_type;
            service_data.gender_id = $('#sel_ran_gen_1_' + i).val();
            service_data.gender = $("#sel_ran_gen_1_" + i + " option[value='" + $.trim($('#sel_ran_gen_1_' + i).val()) + "']").text()
            service_data.age_id = $('#sel_ran_age_1_' + i).val();
            service_data.type_of_age = $("#sel_ran_age_1_" + i + " option[value='" + $.trim($('#sel_ran_age_1_' + i).val()) + "']").text()
            service_data.age_from = $('#sel_age_frm_1_' + i).val();
            service_data.age_to = $('#sel_age_to_1_' + i).val();
            service_data.notes = $('#sel_notes_1_' + i).val();
            service_data.condition_id = $('#sel_condition_1_' + i).val();
            service_data.condition = $("#sel_condition_1_" + i + " option[value='" + $.trim($('#sel_condition_1_' + i).val()) + "']").text()
            service_data.low_value = ($('#sel_lv_1_' + i).val() == '') ? -9999 : $('#sel_lv_1_' + i).val();
            service_data.high_value = ($('#sel_hv_1_' + i).val() == '') ? -9999 : $('#sel_hv_1_' + i).val();
            service_data.normal_value = ($('#sel_nv_1_' + i).val() == '') ? -9999 : $('#sel_nv_1_' + i).val();
            service_data.critical_low = ($('#sel_cl_1_' + i).val() == '') ? -9999 : $('#sel_cl_1_' + i).val();
            service_data.critical_high = ($('#sel_ch_1_' + i).val() == '') ? -9999 : $('#sel_ch_1_' + i).val();
            service_data.range_json = JSON.stringify(range_array);
            service_data.parameter_id = $('#hdnrange_param_id').val();
            service_data.master_service_id = ($('#range_td_1_' + i).attr('data-id') == '') ? 0 : $('#range_td_1_' + i).attr('data-id');
            service.push(service_data);

        }

        console.log(service);
    }
    else {
        for (var i = 1; i <= $('#range_tbl_2>tbody>tr').length; i++) {
            var range_json = {};

            range_json.notes = $('#sel_notes_2_' + i).val();
            range_json.condition_id = $('#sel_condition_2_' + i).val();
            range_json.condition = $("#sel_condition_2_" + i + " option[value='" + $.trim($('#sel_condition_2_' + i).val()) + "']").text()
            range_json.low_value = $('#sel_lv_2_' + i).val();
            range_json.high_value = $('#sel_hv_2_' + i).val();
            range_json.normal_value = $('#sel_nv_2_' + i).val();
            range_json.critical_low = ($('#sel_cl_2_' + i).val() == '') ? -9999 : $('#sel_cl_2_' + i).val();
            range_json.critical_high = $('#sel_ch_2_' + i).val();
            range_array.push(range_json);
        }
        for (var i = 1; i <= $('#range_tbl_2>tbody>tr').length; i++) {
            var service_data = {}
            service_data.range_type = range_type;
            service_data.age_to = $('#sel_age_to_2_' + i).val();
            service_data.notes = $('#sel_notes_2_' + i).val();
            service_data.condition_id = $('#sel_condition_2_' + i).val();
            service_data.condition = $("#sel_condition_2_" + i + " option[value='" + $.trim($('#sel_condition_2_' + i).val()) + "']").text()
            service_data.low_value = ($('#sel_lv_2_' + i).val() == '') ? 0 : $('#sel_lv_2_' + i).val();
            service_data.high_value = $('#sel_hv_2_' + i).val();
            service_data.normal_value = $('#sel_nv_2_' + i).val();
            service_data.critical_low = ($('#sel_cl_2_' + i).val() == '') ? -9999 : $('#sel_cl_2_' + i).val();
            service_data.critical_high = $('#sel_ch_2_' + i).val();
            service_data.parameter_id = $('#hdnrange_param_id').val();
            service_data.master_service_id = $('#range_td_2_' + i).attr('data-id') == '' ? 0 : $('#range_td_2_' + i).attr('data-id');
            service_data.range_json = JSON.stringify(range_array);
            service.push(service_data);
        }
    }


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


            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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

                    var data2 = data1.data;
                    if (data2[0].Stringmsg == 'Success') {
                        toastr.success('Parameter Added Successfully');
                        range_clr_popup();
                        $('#pop_range').modal('toggle');
                    }


                }
            }
            else {
                console.log(data1);
            }
        }
    });
})
//Range Delete
function range_delete(id, flag, flag2) {
    debugger;
    var len = 0;
    $('#range_td_' + id).remove();
    len = $('#range_tbl_' + flag + '>tbody>tr').length;
    if (len == 1) {
        if (flag == 1) {

            $('#sel_ran_gen_1_1').attr('disabled', false);
            $('#sel_ran_age_1_1').attr('disabled', false)
        }
        //$('#sel_condition_' + no + '').val('0');
        //$('#sel_age_frm_' + no + ',#sel_age_to_' + no + ',#sel_notes_' + no + ',#sel_lv_1_1,#sel_hv_' + no + ',#sel_nv_' + no + ',#sel_cl_' + no + ',#sel_ch_' + no + '').val('');
        //$('#sel_lv_' + no + ',#sel_hv_' + no + '').addClass('hidden');

    }

}
//Clear Popup
function range_clr_popup() {
    debugger
    //$('#sel_range').val(0);
    //$('#sel_range').attr('disabled', false);
    $("#range_tbl_1").find("tr:gt(1)").remove();
    $("#range_tbl_2").find("tr:gt(1)").remove();
    $('#range_div_1').addClass('hidden');
    $('#range_div_2').addClass('hidden');
    $('#range_td_1_1').attr('data-id', '');
    $('#sel_ran_gen_1_1,#sel_ran_age_1_1,#sel_condition_1_1').val('0');
    $('#sel_age_frm_1_1,#sel_age_to_1_1,#sel_notes_1_1,#sel_lv_1_1,#sel_hv_1_1,#sel_nv_1_1,#sel_cl_1_1,#sel_ch_1_1').val('');
    //$('#sel_lv_1_1,#sel_hv_1_1').addClass('hidden');
    $('#sel_ran_gen_1_1,#sel_ran_age_1_1,#sel_age_frm_1_1,#sel_age_to_1_1').attr('disabled', false);
    $('#sel_condition_2_1').val('0');
    $('#sel_notes_2_1,#sel_lv_2_1,#sel_hv_2_1,#sel_nv_2_1,#sel_cl_2_1,#sel_ch_2_1').val('');
    $('#sel_lv_2_1,#sel_hv_2_1').addClass('hidden');
    //$('#span_sample').html('');
    //$('#span_parameter').html('');

}
//age_validation
function age_validation(id, flag) {
    debugger;
    var sel_age_type = $('#sel_ran_age_1_' + flag).val()
    var age_to = $('#sel_age_to_1_' + flag).val()
    var sel_gender = $('#sel_ran_gen_1_' + flag).val()
    var age_from = $('#sel_age_frm_1_' + flag).val();
    if (parseInt(age_from) > parseInt(age_to)) {
        $('#P' + id).show();
        $('#P' + id).fadeOut(8000);
        $('#P' + id).html('Invalid Age');
        $('#' + id).focus();
        $('#' + id).val('');
        return false;
    }
    else {
        var tbl_len = $('#range_tbl_1>tbody>tr').length;
        if (sel_age_type == 1) {
            age_from = parseFloat(age_from) * 373;
            age_to = parseFloat(age_to) * 373
        }
        else if (sel_age_type == 2) {
            age_from = parseFloat(age_from) * 31;
            age_to = parseFloat(age_to) * 31;
        }
        for (i = 1; i <= tbl_len; i++) {
            if (flag == i) {
                continue;
            }
            var age_type = $('#sel_ran_age_1_' + i).val();
            var frm_age = $('#sel_age_frm_1_' + i).val();
            var to_age = $('#sel_age_to_1_' + i).val();
            var gender = $('#sel_ran_gen_1_' + i).val()
            if (age_type == 1) {
                to_age = parseFloat(to_age) * 373
                frm_age = parseFloat(frm_age) * 373
            }
            else if (age_type == 2) {
                to_age = parseFloat(to_age) * 31
                frm_age = parseFloat(frm_age) * 31
            }
            if (parseInt(age_from) >= parseFloat(frm_age) && sel_gender == gender && parseInt(age_from) <= parseFloat(to_age)) {
                $('#Psel_age_frm_1_' + flag).show();
                $('#Psel_age_frm_1_' + flag).fadeOut(8000);
                $('#Psel_age_frm_1_' + flag).html('Age already exists');
                $('#sel_age_frm_1_' + flag).focus();
                $('#sel_age_frm_1_' + flag).val('');
                $('#sel_age_to_1_' + flag).val('');
                return false;
            }
            if (parseInt(frm_age) >= parseFloat(age_from) && sel_gender == gender && parseInt(frm_age) <= parseFloat(age_to)) {
                $('#Psel_age_frm_1_' + i).show();
                $('#Psel_age_frm_1_' + i).fadeOut(8000);
                $('#Psel_age_frm_1_' + i).html('Age already exists');
                $('#sel_age_frm_1_' + i).focus();
                $('#sel_age_frm_1_' + i).val('');
                $('#sel_age_to_1_' + i).val('');
                return false;
            }


        }
    }

}
//low value change
function value_change(id, flag) {
    var low_value = $('#sel_lv_' + flag).val();
    var high_value = $('#sel_hv_' + flag).val();
    var low_critics = $('#sel_cl_' + flag).val();
    var high_critics = $('#sel_ch_' + flag).val();
    var sel_condition = $('#sel_condition_' + flag).val();
    if (sel_condition == 5) {
        if (parseFloat(low_value) >= parseFloat(high_value)) {
            err_msg(id, 'Invalid value')
        }
        else {
            if (low_value == '' && (low_critics != '' || high_critics != '')) {
                err_msg("sel_lv_" + flag + "", 'Enter the low value')
                $('#' + id).val('');
                return false;
            }
            if (high_value == '' && (low_critics != '' || high_critics != '')) {
                err_msg("sel_hv_" + flag + "", 'Enter the high value')
                $('#' + id).val('');
                return false;
            }
            if (parseFloat(low_critics) >= parseFloat(low_value)) {
                err_msg(id, 'value should be less than low value')
            }
            if (parseFloat(high_critics) <= parseFloat(high_value)) {
                err_msg(id, 'value should be greater than high value')
            }
        }
    }
    if (sel_condition == 1) {
        if (high_value == '') {
            err_msg("sel_hv_" + flag + "", 'Enter the high value')
            $('#' + id).val('');
        }
        if (parseFloat(low_critics) >= parseFloat(high_value)) {
            err_msg(id, 'value should be less than high value')
        }
    }
    if (sel_condition == 2) {
        if (low_value == '') {
            err_msg("sel_lv_" + flag + "", 'Enter the low value')
            $('#' + id).val('');
        }
        if (parseFloat(high_critics) <= parseFloat(low_value)) {
            err_msg(id, 'value should be greater than low value')
        }
    }
    if (sel_condition == 3) {
        if (high_value == '') {
            err_msg("sel_hv_" + flag + "", 'Enter the high value')
            $('#' + id).val('');
        }
        if (parseFloat(low_critics) > parseFloat(high_value)) {
            err_msg(id, 'value should be less than high value')
        }
    }
    if (sel_condition == 4) {
        if (low_value == '') {
            err_msg("sel_lv_" + flag + "", 'Enter the low value')
            $('#' + id).val('');
        }
        if (parseFloat(high_critics) < parseFloat(low_value)) {
            err_msg(id, 'value should be greater than low value')
        }
    }
}
function err_msg(id, msg) {
    $('#P' + id).show();
    $('#P' + id).fadeOut(8000);
    $('#P' + id).html(msg);
    $('#' + id).focus();
    $('#' + id).val('');
    return false;
}

// schem mapping  start //

function Sevice_Schemmapping(serviceid, branchid, base_amount_type, ServiceName, Department, SubDepartment, Amount) {
    debugger;
    $('#schem_mapping').modal('show');
    $('#Hdnserviceid').val(serviceid);

   // $('#lblServiceName').html(ServiceName);
    //$('#lblDepartment').html(Department);
    //$('#lblSubDepartment').html(SubDepartment);
   // $('#lblBaseAmount').html(Amount);


    if (base_amount_type == 1 || base_amount_type == 3) {
        $('#SchemeActivate_div').addClass('schemeadd');
        $('#Schemeis_activate').prop('checked', false);
        $('#Schemeis_activate').val(2);
    }
    else {
        $('#SchemeActivate_div').removeClass('schemeadd');
    }

    schem_mappingTable(serviceid);
    // SchemEntityName(branchid);
}

function schem_mappingTable(serviceid) {
    debugger
    var servicevalues = {
        P_Dml_Indicator: "SMSEL",
        master_service_id: serviceid

    }

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

            $('#schem_mapping_body tbody').empty();
            var data2 = JSON.parse(data);

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

            }
            else {
                debugger;
                if (data2.msg == "Success") {
                    $('#schem_mapping_body tbody').empty();

                    var data1 = data2.data;

                    if (data1.length > 0) {
                        $.each(data1, function (i, emp) {

                            var ikey = i;
                            var sno = 1 + i;
                            var active = '', edit = '', Action = '';

                            if (emp.status == 1) {
                                edit = "<button class='btn btn-edit  btn-xs btn-add' onclick='SchemMappingEdit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button>";
                                active = '<a  data-toggle="tooltip" title="Make In Active!" id="Scheme_' + ikey + '" class="btn btn-blue btn-xs 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=Scheme_ActiveInActive("' + ikey + '",2)><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</a> ';

                                Action = edit + active;
                            }
                            else {
                                active = '<a  data-toggle="tooltip" title="Make Active!" id="Scheme_' + ikey + '" class="btn btn-blue btn-xs 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=Scheme_ActiveInActive("' + ikey + '",1)><i class="fa fa-check-square-o" aria-hidden="true"></i> Active</a> ';
                                Action = active;
                            }

                            //<button class='btn btn-delete btn-xs' onclick='SchemMappingDelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button>

                            var value = "<tr class='tr_input number' data-id='" + ikey + "' id='td_" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdStatus_" + ikey + "' value=" + emp.status + " /><input type='hidden' id='tdschema_mappingid_" + ikey + "' value=" + emp.schem_mappingid + " /><input type='hidden' id='tdActiveNow_" + ikey + "' value=" + 2 + " /><input type='hidden' id='tdentityid_" + ikey + "' value=" + emp.entityid + " /><td id='tdEntityName_" + ikey + "'>" + emp.entity_name + "</td><td id='tdSMCode_" + ikey + "'>" + emp.schem_code + "</td><td id='tdDescription_" + ikey + "'>" + emp.description + "</td><td class='disp_if' id='tdAction_" + ikey + "'>" + Action + "</td></tr>";

                            $('#schem_mapping_body > tbody:last').append(value);
                        });
                    }
                }
            }
        }
    });
}


function SchemEntityName() {

    debugger;
    var DoctorData = {
        P_Dml_Indicator: "SHMEN",
        // branch_id: branch_id
    }

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

            $('#ddEntityName').empty();
            var data1 = JSON.parse(data)
            if (data1.msg == "Success") {

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


                    var tr = '';
                    var EntityName = '';

                    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++;
                            EntityName = EntityName + '<option  value="' + data1.data[i].master_entity_id + '" data-id="' + data1.data[i].entity_name + '">' + data1.data[i].entity_name + '</option>';
                        }
                        $('#ddEntityName').html(default_opt + EntityName);
                        $('#scheme_name').html(default_opt + EntityName);
                    }

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

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


    var EntityName = $('#ddEntityName option:selected').data('id');

    var Entityid = $('#ddEntityName').val();
    var SMCode = $('#txtSMCode').val();
    var Description = $('#txtDescription').val();
    var ActiveNow = ($('#Schemeis_activate').prop('checked') == true) ? "1" : "2";


    if (parseInt($('#ddEntityName').val()) == 0) {
        $('#PddEntityName').show();
        $('#PddEntityName').fadeOut(8000);
        $('#PddEntityName').html('Select Entity Name');
        $('#ddEntityName').val(0);
        $('#ddEntityName').focus();
        return false;
    }

    if ($('#txtSMCode').val() == '') {
        $('#PtxtSMCode').show();
        $('#PtxtSMCode').fadeOut(8000);
        $('#PtxtSMCode').html('Enter Schem Mapping Code');
        $('#txtSMCode').val('');
        $('#txtSMCode').focus();
        return false;
    }

    if ($('#txtDescription').val() == '') {
        $('#PtxtDescription').show();
        $('#PtxtDescription').fadeOut(8000);
        $('#PtxtDescription').html('Enter Description');
        $('#txtDescription').val('');
        $('#txtDescription').focus();
        return false;
    }

    var ikey = "0";
    var sno = 1;
    var rowcount = $('#schem_mapping_body >tbody >tr').length;

    for (var i = 0; i < rowcount; i++) {

        if ($('#tdentityid_' + i).val() == Entityid) {
            $('#PddEntityName').show();
            $('#PddEntityName').fadeOut(8000);
            $('#PddEntityName').html('Entity Name already Inserted.');
            $('#ddEntityName').val(0);
            $('#ddEntityName').focus();
            return false;
        }

    }

    if (rowcount == 0) {
        var ikey = 0
    }
    else {

        var max = 0;

        $('.number').each(function () {

            var value = parseInt($(this).data('id'));

            max = (value > max) ? value : max;

        });
        var ikey = Number(max) + 1;
        sno = ikey + 1;
    }

    //<button class='btn-xs btn btn-delete btn-add' onclick='SchemMappingDelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button>

    var active = '<a  data-toggle="tooltip" title="Make In Active!" id="Scheme_' + ikey + '" class="btn btn-blue btn-xs 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=Scheme_ActiveInActive("' + ikey + '",2)><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</a> ';

    var value = "<tr class='tr_input number' data-id='" + ikey + "' id='td_" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdStatus_" + ikey + "' value=" + 1 + " /><input type='hidden' id='tdschema_mappingid_" + ikey + "' value='0' /><input type='hidden' id='tdentityid_" + ikey + "' value=" + Entityid + " /><input type='hidden' id='tdActiveNow_" + ikey + "' value=" + ActiveNow + " /><td id='tdEntityName_" + ikey + "'>" + EntityName + "</td><td id='tdSMCode_" + ikey + "'>" + SMCode + "</td><td id='tdDescription_" + ikey + "'>" + Description + "</td><td class='disp_if' id='tdAction_" + ikey + "'><button class='btn-xs btn btn-edit btn-add' onclick='SchemMappingEdit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button> " + active + "</td></tr>";

    $('#schem_mapping_body > tbody:last').append(value);
    $('#ddEntityName').val('0');
    $('#txtSMCode').val('');
    $('#txtDescription').val('');
    $('#Schemeis_activate').prop('checked', false);
    $('#Schemeis_activate').val(2);

});

function SchemMappingEdit(val) {


    var tdEntityid = $('#tdentityid_' + val).val();
    var tdSMCode = $('#tdSMCode_' + val).html();
    var tdDescription = $('#tdDescription_' + val).html();
    var ActiveNow = $('#tdActiveNow_' + val).val();

    $('#ddEntityName').val(tdEntityid);
    $('#txtSMCode').val(tdSMCode);
    $('#txtDescription').val(tdDescription);
    $('#Hdnrowid').val(val);
    $('#oldEntityid').val(tdEntityid);

    if (ActiveNow == 1) {
        $('#Schemeis_activate').prop('checked', true);
    }
    else {
        $('#Schemeis_activate').prop('checked', false);
    }

    $('#BtnSMAdd').hide();
    $('#BtnSMUpdate').removeClass('hidden');

}

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

    debugger
    var EntityName = $('#ddEntityName option:selected').data('id');

    var Entityid = $('#ddEntityName').val();
    var SMCode = $('#txtSMCode').val();
    var Description = $('#txtDescription').val();
    var oldEntityid = $('#oldEntityid').val();
    var ActiveNow = ($('#Schemeis_activate').prop('checked') == true) ? "1" : "2";


    if (parseInt($('#ddEntityName').val()) == 0) {
        $('#PddEntityName').show();
        $('#PddEntityName').fadeOut(8000);
        $('#PddEntityName').html('Select Entity Name');
        $('#ddEntityName').val(0);
        $('#ddEntityName').focus();
        return false;
    }

    if ($('#txtSMCode').val() == '') {
        $('#PtxtSMCode').show();
        $('#PtxtSMCode').fadeOut(8000);
        $('#PtxtSMCode').html('Enter Schem Mapping Code');
        $('#txtSMCode').val('');
        $('#txtSMCode').focus();
        return false;
    }

    if ($('#txtDescription').val() == '') {
        $('#PtxtDescription').show();
        $('#PtxtDescription').fadeOut(8000);
        $('#PtxtDescription').html('Enter Description');
        $('#txtDescription').val('');
        $('#txtDescription').focus();
        return false;
    }

    var rowcount = $('#schem_mapping_body >tbody >tr').length;

    if (oldEntityid != Entityid) {
        for (var i = 0; i < rowcount; i++) {

            if ($('#tdentityid_' + i).val() == Entityid) {

                $('#PddEntityName').show();
                $('#PddEntityName').fadeOut(8000);
                $('#PddEntityName').html('Entity Name already Inserted.');
                $('#ddEntityName').val(0);
                $('#ddEntityName').focus();
                return false;
            }

        }
    }




    var rowid = $('#Hdnrowid').val();
    $('#tdEntityName_' + rowid).html(EntityName);
    $('#tdSMCode_' + rowid).html(SMCode);
    $('#tdDescription_' + rowid).html(Description);
    $('#tdentityid_' + rowid).val(Entityid);
    $('#tdActiveNow_' + rowid).val(ActiveNow);

    $('#ddEntityName').val('0');
    $('#txtSMCode').val('');
    $('#txtDescription').val('');
    $('#Hdnrowid').val('');
    $('#oldEntityid').val('');
    $('#Schemeis_activate').prop('checked', false);
    $('#Schemeis_activate').val(2);
    $('#BtnSMAdd').show();
    $('#BtnSMUpdate').addClass('hidden');

});

function Scheme_ActiveInActive(val, active_id) {
    debugger;
    var mes = '', dml = '', Action = '', active = '', Edit = '', status = '';

    var SMid = $("#tdschema_mappingid_" + val).val();

    Edit = "<button class='btn btn-edit  btn-xs btn-add' onclick='SchemMappingEdit(\"" + val + "\")' data-id=" + val + " ><i class='fa fa-pencil' aria-hidden='true'></i></button> ";

    if (active_id == 2) {
        mes = 'In Active';
        dml = 'SMINA';
        status = 2;
        active = '<a  data-toggle="tooltip" title="Make Active!" id="Scheme_' + val + '" class="btn btn-blue btn-xs 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=Scheme_ActiveInActive("' + val + '",1)><i class="fa fa-check-square-o" aria-hidden="true"></i> Active</a> ';

        Action = active;
    }
    else {
        mes = 'Active';
        dml = 'SMACT';
        status = 1;
        active = '<a  data-toggle="tooltip" title="Make In Active!" id="Scheme_' + val + '" class="btn btn-blue btn-xs 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=Scheme_ActiveInActive("' + val + '",2)><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</a> ';

        Action = Edit + " " + active;
    }

    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>", 'Are You Sure,You want to ' + mes + ' the Schem Mapping ?',
       {

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

           onShown: function (toast) {
               $("#confirmationRevertYes").click(function () {
                   debugger;
                   if (SMid != "0") {

                       var servicevalues = {
                           P_Dml_Indicator: dml,
                           master_service_id: $("#tdschema_mappingid_" + val).val()

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


                               var data2 = JSON.parse(data);

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

                               }
                               else {

                                   if (data2.data[0].Message == "Mapped") {
                                       toastr.warning("Scheme already Mapped with user");
                                       return false;
                                   }
                                   else if (data2.msg == "Success") {
                                       $('#tdStatus_' + val).val(status);
                                       $('#tdAction_' + val).html('');
                                       $('#tdAction_' + val).html(Action);
                                       toastr.success("Schem Mapping " + mes + " Successfully");
                                   }
                               }
                           }
                       });

                   }
                   else {
                       debugger;
                       $('#tdStatus_' + val).val(status);
                       $('#tdAction_' + val).html('');
                       $('#tdAction_' + val).html(Action);
                       toastr.success("Schem Mapping " + mes + " Successfully");

                   }
               });
           }
       });
}

function SchemMappingDelete(val) {

    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>", 'Are You Sure,You want to Delete the Schem Mapping ?',
       {

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

           onShown: function (toast) {
               $("#confirmationRevertYes").click(function () {
                   var SMid = $("#tdschema_mappingid_" + val).val();
                   if (SMid != "0") {

                       var servicevalues = {
                           P_Dml_Indicator: "SMDEL",
                           master_service_id: $("#tdschema_mappingid_" + val).val()

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


                               var data2 = JSON.parse(data);

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

                               }
                               else {

                                   if (data2.msg == "Success") {
                                       $('#td_' + val).remove();
                                       toastr.success("Removed Successfully");
                                   }
                               }
                           }
                       });

                   }
                   else {

                       $('#td_' + val).remove();
                       toastr.success("Removed Successfully");

                   }
               });
           }
       });
}



$('#SM_Submit').click(function () {
    SaveSchem_Mapping();
});

function SaveSchem_Mapping() {

    var rowcount = $('#schem_mapping_body >tbody >tr').length;

    if (rowcount == 0) {
        return false;
    }
    var count = rowcount;

    var Contact_details = [];
    for (var i = 0; i < count; i++) {


        var schema_mappingid = $('#tdschema_mappingid_' + (i)).val();
        var Entityid = $('#tdentityid_' + (i)).val();
        var SMCode = $('#tdSMCode_' + (i)).html();
        var Description = $('#tdDescription_' + (i)).html();
        var ActiveNow = $('#tdActiveNow_' + (i)).val();
        var Status = $('#tdStatus_' + (i)).val();

        Contact_details.push({
            master_serviceid: $('#Hdmaster_service_id').val(),
            schem_mappingid: schema_mappingid,
            entityid: Entityid,
            schem_code: SMCode,
            description: Description,
            created_by: $("#hiddenUser_id").val(),
            Dml_Indicator: "SMIN",
            is_active_now: ActiveNow,
            scheme_status: Status
        })
    }


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

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


                if (data1.length > 0) {
                    toastr.success('Schem Mapping Inserted Successfully.');
                    Servicenext(1)
                    //schem_mappingTable($('#Hdmaster_service_id').val());
                }

            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

// schem mapping end //
//load Service type
function loadservice_type() {
    var data = {
        P_Dml_Indicator: 'ST'
    }
    $.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") {
                    $('#servicetype_filter,#service_type').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.service_typeid + " >" + emp.visit_type_name + "</option>"
                    })
                    $('#servicetype_filter').append(default_option + option);
                    $('#service_type').append(default_option + option);
                }
            }
        }
    })
}
//service name onchange
$('#service_name').change(function () {
    if ($('#master_service_id').val() == '') {
        $('#display_name').val($('#service_name').val())
    }
})
//-------- Sample Type Add Starts-----
//Add sample 
$("#new_sample").click(function () {
    load_sample_table();
    clr_sample();
})
//Load Sample Table
var load_sample_table = function () {
    var data = {
        P_Dml_Indicator: 'LST'
    }
    $.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 {
                $('#tbl_sample tbody').empty();
                $('#tbl_sample').dataTable().fnClearTable();
                $('#tbl_sample').dataTable().fnDraw();
                $('#tbl_sample').dataTable().fnDestroy();
                if (data2.msg == "Success") {
                    var data1 = data2.data;
                    var tr = '';
                    $.each(data1, function (i, emp) {
                        tr = tr + '<tr id=tr_sam_' + (i + 1) + ' data-id="' + emp.sample_id + '"><td>' + (i + 1) + '</td><td id=td_sam_name_' + (i + 1) + '>' + emp.sample_name + '</td><td id=td_sam_unit_' + (i + 1) + ' data-id=' + emp.refunitflag + '>' + emp.Unit + '</td><td><button class="btn btn-xs btn-edit mr-10" onclick="edit_sample(' + (i + 1) + ')"><i class="fa fa-pencil" aria-hidden="true"></i></button><button class="btn btn-xs btn-delete mr-10" onclick="delete_sample(' + (i + 1) + ')"><i class="fa fa-trash" aria-hidden="true"></i></button></td></tr>'
                    })
                    $('#tbl_sample').append(tr);
                    //datatable('tbl_sample', 'Sample_Master', 'Legal');
                    $('#tbl_sample').DataTable();
                }
            }
        }
    })
}
//Add Sample
$('#btn_sample_add').click(function () {

    insert_update_sample('SAI')
})
//Update Sample
$('#btn_sample_update').click(function () {
    insert_update_sample('SAU')
})
//Insert Update Sample
function insert_update_sample(indicator) {
    if (!($('#txt_sample_name').val())) {
        err_msg('txt_sample_name', 'Enter the Sample Name')
        return false;
    }
    if (!($('#is_unit').val())) {
        err_msg('is_unit', 'Select Unit')
        return false;
    }
    else {
        var data = {
            P_Dml_Indicator: indicator,
            service_name: $('#txt_sample_name').val(),
            service_type: $('#is_unit').val(),
            master_service_id: $('#Hsample_id').val()
        }
        $.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[0].Stringmsg == 'success') {
                            toastr.success(data1[0].msg);
                            clr_sample();
                            load_sample_table();
                            if ($('#AddTestTable>tbody>tr').length == 0) {
                                loadsampletype();
                            }
                            else {
                                loadsampletype($('#sType').val());
                            }
                            $('#btn_sample_update').hide();
                            $('#btn_sample_add').show();
                        }

                    }
                }
            }
        })
    }
}
//Edit Sample
var edit_sample = function (id) {
    $('#txt_sample_name').val($('#td_sam_name_' + id).html());
    $('#Hsample_id').val($('#tr_sam_' + id).attr('data-id'))
    $('#is_unit').val($('#td_sam_unit_' + id).attr('data-id'))

    $('a[data-toggle=is_unit][data-title="1"]').addClass('not-active').removeClass('active');
    $('a[data-toggle=is_unit][data-title="0"]').addClass('not-active').removeClass('active');
    $('a[data-toggle=is_unit][data-title="' + $('#td_sam_unit_' + id).attr('data-id') + '"]').removeClass('not-active');
    $('a[data-toggle=is_unit][data-title="' + $('#td_sam_unit_' + id).attr('data-id') + '"]').addClass('active');
    $('#radioBtn').addClass('disabled');
    $('#btn_sample_update').show();
    $('#btn_sample_add').hide();
}
//Delete Sample
var delete_sample = function (id) {
    var data = {
        P_Dml_Indicator: 'SAD',
        master_service_id: $('#tr_sam_' + id).attr('data-id')
    }
    $.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[0].Stringmsg == 'success') {
                        toastr.success(data1[0].msg);
                        /* $('#tr_sam_' + id).remove();*/
                        load_sample_table();
                        if ($('#AddTestTable>tbody>tr').length == 0) {
                            loadsampletype();
                        }
                        else {
                            loadsampletype($('#sType').val());
                        }
                    }

                }
            }
        }
    })
}
//clear sample field
var clr_sample = function () {
    $('#txt_sample_name').val('');
    $('#is_unit').val('');
    $('#Hsample_id').val(0);
    $('a[data-toggle=is_unit][data-title="1"]').addClass('not-active').removeClass('active');
    $('a[data-toggle=is_unit][data-title="0"]').addClass('not-active').removeClass('active');
    $('#radioBtn').removeClass('disabled');
}
//--Add Sample Ends--
//Appointment onchange
$('#typeofserviceapporder').change(function () {
    var val = $('#typeofserviceapporder').val()
    if (val == 2) {
        $('#txtPatientTime').val(0);
    }
})
////lab-display order onchange
//$('#txt_dis_order').change(function () {
//    var value = $('#txt_dis_order').val();
//    for (var i = 1; i <= $('#testAddTable_body>tr').length; i++) {
//        if (parseInt(value) == parseInt($('#display_order_' + i).html())) {
//            err_msg('txt_dis_order', 'Already exists')
//            return false;
//        }
//    }
//})

$('#Selprimarycost').autocomplete({
    //branch_id: $('#branch_id').val() mewway all branch concept,
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "PCC", hospital_id: $('#HospitalId').val() },
            success: function (data) {
                debugger;
                //$('#HdnadmDoctorid').val('');
                $('#HSelprimarycost').val('')
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.name, value: item.name, id: item.master_category_department_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HSelprimarycost').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$('#Selsecondarycost').autocomplete({
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "SCC", Master_cd_id: $('#HSelprimarycost').val() },
            success: function (data) {
                debugger;
                //$('#HdnadmDoctorid').val('');
                $('#HSelsecondarycost').val('')
                var data2 = JSON.parse(data);
                response($.map(data2.data.Table, function (item) {
                    return { label: item.sub_cd_name, value: item.sub_cd_name, id: item.sub_category_department_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HSelsecondarycost').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});


$('#SelLedge').autocomplete({
    //branch_id: $('#branch_id').val() // medway all branch concept
    source: function (request, response) {
        $.ajax({
            async: true,
            url: '/Billing/MasterServiceType_Ins_Upd_Del',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "SLL", hospital_id: $('#HospitalId').val(), master_service_name: $('#SelLedge').val() },
            success: function (data) {
                debugger;
                $('#HSelLedge').val('');

                var data2 = JSON.parse(data);
                response($.map(data2.data, function (item) {
                    return { label: item.master_service_name, value: item.master_service_name, id: item.master_servie_type_id };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HSelLedge').val(ui.item.id);
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});
//ward id unselect check with visit_report
$('#ward_id').on('select2:unselect', function (e) {
    debugger;
    var id = e.params.data.id;
    if ($('#master_service_id').val() != '') {
        var DoctorData = {
            P_Dml_Indicator: "WVC",
            ward_id: id
        }

        $.ajax({
            async: true,
            type: 'POST',
            url: '/Billing/Service_Master_Ins_upd_sel',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(DoctorData),
            success: function (data) {
                var data1 = JSON.parse(data)
                if (data1.msg == "Success") {
                    if (jQuery.isEmptyObject((data1.data))) {
                    }
                    else {
                        if (data1.data[0].Stringmsg != 'Success') {
                            toastr.warning(data1.data[0].Stringmsg)
                            var arr = $('#ward_id').val();
                            arr.push(id);
                            $('#ward_id').val(arr).change();
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
});

$('#isexternal').change(function () {
    debugger
    var checkbox = document.getElementById("isexternal");
    var isChecked = checkbox.checked;
    if (isChecked == true) {
        loadExternal(0, 0, 0);
        $('#externallab').show();
    }
    else {
        $('#externallab').hide();
    }
});
$('#isconsumables').change(function () {
    if ($('#isconsumables').prop('checked') == true) {
        LoadStore()
    }

})

function LoadStore(id) {
    debugger;
    var store = {
        Dml_Indicator: "LS",
        Hospital_id: $('#HospitalIdInt').val(),
        branch_id: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceStore',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            $('#store_name').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '">' + emp.Name + '</option>';
                    });
                    $('#store_name').append(default_opt + SubDepartment);
                    if (id != '') {
                        $('#store_name').val(id)
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
$('#item_name').autocomplete({
    source: function (request, response) {
        debugger
        $.ajax({
            async: true,
            url: '/Billing/AutoCompleteServicesItemList',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "H", FromStoreId: $('#store_name').val(), ToStoreId: 0, StoreType: 0, SupplierId: 0, ItemName: $('#item_name').val() },
            success: function (data) {
                debugger;
                $('#HItem').val('')
                $('#HItemName').val('')
                $('#HItemcode').val('')
                $('#HItemMRP').val('')
                $('#HHSNName').val('')

                var data2 = JSON.parse(data);
                response($.map(data2.data, function (item) {
                    return { label: item.Name, value: item.Name, id: item.Id, HSNName: item.HSNName, code: item.Code };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#HItem').val(ui.item.id);
        $('#HItemName').val(ui.item.value);
        $('#HHSNName').val(ui.item.HSNName);

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

    }
});
//Consumables add
$('#btn_consumables_Add').click(function () {
    debugger
    if ($('#item_name').val() == "" || $('#item_name').val() == 0) {
        $('#Pitem_name').show();
        $('#Pitem_name').fadeOut(8000);
        $('#Pitem_name').html('Please search');
        $('#Pitem_name').focus();
        $('#item_name').val('');
        return false;
    }
    if ($('#quantity').val() == "" || $('#quantity').val() == 0) {
        $('#Pquantity').show();
        $('#Pquantity').fadeOut(8000);
        $('#Pquantity').html('Please enter the quantity');
        $('#Pquantity').focus();
        $('#quantity').val('');
        return false;
    }


    else {
        if ($('#tbl_consumables tbody').length > 0) {
            var labid = $('#item_name').val();
            var arr = [];
            for (var i = 1; i <= $('#tbl_consumables>tbody>tr').length; i++) {
                //var conNameText = $('#con_name_' + i).text();
                var row = $('#con_name_' + i).text() + '_' + $('#Item_' + i).attr('data-id');
               arr.push(row)

               var combinedkey = labid + '_' + $('#Item_' + i).attr('data-id');

               if (row === combinedkey) {
                   // Update the quantity in the existing row
                   var newQuantity = parseInt($('#quantity').val(), 10);
                   var currentQuantity = parseInt($('#con_quan_' + i).text(), 10);
                   $('#con_quan_' + i).text(newQuantity);

                   // Reset input values
                   $('#item_name').val('');
                   $('#quantity').val('');
                   $('#item_name').attr('disabled', false);
                   $('#btn_consumables_Add').html('Add')

                   return false;
               }
            }
           // var combinedkey = labid + '_' + $('#item_name option:selected').attr('data-id')
            if ($.inArray(combinedkey, arr) != -1) {
                $('#Pitem_name').show();
                $('#Pitem_name').fadeOut(8000);
                $('#Pitem_name').html('Selected Already');
                $('#Pitem_name').focus();
                $('#item_name').val(0);
                return false;
            }
        }
        var c = $('#tbl_consumables>tbody>tr').length
        //for (var i = 0; i < $('#tbl_external_lab>tbody>tr').length; i++) {
        var trow = '<tr id=Item_' + (c + 1) + ' data-id=' + $('#HItem').val() + '><td id=item_id_' + (c + 1) + '>' + $('#HItem').val() + '<td id=con_name_' + (c + 1) + '>' + $('#HItemName').val() + '<td id=con_quan_' + (c + 1) + '>' + $('#quantity').val() + '<td><span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (c + 1) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span></td></tr>'
        $("#tbl_consumables tbody:last").append(trow);
        //    c = c + 1;
        //}
        $('#item_name').val('');
        $('#quantity').val('');
        $('#item_name').attr('disabled', false);
        $('#btn_consumables_Add').html('Add')
    }
})
function consumables_chk(id, flag) {
    debugger;
    if ($('#master_service_id').val() == '') {
        $('#Item_' + id).remove();
    }
    else {
        var status = "";
        if (flag == 0) {
            status = "Are You Sure, You Want to Delete the Lab?";
        }
        else if (flag == 2) {
            status = "Are You Sure, You Want to In-Activate the Lab?";
        }
        else if (flag == 1) {

            status = "Are You Sure,You Want to Activate the Lab?";
        }
        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 () {
                          var data = {
                              P_Dml_Indicator: 'CL',
                              is_workorder: $('#item_id_' + id).html(),
                              master_service_id: $('#master_service_id').val(),
                              status: flag
                          }
                          return $.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[0];
                                          var tr = ''
                                          if (data1.status == 'success') {
                                              if (flag == 0) {
                                                  $('#Item_' + id).remove();
                                              }
                                              else if (flag == 2) {
                                                  $('#consumables_action_' + id).empty();
                                                  tr = '<span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue  btn-xs" title="Make Active" onclick=consumables_chk(' + (id) + ',1) ><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></span>'
                                                  $('#consumables_action_' + id).append(tr);
                                              }
                                              else {
                                                  $('#consumables_action_' + id).empty();
                                                  tr = '<span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn  btn-blue  btn-xs" title="Make Inactive" onclick=consumables_chk(' + (id) + ',2) ><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></span>'
                                                  $('#consumables_action_' + id).append(tr);
                                              }
                                          }
                                          else {
                                              toastr.warning('User Mapped already');
                                              //var arr = $('#external_lab').val();
                                              //arr.push(id);
                                              //$('#external_lab').val(arr).change();
                                          }

                                      }
                                  }
                              }
                          })
                      })
                  }
              })

    }
}
//Form Mapping start

//load Select Form
function loadserviceForm() {
    debugger;
    var data = {
        Dml_Indicator: 'FSI',
        ServiceId: $('#Hdmaster_service_id').val(),
        ConsultingType: $('#ConsultingType .active a').attr('value')
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    $('#selectfrom').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.Formid + " >" + emp.Form_Name + "</option>"
                    })
                    // $('#servicetype_filter').append(default_option + option);
                    $('#selectfrom').append(default_option + option);
                }
            }
        }
    })
}

$('#selectfrom').change(function () {
    debugger;
    var selectid = $('#selectfrom').val()
   selectedOptionText = $(this).find('option:selected').text();

    $('#formShow_header').html(selectedOptionText);
    $('#formShow').attr('src',$("#Hdformurl").val() + 'form/' + selectid + '')

})


$('#applicationto').change(function () {
    debugger
    loadapplication()
})

function loadapplication(id) {
    $('#selectapplication').empty();
    var value = [{ value: 1, name: 'Web Application' },
                 { value: 2, name: 'Patient Application' },
                 { value: 3, name: 'Doctor Application' }];
    var option = "";
    var default_option = "<option value='0'>--Select--</option>";
    $.each(value, function (i, emp) {
        if ($('#applicationto').val() == 1 && emp.value != 1) {
            option = option + "<option value=" + emp.value + " >" + emp.name + "</option>"
        }
        else if ($('#applicationto').val() == 2 && emp.value == 1) {
            option = option + "<option value=" + emp.value + " >" + emp.name + "</option>"
        }
        else {
            console.log($('#applicationto').val())
        }
    })
    $('#selectapplication').append(default_option + option);
    if (id != '') {
        $('#selectapplication').val(id);
    }
}

$('#selectapplication').change(function () {
    loadWhereToDisplay(1)
})

//load WhereToDisplay
function loadWhereToDisplay(id,editid) {
    debugger;
    var data = {
        Dml_Indicator: 'FDS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    $('#wheretodisplay').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.form_id + " >" + emp.form_displayname + "</option>"
                    })
                    // $('#servicetype_filter').append(default_option + option);
                    if ($('#selectapplication').val() == id) {
                        $('#wheretodisplay').append(default_option + option);
                    }
                    if (editid != '') {
                        $('#wheretodisplay').append(default_option + option);
                        $('#wheretodisplay').val(editid);
                    }
                }
            }
        }
    })
}



//Load Message Class
//function loadMessageClass() {
//    debugger;
//    var data = {
//        Dml_Indicator: "H"
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/ServiceMessageClass',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(data),
//        success: function (data) {
//            debugger;

//            var data2 = JSON.parse(data);
//            console.log(data2);
//            if (jQuery.isEmptyObject((data2.data))) {

//            }
//            else {

//                if (data2.msg == "Success") {
//                    $('#selectmessage').empty();
//                    var option = "";
//                    var data1 = data2.data;
//                    var default_option = "<option value='0'>--Select--</option>";
//                    $.each(data1, function (i, emp) {
//                        option = option + "<option value=" + emp.ID + " >" + emp.Name + "</option>"
//                    })
//                    // $('#servicetype_filter').append(default_option + option);
//                    $('#selectmessage').append(default_option + option);
//                }
//            }
//        }
//    })
//}



$('#selectmessage').autocomplete({
    //branch_id: $('#branch_id').val() mewway all branch concept,
    source: function (request, response) {
        debugger
        $.ajax({
            async: true,
            url: '/Billing/ServiceMessageClass',
            type: "POST",
            dataType: "json",
            data: { Prefix: request.term, Dml_Indicator: "H" },
            success: function (data) {
                debugger;
                // var data2 = JSON.parse(data);
                var data2 = JSON.parse(data);
                response($.map(data2.data, function (item) {
                    return { label: item.Name, value: item.Name, id: item.ID };
                }))
            }
        })
    },
    minLength: 1,
    select: function (event, ui) {
        debugger;
        $('#Hdselectmessage').val(ui.item.id);
        $('#HdMessageClassName').val(ui.item.value)
    },
    html: true,
    open: function (event, ui) {
        $(".ui-autocomplete").css("z-index", 1000);

    }
});

$("#selectmessage").change(function () {
    Loadsms($('#selectmessage').val(), 0);
})

$("#smsid").change(function () {
    debugger
    if ($('#smsid').prop('checked')) {
        Loadsms($('#Hdselectmessage').val(), 0);
        smsflag = 1
    }
    else {
        $('#SMS').empty();
        smsflag = 2
    }
})

function Loadsms(id, val) {
    debugger;
    var data = {
        Id: id,
        Dml_Indicator: "G"
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceMessageClass',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(data),
        success: function (data) {
            debugger;

            var data2 = JSON.parse(data);
            console.log(data2);
            if (jQuery.isEmptyObject((data2.data))) {

            }
            else {

                if (data2.msg == "Success") {
                    $('#SMS').empty();
                    $('#' + smsfield).empty();
                    var option = "";
                    var data1 = data2.data;
                    $.each(data1, function (i, emp) {
                        option = option + emp.Message
                    })

                    $('#SMS').append(option);
                    $('#' + smsfield).append(option);

                }
            }
        }
    })


}


$('#Save').click(function () {
    debugger;
    var tabValue = $('#ConsultingType .active a').attr('value');

    if ($('#selectfrom').val() == 0 || !$('#selectfrom').val()) {
        $('#Pselectfrom').show();
        $('#Pselectfrom').fadeOut(8000);
        $('#Pselectfrom').html('Select Form Name');
        $('#selectfrom').focus();
        $('#selectfrom').val(0)
        return false;
    }
    else if ($.trim($('#applicationto').val()) == 0 || $.trim($('#applicationto').val()) == '') {
        $('#Papplicationto').show();
        $('#Papplicationto').fadeOut(8000);
        $('#Papplicationto').html('Select ApplicableTo');
        $('#applicationto').focus();
        $('#applicationto').val(0)
        return false;
    }
    else if ($.trim($('#selectapplication').val()) == 0 || $.trim($('#selectapplication').val()) == '') {
        $('#Pselectapplication').show();
        $('#Pselectapplication').fadeOut(8000);
        $('#Pselectapplication').html('Select Application');
        $('#selectapplication').focus();
        $('#selectapplication').val(0)
        return false;
    }
    else if ($.trim($('#wheretodisplay').val()) == 0 || $.trim($('#wheretodisplay').val()) == '') {
        $('#Pwheretodisplay').show();
        $('#Pwheretodisplay').fadeOut(8000);
        $('#Pwheretodisplay').html('Select Where to display');
        $('#Pwheretodisplay').focus();
        $('#wheretodisplay').val(0)
        return false;
    }
    else if (!$('input[name="typeofsave"]:checked').length > 0) {
        $('#Phsaveform').show();
        $('#Phsaveform').fadeOut(8000);
        $('#Phsaveform').html('Select how to save the form');
        $('#Phsaveform').focus();
        return false;
    }

    if ($('#Save').html() == 'Update') {
        indicator_id = 'UP'
    }
    else {
        indicator_id = 'IS'
    }
    var formid = ''
    if ($('#Htformid').val() == "") {
        formid = 0
    }
    else {
        formid = $('#Htformid').val();
    }

    var saveValue = 0;
    if ($('#typeofsave1').prop('checked') && $('#typeofsave2').prop('checked')) {
        saveValue = 3;
    }
    else {
        saveValue = $('#typeofsave2').prop('checked') ? 2 : ($('#typeofsave1').prop('checked') ? 1 : 0);
    }


    var RightsValue = 0;
    if ($('#accessrights1').prop('checked') && $('#accessrights2').prop('checked')) {
        RightsValue = 3;
    }
    else {
        RightsValue = $('#accessrights2').prop('checked') ? 2 : ($('#accessrights1').prop('checked') ? 1 : 0);
    }

    var messageclass = ''
    if ($('#Hdselectmessage').val() == '' || $('#Hdselectmessage').val() == null) {
        messageclass = 0;
    }
    else {
        messageclass = $('#Hdselectmessage').val()
    }
    if (smsflag == '') {
        smsflag = 0
    }
    var submit = {
        Dml_Indicator: indicator_id,
        Id: formid,
        FormId: $('#selectfrom').val(),
        ApplicableTo: $('#applicationto').val(),
        ApplicationType: $('#selectapplication').val(),
        WhereToDisplay: $('#wheretodisplay').val(),
        ServiceId: $('#Hdmaster_service_id').val(),
        //$('#master_service_id').val(),
        IsUpload: saveValue,
        AccessRights: RightsValue,
        ConsultingType:tabValue,
        MessageClassId: messageclass,
        Hospital_id: $('#HospitalId').val(),
        SMS_flag: smsflag,
        MessageClassName: $('#HdMessageClassName').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        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[0].Message == 'Inserted') {
                    toastr.success('Inserted Successfully');                  
                    formclear()
                }
                else if (data2[0].Message == 'Updated') {
                    toastr.success('Updated Successfully');
                    formclear()
                }
                else {
                    toastr.success('Somthing Went Wrong');
                }
            }
            else {
                toastr.success('Somthing Went Wrong');
            }
            LoadFormmappingTable(tabValue)
        },
    });
});

function formclear() {
    $('#selectfrom').val(0)
    $('#applicationto').val(0)
    $('#selectapplication').val(0)
    $('#wheretodisplay').val(0)
    $("input[name='typeofsave']:checked").prop('checked', false);
    $("input[name='accessrights']:checked").prop('checked', false);
    $('#selectmessage').val('')
    var iframe = document.getElementById('formShow');
    iframe.src = ''
   $('#formShow_header').html('')
   $('#Save').html('Save')
   $('#SMS').empty()
}

$('#add_form').click(function () {
    formclear()
    loadserviceForm()
    //loadWhereToDisplay()
})

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

    formmappingedit(Id)

});

function formmappingedit(Id) {
    debugger;
    $('#Htformid').val(Id)
    var Edit = {
        Id: Id,
        Dml_Indicator: "E"
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data[0];
            
            $("#selectfrom").val(emp.FormId);
            $("#applicationto").val(emp.ApplicableTo);
            //$("#selectapplication").val(emp.ApplicationType);
            loadapplication(emp.ApplicationType)
            loadWhereToDisplay(0,emp.WhereToDisplay);
            //$("#wheretodisplay").val(emp.WhereToDisplay);
            $("#selectmessage").val(emp.MessageClassName);
            selectedOptionText = $('#selectfrom').find('option:selected').text();
            $('#formShow_header').html(selectedOptionText);
            $('#formShow').attr('src', $("#Hdformurl").val() + 'form/'  + emp.FormId + '')
      
            if (emp.IsUpload == "3") {
                $('#typeofsave1').prop('checked', "checked");
                $('#typeofsave2').prop('checked', "checked");
            }
            else if (emp.IsUpload == "1") {
                $('#typeofsave1').prop('checked', "checked");
            }
            else if (emp.IsUpload == "2") {
                $('#typeofsave2').prop('checked', "checked");
            }
            else {
                $('#typeofsave1').prop('checked', false);
                $('#typeofsave2').prop('checked', false);
            }
            if (emp.AccessRights == "3") {
                $('#accessrights1').prop('checked', "checked");
                $('#accessrights2').prop('checked', "checked");
            }
            else if (emp.AccessRights == "1") {
                $('#accessrights1').prop('checked', "checked");
            }
            else if (emp.AccessRights == "2") {
                $('#accessrights2').prop('checked', "checked");
            }
            else {
                $('#accessrights1').prop('checked', false);
                $('#accessrights2').prop('checked', false);
            }
     
            $('#Save').html('Update');
        }
    })
}

function formmappingdelete(event, Id) {
    debugger;
    var status = "";
    if (Id != '0') {
        status = "Are You Sure, 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 () {

                      var Delete = {
                          Dml_Indicator: 'D',
                          Id: Id
                      }

                      $.ajax({
                          async: true,
                          type: 'POST',
                          url: "/Billing/ServiceFormMapping_Ins_upd_sel",
                          contentType: 'application/json; charset=UTF-8',
                          data: JSON.stringify(Delete),
                          success: function (data) {
                              debugger;
                              var data1 = JSON.parse(data);
                              console.log(data1);
                              if (data1.data[0].status != "deleted") {

                                  toastr.warning(data1.data[0].status);
                                  return false;
                              }
                              else if (data1.data[0].status == "deleted") {

                                  toastr.success("Deleted Successfully");
                              }
                           
                              var tabValue = $('#ConsultingType .active a').attr('value');
                              LoadFormmappingTable(tabValue)
                          }
                      });
                  });
              }
          })
}

function FormConsulting(val){
    debugger;
    LoadFormmappingTable(val)
}

function LoadFormmappingTable(val) {
    debugger;
    var values = {
        Dml_Indicator: "S",
        ServiceId: $('#Hdmaster_service_id').val(),
        ConsultingType: val
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceFormMapping_Ins_upd_sel',
        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 {
                    $("#accordion").empty();
                    var j = 0, b = '', tr = '', edit = '', del = '', active_inactive = '', active = '', other_info = '';
                    var accordionContainer = $("#accordion");
                    b = data1;
                    $.each(b, function (i, emp) {
                        j++
                        var collapseID = `collapseOne${j}`;
                        var checkboxID = `smsid${j}`;
                        smsfield = `sms${j}`;
                        if (emp.SMS_flag == 1) {
                            $.when(Loadsms(emp.MessageClassId, 0))
                            $('#' + checkboxID).prop('checked', true) // Check the checkbox if emp.SMS_flag is 1

                        } else {
                            $('#' + checkboxID).prop('checked', false); // Uncheck the checkbox if emp.SMS_flag is not 1
                        }
                       

                        var applicableto = (emp.ApplicableTo == '1' ? 'patient' : 'doctor')

                        var formcard = '<div class="col-md-4 col-sm-4 col-xs-6 pat-card mb-20">' +
                                               '<div class="pat-box">' +
                                               '<div class="card-header" role="tab" id="headingOne">' +
                                               '<div class="d_flex"><div style="width:100%;">' +
                                               '<p class="pform_name">' + emp.Form_Name + '</p>' + // Fix: Corrected closing tag for h3
                                               '<p class="ppage_name">' + emp.form_displayname + '</p></div>' +
                                               '<div class="previewtap">' +
                                               '<i class="fa fa-pencil" data-toggle="modal" data-target="#editpopup" id="edit_formmapping" onclick="formmappingedit(' + emp.Id + ')"></i>' +
                                                '<i class="fa fa-trash" data-toggle="modal"  id="delete_formmapping" onclick="formmappingdelete(this,' + emp.Id + ')"></i>' +
                                               '</div></div><p class="papplicable mt10">APPLICABLE TO: <span>' + applicableto + '<span>' +
                                               '</p><p class="papplicable mt10">WHERE TO DISPLAY: <span>' + emp.form_displayname + '</span></p>' +
                                               '<div class="smsoveralldiv mt10">' +
                                               '<div class="smsdiv"><p><b>SMS</b></p>' +
                                               '<div><label class="switch pull-right" data-toggle="collapse" data-target="#externallab">' +
                                               '<input type="checkbox" id="' + checkboxID + '"><span class="slider round"></span>' +
                                               '</label></div></div><div class="smscontentdiv">' +
                                               '<p id="' + smsfield + '"></p></div></div></div></div></div></div>';

                        accordionContainer.append(formcard);


                    });

                }

            }
            else {
                console.log(data);
                $("#accordion").empty();
            }
            loadserviceForm()
            //loadWhereToDisplay()
        }

    });

}
//Form Mapping end



// CAMPAIGN SERVICE START
$('#campaign_search').change(function () {
    var campsearch = $('#campaign_search').val()
    loadCampaigndata(campsearch)
})


$('#btnCampaignSubmit').on("click", function () {
    debugger;

    if ($.trim($('#campaign_urlname').val()) == "") {
        $('#Pcampaign_urlname').show();
        $('#Pcampaign_urlname').fadeOut(8000);
        $('#Pcampaign_urlname').html('Enter URL  Name');
        $('#Pcampaign_urlname').focus();
        return false;
    }

    if ($.trim($('#campaign_type').val()) == "" || $('#campaign_type').val() == '0') {
        $('#Pcampaigntype').show();
        $('#Pcampaigntype').fadeOut(8000);
        $('#Pcampaigntype').html('Select Type');
        $('#Pcampaigntype').focus();
        $('#Pcampaigntype').val('')
        return false;
    }

    if ($('#campaign_from_date').val() == "" || $('#campaign_from_date').val() == '0') {
        $('#Pcampaign_from_date').show();
        $('#Pcampaign_from_date').fadeOut(8000);
        $('#Pcampaign_from_date').html('Select the From Date');
        $('#Pcampaign_from_date').focus();
        return false;
    }
    if ($('#campaign_to_date').val() == "" || $('#campaign_to_date').val() == '0') {
        $('#Pcampaign_to_date').show();
        $('#Pcampaign_to_date').fadeOut(8000);
        $('#Pcampaign_to_date').html('Select the ToDate');
        $('#Pcampaign_to_date').focus();
        return false;
    }
    if ($('#status_camp').val() == "" || $('#status_camp').val() == '0') {
        $('#Pstatus_camp').show();
        $('#Pstatus_camp').fadeOut(8000);
        $('#Pstatus_camp').html('Select The Status');
        $('#Pstatus_camp').focus();
        return false;
    }
    var from_date = '', to_date = ''
    var date = $('#campaign_from_date').val().split('/');
    from_date = date[2] + '-' + date[1] + '-' + date[0];

    var date2 = $('#campaign_to_date').val().split('/');
    to_date = date2[2] + '-' + date2[1] + '-' + date2[0];

    var uploadfile = $('#hformimg').val()

    var Dml_Indicator = '', Id = '';

    if ($('#btnCampaignSubmit').html() == 'Add') {
        Id = 0
        Dml_Indicator = 'IS'
    }
    else {
        Dml_Indicator = 'UP'
        Id = $("#Htcampaignid").val()
    }
    var submit = {
        Id: Id,
        URL: $('#campaign_urlname').val(),
        Plateform: $('#campaign_type').val(),
        ActiveForm: from_date,
        ActiveTo: to_date,
        Status: $('#status_camp').val(),
        QR: uploadfile,
        Dml_Indicator: Dml_Indicator,
        masterserviceid: $('#Hdmaster_service_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: "/Billing/ServiceCampaign_Ins_upd_sel",
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(submit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            console.log(data1);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data[0];
                if (data2.Message == 'Inserted') {
                    toastr.success('Inserted Successfully');
                }
                else if (data2.Message == 'Updated') {
                    toastr.success("Updated Successfully");
                }
                else {
                    toastr.success('Somthing Went Wrong');
                }
                loadCampaigndata()
            }

        },
    });
});

$('#qr_image').change(function () {
    debugger;
    QRimageupload();
});
// Image Upload
function QRimageupload() {
    debugger;
    var uploadpath = $('#qr_image').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (fileExtension == "png" || fileExtension == "PNG") {
    }
    else {
        $('#Pqr_image').show();
        $('#Pqr_image').fadeOut(8000);
        $('#Pqr_image').html('Please upload file having extensions .png only.');
        $('#Pqr_image').val('');
        $('#Pqr_image').focus();
        return false;
    }
    if (window.FormData !== undefined) {
        var fileUpload = $("#qr_image").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();

        $.when(checkimagedimensionvalidation(fileUpload.files[0], 240, 256)).
        done(function (Results) {
            if (Results == 'Success') {
                for (var i = 0; i < files.length; i++) {
                    fileData.append(files[i].name, files[i]);

                }
                fileData.append('username', 'Manas');
                $.ajax({
                    url: '/Form_builder/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, drloimage;
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnCDfilepath').val() + $('#HospitalId').val() + '/FormBuilderFileUpload/' + emp + '?' + n;
                            $('#profile-photo').append('<a href="' + drloimage + '" target="_blank" id="QRimage">Image</a>');
                            $('#hformimg').val(emp);

                        });
                    }
                });
            }
            else {
                $('#qr_image').val('');

            }
            //this code is executed when all ajax calls are done
        });

    }
}

// table list
function loadCampaigndata() {
    debugger;
    var values = {
        Dml_Indicator: "S",
        masterserviceid: $('#Hdmaster_service_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: "/Billing/ServiceCampaign_Ins_upd_sel",
        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_campaign tbody').empty();
                    $('#tbl_campaign').dataTable().fnClearTable();
                    $('#tbl_campaign').dataTable().fnDestroy();

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

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

                        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=Campaignedit(this,"' + emp.Id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a  data-toggle="tooltip" title="Delete"  id="TPAdel_' + emp.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=Campdel(this,"' + emp.Id + '","DE")><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=Campdel(this,"' + emp.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=Campdel(this,"' + emp.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>';
                        }
                        if (emp.QR != '' && emp.QR != null) {
                            QR_Image = '<a target="_blank" href="' + $('#hdnCDfilepath').val() + "/" + $('#HospitalId').val() + "/" + "FormBuilderFileUpload/" + emp.QR + '">Form Image</a>';
                        }
                        else {
                            QR_Image = '';
                        }
                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.URL + '</td><td>' + emp.Plateform + '</td><td >' + emp.ActiveForm + '</td><td>' + emp.ActiveTo + '</td><td>' + QR_Image + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#campaign_table_body').html(tr);
                    $('#tbl_campaign').DataTable();

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

}
function Campdel(event, campid, indicatorid) {
    debugger;
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    debugger;
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
     .then(function (data) {
         var data1 = JSON.parse(data);
         if (data1.msg == "Success") {
             var data1 = data1.data;
             if (jQuery.isEmptyObject((data1))) {
             }
             else {
                 var j = 0;
                 var status = data1.Table[0].role_rights_add
                 if (status == 0) {

                     return;
                 }
                 else {
                     var status = "";
                     if (indicatorid == 'DE') {
                         status = "Are You Sure, You Want to Delete?";
                     }
                     else if (indicatorid == 'INACT') {
                         status = "Are You Sure, You Want to In-Activate?";
                     }
                     else if (indicatorid == 'ACT') {

                         status = "Are You Sure,You Want to Activate?";
                     }
                     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 () {

                                       var Delete = {
                                           Dml_Indicator: indicatorid,
                                           Id: campid
                                       }

                                       $.ajax({
                                           async: true,
                                           type: 'POST',
                                           url: "/Billing/ServiceCampaign_Ins_upd_sel",
                                           contentType: 'application/json; charset=UTF-8',
                                           data: JSON.stringify(Delete),
                                           success: function (data) {
                                               debugger;
                                               var data1 = JSON.parse(data);

                                               if (indicatorid == 'DE') {

                                                   toastr.success("Deleted Successfully");
                                               }
                                               else if (indicatorid == 'INACT') {

                                                   toastr.success("Inactivated Successfully");
                                               }
                                               else if (indicatorid == 'ACT') {

                                                   toastr.success("Activated Successfully");
                                               }
                                               loadCampaigndata()
                                           }
                                       });
                                   });
                               }
                           })

                 }
             }
         }

     })

};
//Edit
function Campaignedit(event, Id) {
    debugger;
    $('#campaign_modal').modal('toggle');
    $('#Htcampaignid').val(Id)
    var Edit = {
        Id: Id,
        Dml_Indicator: "E"
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: "/Billing/ServiceCampaign_Ins_upd_sel",
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data;

            $("#campaign_urlname").val(emp[0].URL);
            $("#campaign_type").val(emp[0].Plateform);
            $("#campaign_from_date").val(emp[0].ActiveForm);
            $("#campaign_to_date").val(emp[0].ActiveTo);
            $("#status_camp").val(emp[0].Status);
            $("#Htcampaignid").val(emp[0].Id);

            if (emp[0].QR != null && emp[0].QR != "") {
                $('#profile-photo').show();
                drloimage = $('#hdnCDfilepath').val() + $('#HospitalId').val() + '/FormBuilderFileUpload/' + emp[0].QR;
                $('#profile-photo').append('<a href="' + drloimage + '" target="_blank" id="formimage">Image</a>');
                $('#hformimg').val(emp[0].QR);
            }
            $('#btnCampaignSubmit').html('Update');
        }
    })
}
function clear() {
    $('#campaign_urlname').val(''),
    $('#campaign_type').val(''),
    $('#campaign_from_date').val(''),
    $('#campaign_to_date').val(''),
    $('#status_camp').val(''),
    $('#qr_image').val('')

};

//-- Campaign Ends---


//Package Mapping Start
function table_package() {
    debugger;
    $('#shade_slot').show();
    var indicator_id = '';
    //if ($('#hiddenRole_id').val() == 2) {
    //    indicator_id = 'PDST'
    //}
    //else {
    indicator_id = 'PST'
    //}
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();

    var package_data = {
        indicator_id: indicator_id,
        master_service_id: $('#Hdmaster_service_id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            debugger;
            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 {
                    $('#package_list_table tbody').empty();
                    $('#package_list_table').dataTable().fnClearTable();
                    $('#package_list_table').dataTable().fnDraw();
                    $('#package_list_table').dataTable().fnDestroy();
                    var j = 0, row_data = '';

                    var b = data1.Table;
                    $.each(b, function (i, emp) {
                       
                        j++;
                        edit = '<button class="btn btn-edit btn-xs" data-toggle="tooltip" data-placement="bottom" title="Edit" data-id="PS_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="package_details_form" onclick=package_edit("' + emp.package_auto_id + '",this)><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                        del = '<button data-toggle="tooltip" data-placement="bottom" title="Delete"  class="btn deleteicon-btn btn-xs" data-id="PS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="package_details_form" onclick=package_delete("' + emp.package_auto_id + '",this,"PDD")><i class="fa fa-trash-o" aria-hidden="true"></i></button>';

                        print = '<button type="button" class="btn btn-blue btn-xs mr-5" data-id="B_F1" data-type="role_rights_function" data-nav="" data-name="" onclick=package_wise_report(' + emp.package_auto_id + ',' + emp.branch_id + ',' + emp.hospitalid + ',this)><i class="fa fa fa-print" aria-hidden="true"></i>Print</button>';

                        if (emp.package_status == "2") {
                            MakeActive = '<button data-toggle="tooltip" data-placement="bottom" title="Active" class="btn btn-blue btn-xs" data-id="PS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="package_details_form" onclick=package_delete("' + emp.package_auto_id + '",this,"PAC")><i class="fa fa-check-square-o" aria-hidden="true"></i> Active</button>';
                        }
                        else {
                            MakeActive = '<button data-toggle="tooltip" data-placement="bottom" title="In Active" class="btn btn-blue btn-xs" data-id="PS_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="package_details_form" onclick=package_delete("' + emp.package_auto_id + '",this,"PA")><i class="fa fa-minus-square-o" aria-hidden="true"></i> In Active</button>';
                        }
                        view_more = '<button data-toggle="tooltip" data-placement="bottom" title="View_more" onclick=servicedetails(this,"' + emp.package_auto_id + '"); class="btn addicon-btn btn-xs mr-10"><span class="fa fa-angle-double-down"></span></button>';
                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + view_more + '</div></div></div></div>';

                        var validity_from_date = "-", validity_to_date = "-", validity_period_days = '';
                        if (emp.validity_from_date == null || emp.validity_from_date == '') {
                            validity_from_date = "-"
                        }
                        else {
                            validity_from_date = emp.validity_from_date;
                        }
                        if (emp.validity_to_date == null || emp.validity_to_date == '') {
                            validity_to_date = "-"
                        }
                        else {
                            validity_to_date = emp.validity_to_date;
                        }
                        if (emp.package_status == "2" && emp.expire_status != 0) {
                            validity_period_days = '<span class="label label-warning">Inactive</span>';
                        }
                        else if (emp.package_status == "1" && emp.expire_status != 0) {
                            validity_period_days = '<span class="label label-success">Active</span>';
                        }
                        else if (emp.expire_status == 0) {
                            validity_period_days = '<span class="label label-danger">Expired</span>';
                        }
                        //else {
                        //    validity_period_days = '<span class="label label-success">Active</span>';
                        //}
                        if (emp.package_status == "1") {

                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + '' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + MakeActive + '</div><div class="text-left">' + print + '</div></div></div>';

                            //row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.package_id + "</td><td class='tbl-name'>" + emp.package_name + "</td><td>" + validity_from_date + "</td><td>" + validity_to_date + "</td><td><span class='rup-sym'>&#8377</span><span class='tbl-price'>" + emp.price + "</span></td><td>" + emp.is_surgical + "</td><td>" + validity_period_days + "</td><td>" + other_info + "</td><td>" + view_more + "</td></tr>";
                            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.package_id + "</td><td class='tbl-name'>" + emp.package_name + "</td><td>" + validity_from_date + "</td><td>" + validity_to_date + "</td><td>&#8377 " + emp.price + "</td><td>" + emp.is_surgical + "</td><td>" + validity_period_days + "</td></tr>";

                        }
                        else if (emp.package_status == "2") {
                            other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs" data-toggle="dropdown" aria-expanded="true"> <span class="fa fa-ellipsis-h" data-toggle="tooltip" data-placement="bottom" title="Other Options" style="color:black;" aria-hidden="true"></span><span class="sr-only">Options</span></a><div class="dropdown-menu info-dropdown" id=""> <div class="text-left">' + MakeActive + '</div><div class="text-left">' + print + '</div></div></div></div>';
                            //row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.package_id + "</td><td class='tbl-name'>" + emp.package_name + "</td><td>" + validity_from_date + "</td><td>" + validity_to_date + "</td><td><span class='rup-sym'>&#8377</span><span class='tbl-price'>" + emp.price + "</span></td><td>" + emp.is_surgical + "</td><td>" + validity_period_days + "</td><td>" + other_info + "</td><td>" + view_more + "</td></tr>";
                            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.package_id + "</td><td class='tbl-name'>" + emp.package_name + "</td><td>" + validity_from_date + "</td><td>" + validity_to_date + "</td><td>&#8377 " + emp.price + " </td><td>" + emp.is_surgical + "</td><td>" + validity_period_days + "</td></tr>";

                        }
                        else {
                            row_data = row_data + "<tr><td>" + j + "</td><td>" + emp.package_id + "</td><td class='tbl-name'>" + emp.package_name + "</td><td>" + validity_from_date + "</td><td>" + validity_to_date + "</td><td>&#8377 " + emp.price + "</td><td>" + emp.is_surgical + "</td><td>" + validity_period_days + "</td><td><span></span></td></tr>";
                        }
                    });

                    $('#package_list_table tbody').append(row_data);
                    $('#shade_slot').hide();
                    //datatable('package_list_table', 'Package_Details', 'Legal');
                    $('#package_list_table').DataTable();

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

//---Package Mapping End---

//----CRM Mapping Starting---
$('#crm_mapping_search').keyup(function () {
    debugger;
    SearchFilteration();

});

function SearchFilteration() {
    debugger
    var filteredArr = [];
    if (crm_data.length > 0) {
        var fillType = '';
        if ($('#crm_mapping_search').val()) {
            fillType = 'item.Name.toUpperCase().includes($("#crm_mapping_search").val().toUpperCase())'
        }
   
        filteredArr = crm_data.filter((item) =>(fillType != '' ? eval(fillType) : true));

        SearchBind(filteredArr);
    }
}
function SearchBind(data) {
    $("#crmmapping_accordion").empty();
 
    var accordionContainerCRM = $("#crmmapping_accordion");
    var j = 0;
    if (data.length > 0) {
        $.each(data, function (i, emp) {
            j++
            var collapseID = `collapse${j}`;
            var empId = emp.Id;
            accordionContainerCRM.append(`


                                <div class ="panel" style="margin-bottom: 10px !important;">
                                    <div class ="row d_flex accordion_header">
                                        <div class ="col-lg-6 col-md-6 col-sm-8 col-xs-10 d_flex_aic pl-0">
                                            <div class ="accordion_circle">P</div>
                                            <div class ="pl-10">
                                                <p class ="light_txt mb-0">FORM </p>
                                                <p class ="details_title mb-0">${emp.Name} </p>
                                            </div>
                                        </div>
                                        <div class ="col-lg-6 col-md-6 col-sm-4 col-xs-2 pr-0 accordion_icon">
                                          <i class ="fa fa-pencil pull-right" aria-hidden="true" data-toggle="modal" data-target="#crm_mapping_add" onclick="servicecrmedit('${empId}')"></i>
                                        </div>
                                    </div>
                                    <div id="${collapseID}" class ="collapse overall_body in">
                                        <div id="another_div"></div>
                                    </div>
                                </div>


                        `);
        });
    }
    return true;
}

$('#crmtaskcreationtype').change(function () {
    debugger
    if ($('#crmtaskcreationtype').val() == 3) {
        $('#div_repeattype').show()
        $('#div_repeatday').show()
        $('#taskcreation_div').hide()
    }
    else if ($('#crmtaskcreationtype').val() == 2) {
        $('#taskcreation_div').hide()
    }
    else {
        $('#div_repeattype').hide()
        $('#div_repeatday').hide()
        $('#taskcreation_div').show()
    }

})

$('#crm_duedateindays').on('keyup', function () {
    var DueDays = $('#crm_duedateindays').val();
    if (parseFloat(DueDays) <= 0) {
        $('#Pcrm_duedateindays').show();
        $('#Pcrm_duedateindays').fadeOut(8000);
        $('#Pcrm_duedateindays').html('Doesn\'t allow zero value');
        $('#crm_duedateindays').focus();
        $('#crm_duedateindays').val('');
        return false;
    }
});

$('#crm_taskcreationindays').on('keyup', function () {
    var TaskCreationdays = $('#crm_taskcreationindays').val();
    if (parseFloat(TaskCreationdays) <= 0) {
        $('#Pcrm_taskcreationindays').show();
        $('#Pcrm_taskcreationindays').fadeOut(8000);
        $('#Pcrm_taskcreationindays').html('Doesn\'t allow zero value');
        $('#crm_taskcreationindays').focus();
        $('#crm_taskcreationindays').val('');
        return false;
    }
});

$('#crm_mapping_save').click(function () {
    debugger
    var selectedButtons = document.querySelectorAll('#radio_Btn a.active');
    if (selectedButtons.length === 0) {
        $('#PClinical').show();
        $('#PClinical').fadeOut(8000);
        $('#PClinical').html("Please select a Clinical type.");
        return false;
    }

    if ($.trim($('#crm_mapping_name').val()) == '') {
        $('#Pcrm_mapping_name').show();
        $('#Pcrm_mapping_name').fadeOut(8000);
        $('#Pcrm_mapping_name').html('Enter Name');
        $('#crm_mapping_name').focus();
        return false;
    }
    if ($.trim($('#crm_mapping_type').val()) == 0 || $.trim($('#crm_mapping_type').val()) == '') {
        $('#Pcrm_mapping_type').show();
        $('#Pcrm_mapping_type').fadeOut(8000);
        $('#Pcrm_mapping_type').html('Select Task Type');
        $('#crm_mapping_type').focus();
        return false;
    }
    if ( $.trim($('#crm_duedateindays').val()) == '') {
        $('#Pcrm_duedateindays').show();
        $('#Pcrm_duedateindays').fadeOut(8000);
        $('#Pcrm_duedateindays').html('Enter Due Date');
        $('#crm_duedateindays').focus();
        return false;
    }

    if ($.trim($('#crmtaskcreationtype').val()) == 0 || $.trim($('#crmtaskcreationtype').val()) == '') {
        $('#Pcrmtaskcreationtype').show();
        $('#Pcrmtaskcreationtype').fadeOut(8000);
        $('#Pcrmtaskcreationtype').html('Select Task Creation Type');
        $('#crmtaskcreationtype').focus();
        return false;
    }
    if ($('#crmtaskcreationtype').val() == 1) {
        if ($.trim($('#crm_taskcreationindays').val()) == '') {
            $('#Pcrm_taskcreationindays').show();
            $('#Pcrm_taskcreationindays').fadeOut(8000);
            $('#Pcrm_taskcreationindays').html('Enter Task creation in day');
            $('#crm_taskcreationindays').focus();
            return false;
        }
    }
    if ($.trim($('#crmtaskpriotity').val()) == 0 || $.trim($('#crmtaskpriotity').val()) == '') {
        $('#Pcrmtaskpriotity').show();
        $('#Pcrmtaskpriotity').fadeOut(8000);
        $('#Pcrmtaskpriotity').html('Select Task Priority');
        $('#crmtaskpriotity').focus();
        return false;
    }

    var clinical = $("#radio_Btn a.active").attr("value");
    var CRM_Id = ''
    if ($("#HCRMMapping").val() == '') {
        CRM_Id = 0
    }
    else {
        CRM_Id = $("#HCRMMapping").val()
    }
    var Crmtaskcreationindays = ''
    if ($("#crm_taskcreationindays").val() == '') {
        Crmtaskcreationindays = 0
    }
    else {
        Crmtaskcreationindays= $("#crm_taskcreationindays").val()
    }
   var CRMArray = [];

 // for (j = 0; j < service.length; j++) {
    var Obj = {};

    Obj.Dml_Indicator = 'CMA';
    Obj.branch_id = $('#branch').val();
    Obj.hospital_id = $('#HospitalId').val();
    Obj.CreatedBy = $('#hiddenUser_id').val()
    Obj.IsClinical = clinical
    Obj.Name = $('#crm_mapping_name').val()
    Obj.TaskType = $('#crm_mapping_type').val()
    Obj.DueDays = $('#crm_duedateindays').val()
    Obj.TaskCreationType = $('#crmtaskcreationtype').val()
    Obj.TaskCreationdays = Crmtaskcreationindays
    Obj.TaskPriority = $('#crmtaskpriotity').val()
    Obj.Description = $('#crmmapping_description').val()
    Obj.ServiceId = $('#Hdmaster_service_id').val()
    Obj.Id = CRM_Id
    Obj.ServiceTypeId = $('#Hdservice_type_id').val()
    Obj.RepeatDay = $('#repeatday').val()
    Obj.RepeatType = $('#repeattype').val()

    CRMArray.push(Obj);
   // }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceCRM_Mapping',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(CRMArray),
        success: function (data) {
            var data1 = JSON.parse(data);
             var data2 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data2[0].stringMsg == "success") {
                        debugger;                      
                            toastr.success('Added Successfully');
                            CRMClear();
                    }
                    else {
                        toastr.error('Something Went Wrong');
                    }
                    LoadCRMmappingTable();
                }            
        }
    });
});

function LoadCRMmappingTable() {
    debugger;
    var values = {
        P_Dml_Indicator: "CRMS",
        master_service_id: $('#Hdmaster_service_id').val(),
      //  service_name: crmname
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        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 {
                    $("#crmmapping_accordion").empty();
                    var j = 0, b = '';
                    var accordionContainerCRM = $("#crmmapping_accordion");
                    b = data1;
                  
                    $.each(b, function (i, emp) {
                        j++
                        crm_data.push(emp)
                        var collapseID = `collapse${j}`;
                        var empId = emp.Id;
                        accordionContainerCRM.append(`


                                <div class ="panel" style="margin-bottom: 10px !important;">
                                    <div class ="row d_flex accordion_header">
                                        <div class ="col-lg-6 col-md-6 col-sm-8 col-xs-10 d_flex_aic pl-0">
                                            <div class ="accordion_circle">P</div>
                                            <div class ="pl-10">
                                                <p class ="light_txt mb-0">FORM </p>
                                                <p class ="details_title mb-0">${emp.Name} </p>
                                            </div>
                                        </div>
                                        <div class ="col-lg-6 col-md-6 col-sm-4 col-xs-2 pr-0 accordion_icon">
                                          <i class ="fa fa-pencil pull-right" aria-hidden="true" data-toggle="modal" data-target="#crm_mapping_add" onclick="servicecrmedit('${empId}')"></i>
                                        </div>
                                    </div>
                                    <div id="${collapseID}" class ="collapse overall_body in">
                                        <div id="another_div"></div>
                                    </div>
                                </div>


                        `);
                    });
                }
            }
            else {
                console.log(data);
                $("#crmmapping_accordion").empty();
            }
        }
    });

}

function servicecrmedit(Id) {
    debugger;
    var values = {
        P_Dml_Indicator: "CRME",
        master_service_id: Id
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Service_Master_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data;

            $("#crm_mapping_name").val(emp[0].Name);
           // $("#crm_mapping_type").val(emp[0].TaskType);
            $("#crm_duedateindays").val(emp[0].DueDays);
            $("#crmtaskcreationtype").val(emp[0].TaskCreationType);
            $("#crm_taskcreationindays").val(emp[0].TaskCreationdays);
            $("#crmtaskpriotity").val(emp[0].TaskPriority);
            $("#crmmapping_description").val(emp[0].Description);
            $("#HCRMMapping").val(emp[0].Id);
            if (emp[0].IsClinical == 1) {
                $("#radio_Btn a[value='1']").removeClass("not_active").addClass("active");
                $("#radio_Btn a[value='2']").removeClass("active").addClass("not_active");
            } else if (emp[0].IsClinical == 2) {
                $("#radio_Btn a[value='1']").removeClass("active").addClass("not_active");
                $("#radio_Btn a[value='2']").removeClass("not_active").addClass("active");
            }
            if (emp[0].ServiceTypeId == 1) {
                $('.crmservicetype').html('Consulting')
            }
            else if (emp[0].ServiceTypeId == 2) {
                $('.crmservicetype').html('Work Order')
            }
            else if (emp[0].ServiceTypeId == 3) {
                $('.crmservicetype').html('Surgery')
            }
            else if (emp[0].ServiceTypeId == 4) {
                $('.crmservicetype').html('Misc')
            }
            else if (emp[0].ServiceTypeId == 5) {
                $('.crmservicetype').html('Procedure')
            }
            else {
                $('.crmservicetype').html('-')
            }

            var tasktype = emp[0].TaskType
            loadtasktype($('#Hdservice_type_id').val(), tasktype)

            LoadtaskCreationType(emp[0].TaskCreationType, tasktype)

            if (emp[0].TaskCreationType == 3) {
                $('#div_repeattype').show()
                $('#div_repeatday').show()
                $('#taskcreation_div').hide()
            }
            else if (emp[0].TaskCreationType == 2) {
                $('#taskcreation_div').hide()
            }
            else {
                $('#div_repeattype').hide()
                $('#div_repeatday').hide()
                $('#taskcreation_div').show()
            }

            $('#repeattype').val(emp[0].RepeatType)
            $('#repeatday').val(emp[0].RepeatDay)
            $('#crm_mapping_save').html('Update');
        }
    });
}

function CRMClear() {
    $('#crm_mapping_name').val('')
    $('#crm_mapping_type').val(0)
    $('#crm_duedateindays').val('')
    $('#crmtaskcreationtype').val(0)
    $('#crm_taskcreationindays').val('')
    $('#crmtaskpriotity').val(0)
    $('#crmmapping_description').val('')
    $('#radio_Btn a').removeClass('active').addClass('not_active');
    $('#repeattype').val(0)
    $('#repeatday').val('')
    $("#HCRMMapping").val('')
}
$('#AddCRM').click(function () {
    CRMClear();

    if ($('#Hdservice_type_id').val() == 1) {
        $('.crmservicetype').html('Consulting')
    }
    else if ($('#Hdservice_type_id').val() == 2) {
        $('.crmservicetype').html('Work Order')
    }
    else if ($('#Hdservice_type_id').val() == 3) {
        $('.crmservicetype').html('Surgery')
    }
    else if ($('#Hdservice_type_id').val() == 4) {
        $('.crmservicetype').html('Misc')
    }
    else if ($('#Hdservice_type_id').val() == 5) {
        $('.crmservicetype').html('Procedure')
    }
    else {
        $('.crmservicetype').html('-')
    }

    loadtasktype($('#Hdservice_type_id').val())
    $("#HCRMMapping").val('')
    $('#crm_mapping_save').html('Add')
});

function loadtasktype(type, tasktype) {
    debugger
    var data = {
        P_Dml_Indicator: 'LTT',
        consulting_type: type
    }
    $.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") {
                    $('#crm_mapping_type').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.Id + " >" + emp.TaskTypeName + "</option>"
                    })
                    $('#crm_mapping_type').append(default_option + option);

                    if (tasktype != '' || tasktype != null) {
                        $('#crm_mapping_type').val(tasktype)
                    }
                }
            }
        }
    })
}

$('#crm_mapping_type').change(function () {
    debugger
    var tasktype = $('#crm_mapping_type').val()
    LoadtaskCreationType(0,tasktype)
})

function LoadtaskCreationType(type,tasktype) {
    debugger
    var data = {
        P_Dml_Indicator: 'LTCT',
        consulting_type: tasktype
    }
    $.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") {
                    $('#crmtaskcreationtype').empty();
                    var option = "";
                    var data1 = data2.data;
                    var default_option = "<option value='0'>--Select--</option>";
                    $.each(data1, function (i, emp) {
                        option = option + "<option value=" + emp.TaskCreationId + " >" + emp.TaskTypeName + "</option>"
                    })
                    $('#crmtaskcreationtype').append(default_option + option);

                    if (type != '' || type != null) {
                        $('#crmtaskcreationtype').val(type)
                    }
                }
            }
        }
    })
}
//----CRM Mapping End---

//---Sale Start---

$('#btnmobilediscountAdd').click(function () {
    insertsales(1);
});
$('#btnwebdiscountadd').click(function () {
    insertsales(2);
});
$('#btnqrcodediscount').click(function () {
    insertsales(3);
});

function alwaysvalid(val) {
    debugger;
    if ($('#sales_always_valid_' + val + "").prop("checked") == true) {
        $("#sales_from_date_" + val + "").val('');
        $("#sales_from_date_" + val + "").prop("disabled", true);
        $("#sales_to_date_" + val + "").val('');
        $("#sales_to_date_" + val + "").prop("disabled", true);

    }
    else {
        $("#sales_from_date_" + val + "").prop("disabled", false);
        $("#sales_to_date_" + val + "").prop("disabled", false);
    }
}

function insertsales(val) {
    debugger;
    var chsales_always_valid = 0;
    if ($('#sales_always_valid_' + val + "").prop("checked") == true) {
        chsales_always_valid = 1;
    }
    if ($.trim($('#discount_' + val + "").val()) == 0 || $.trim($('#discount_' + val + "").val()) == '') {
        $('#Pdiscount').show();
        $('#Pdiscount').fadeOut(8000);
        $('#Pdiscount').html('Select Mobile Discount Type');
        $('#discount_' + val + "").focus();
        return false;
    }
    if ($.trim($('#amount_' + val + "").val()) == '') {
        $('#Pamount').show();
        $('#Pamount').fadeOut(8000);
        $('#Pamount').html('Enter Mobile Discount Amount');
        $('#amount_' + val + "").focus();
        return false;
    }
    if ($.trim($("#sales_from_date_" + val + "").val()).length == "" && chsales_always_valid == 0) {
        $('#Psales_from_date').show();
        $('#Psales_from_date').fadeOut(8000);
        $('#Psales_from_date').html('Select Active From Date');
        $("#sales_from_date_" + val + "").focus();
        $("#sales_from_date_" + val + "").val('');
        return false;
    }
    if ($.trim($("#sales_to_date_" + val + "").val()).length == "" && chsales_always_valid == 0) {
        $('#Psales_to_date').show();
        $('#Psales_to_date').fadeOut(8000);
        $('#Psales_to_date').html('Select Active To Date');
        $("#sales_to_date_" + val + "").focus();
        $("#sales_to_date_" + val + "").val('');
        return false;
    }

    var from_date = null, to_date = null;
    if ($("#sales_from_date_" + val + "").val() != '') {
        var date1 = $("#sales_from_date_" + val + "").val().split('/');
        from_date = date1[2] + '-' + date1[1] + '-' + date1[0];
    }
    if ($("#sales_to_date_" + val + "").val() != '') {
        var date2 = $("#sales_to_date_" + val + "").val().split('/');
        to_date = date2[2] + '-' + date2[1] + '-' + date2[0]
    }

    var Status
    if ($("#mobdiscountenables").prop("checked") || $("#webdiscountenables").prop("checked") || $("#qrdiscountenables").prop("checked")) {
        Status = 1;
    } else {
        Status = 0
    }
    var uploadfile = $("#hformimg_" + val + "").val()
    var addData = {
        Dml_Indicator: "IS",
        masterserviceid: $("#Hdmaster_service_id").val(),
        DiscountTypeId: val,
        DiscountType: $("#discount_" + val + "").val(),
        DiscountValue: $("#amount_" + val + "").val(),
        ActiveForm: from_date,
        ActiveTo: to_date,
        FilePath: uploadfile,
        Status: Status,
        AlwaysValid: $("#sales_always_valid_" + val + "").prop('checked')
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceSales_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(addData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;
                if (data2[0].Message == 'Inserted') {
                    toastr.success('Inserted Successfully');
                } else {
                    toastr.error('Something Went Wrong');
                }
            }
        },
        error: function () {
            toastr.error('Something Went Wrong');
        }
    });

}


function SalesServiceimageupload(val) {
    debugger;
    var uploadpath = $("#sales_image_" + val + "").val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (fileExtension == "png" || fileExtension == "PNG") {
    }
    else {
        $('#Psales_image').show();
        $('#Psales_image').fadeOut(8000);
        $('#Psales_image').html('Please upload file having extensions .png only.');
        $('#Psales_image').val('');
        $('#Psales_image').focus();
        return false;
    }
    if (window.FormData !== undefined) {
        var fileUpload = $("#sales_image_" + val + "").get(0);
        var files = fileUpload.files;
        var fileData = new FormData();

        $.when(checkimagedimensionvalidation(fileUpload.files[0], 240, 256)).
        done(function (Results) {
            if (Results == 'Success') {
                for (var i = 0; i < files.length; i++) {
                    fileData.append(files[i].name, files[i]);

                }
                fileData.append('username', 'Manas');
                $.ajax({
                    url: '/Form_builder/UploadPhotoFiles',
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: fileData,
                    success: function (result) {
                        $.each(result, function (i, emp) {
                            $('#profile-photo_' + val).empty();
                            $('#profile-photo_' + val).show();
                            var d, n, drloimage;
                            d = new Date();
                            n = d.getTime();
                            drloimage = $('#hdnCDfilepath').val() + $('#HospitalId').val() + '/FormBuilderFileUpload/' + emp + '?' + n;
                            $('#profile-photo_' + val).append('<a href="' + drloimage + '" target="_blank" id="SalesImage_"' + val + '">Image</a>');
                            $('#hformimg_' + val).val(emp);

                        });
                    }
                });
            }
            else {
                $('#sales_image_' + val).val('');

            }
            //this code is executed when all ajax calls are done
        });

    }
}



//Edit
function editSales(masterserviceid) {
    $('#div_mobilediscountenable').removeClass('hidden');
    debugger;
    var sales = {
        masterserviceid: $('#Hdmaster_service_id').val(),
        Dml_Indicator: "E"
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceSales_Ins_upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(sales),
        success: function (data) {
            debugger;
            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 {

                    var b = '', j = '', val = 0;
                    b = data1;
                    $.each(b, function (i, emp) {
                        j++;

                        if (emp.DiscountTypeId == 1) {
                            val = 1
                            $('#mobdiscountenables').prop('checked', true)
                            $('#mobdiscountenable').show();
                        }
                        else if (emp.DiscountTypeId == 2) {
                            val = 2
                            $("#webdiscountenables").prop("checked", true)
                            $('#webdiscountenable').show();
                        }
                        else if (emp.DiscountTypeId == 3) {
                            val = 3
                            $("#qrdiscountenables").prop("checked", true)
                            $('#qrdiscountenable').show();
                        }
                        else {
                            $('#mobdiscountenable').hide();
                            $('#webdiscountenable').hide();
                            $('#qrdiscountenable').hide();
                        }
                        if (emp.AlwaysValid == 1) {
                            $("#sales_from_date_" + val + "").prop("disabled", true);
                            $("#sales_to_date_" + val + "").prop("disabled", true);
                            $("#sales_always_valid_" + val + "").prop("checked", true)
                        }
                        else {
                            $("#sales_always_valid_" + val + "").prop("checked", false)

                        }

                        $("#sales_from_date_" + val + "").val(emp.ActiveForm);
                        $("#sales_to_date_" + val + "").val(emp.ActiveTo);
                        $("#sales_always_valid_" + val + "").val(emp.AlwaysValid);
                        $("#amount_" + val + "").val(emp.DiscountValue);
                        $("#discount_" + val + "").val(emp.DiscountType);
                        $('#profile-photo_' + val).empty();
                        $('#profile-photo_' + val).show();
                        var d, n, drloimage;
                        d = new Date();
                        n = d.getTime();
                        drloimage = $('#hdnCDfilepath').val() + $('#HospitalId').val() + '/FormBuilderFileUpload/' + emp.FilePath + '?' + n;
                        $('#profile-photo_' + val).append('<a href="' + drloimage + '" target="_blank" id="SalesImage_"' + val + '">Image</a>');
                        $('#hformimg_' + val).val(emp.FilePath);


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

}
// --- Sales End-----

function servicestepperclick(n) {
    debugger;
    if ($('#Hdmaster_service_id').val() != '') {
        var x = document.getElementsByClassName("stepper_tab");

        x[currentTab].style.display = "none";
        currentTab1 = currentTab;
        currentTab = n;

        if ($('#Hdservice_type_id').val() == 1) {
            if (currentTab == 1) {
                toastr.warning('Form mapping is not allowed for Consultation Service');
                currentTab = currentTab1;
            }
        }
    }
        

    showTab(currentTab);
    var ids = ['#servicetypeval', '#servicetypeval1', '#servicetypeval2', '#servicetypeval3'];
    if ($('#Hdservice_type_id').val() == 1) {
        ids.forEach(function (id) {
            $(id).html('Consulting');
        });
    }
    else if ($('#Hdservice_type_id').val() == 2) {
        ids.forEach(function (id) {
            $(id).html('Work Order');
        });
    }
    else if ($('#Hdservice_type_id').val() == 3) {
        ids.forEach(function (id) {
            $(id).html('Surgery');
        });
    }
    else if ($('#Hdservice_type_id').val() == 4) {
        ids.forEach(function (id) {
            $(id).html('MISC');
        });
    }
    else if ($('#Hdservice_type_id').val() == 5) {
        ids.forEach(function (id) {
            $(id).html('Procedure');
        });
    }
}

function Servicenext(n) {
    debugger
    $('#crm_mapping_search').val('')
    if ($('#Hdmaster_service_id').val() != '' || $('#btnsubmit').html() == 'Update') {
        var x = document.getElementsByClassName("stepper_tab");
        debugger;
        x[currentTab].style.display = "none";

        currentTab = currentTab + n;

        if ($('#Hdservice_type_id').val() == 1) {
            if (n == 1 && currentTab == 1) {
                currentTab = 2;
            }
            else if (n == -1 && currentTab == 1) {
                currentTab = 0;
            }
           // toastr.warning('Form mapping is not allowed for Consultation Service');
        }
        if ($('#service_name').val() != '') {
            var service = $('#Hdmaster_service_id').val()
            $('#btnsubmit').html('Update')
            $("#master_service_id").val(service)
        }
        if (currentTab >= x.length) {

            return false;
        }


        showTab(currentTab);

        var ids = ['#servicetypeval', '#servicetypeval1', '#servicetypeval2', '#servicetypeval3'];
        if ($('#Hdservice_type_id').val() == 1) {         
            ids.forEach(function (id) {
                $(id).html('Consulting');
            });
        }
        else if ($('#Hdservice_type_id').val() == 2) {
            ids.forEach(function (id) {
                $(id).html('Work Order');
            });
        }
        else if ($('#Hdservice_type_id').val() == 3) {
            ids.forEach(function (id) {
                $(id).html('Surgery');
            });
        }
        else if ($('#Hdservice_type_id').val() == 4) {
            ids.forEach(function (id) {
                $(id).html('MISC');
            });
        }
        else if ($('#Hdservice_type_id').val() == 5) {
            ids.forEach(function (id) {
                $(id).html('Procedure');
            });
        }
    }
    else {
        toastr.warning("Sorry, there is no service created.");
    }

}
$('.typeofservice').click(function () {
    debugger;
    var selectedValue = $(this).attr('value');
    $('#Hdservice_type_id').val(selectedValue)
    if (selectedValue == 1 || selectedValue == 3 || selectedValue == 4 || selectedValue == 5) {
        $('#loadctubecontainer').val(0)
        $('#method_name').val('')
        $('#lab_type').val('')
        $('#sType').val(0)
        $('#pname').val('')
        $('#rvalue').val('')
        $('#unit').val('')
        $('#txt_dis_order').val('')
        $('#testNotes').val('')
        $('#typeofservicelab').prop('checked', false)
        $('#isexternal').prop('checked', false)
        $('#external_div').addClass('hidden');
        $('#mobile_div').removeClass('hidden');
    } else {
        $('#external_div').removeClass('hidden');
        //$('#mobile_div').removeClass('hidden');

    }
    if (selectedValue == 3) {
        $('#div_doctor_enable').addClass('hidden');
    }
    else {
        $('#div_doctor_enable').removeClass('hidden');

    }
    $('#consulting_type').val(0)
    $('#consultation_type').val(0)
    $('#SelDoctor').val('')
    $('#is_doctor_enable').val(0)
    $('#refund_scenario').val(2)
});



function serviceconsunabledit() {
    debugger;
    var values = {
        Dml_Indicator: "CE",
        PackageId: $("#HPackage_id").val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/Serviceconsumable',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(values),
        success: function (data) {
            debugger;
            console.log(data);
            var data3 = JSON.parse(data);
            if (jQuery.isEmptyObject((data3)) || data3.data === 'Records Not Found') {
            }
            else {
               
                var emp = data3.data;
                $('#isconsumables').prop('checked', true);
                $('#consumables').show();

                var trow = '';
                for (var i = 0; i < emp.length; i++) {
                    var Id = emp[i].Id
                    var ServiceId = emp[i].PackageId;
                    var ItemId = emp[i].ItemId;
                    //  var ItemCode = data1[0].ItemCode.split(',');
                    var ItemName = emp[i].ItemName;
                    var Quantity = emp[i].Quantity;
                    // var Tax = data1[0].Tax.split(',');
                    // var Mrp = data1[0].Mrp.split(',');
                    var sts = emp[i].IsActive;
                    $('#tbl_consumables tbody').empty();
                    //var arr = [];
                    if (emp[i].IsActive == true) {
                        if ($.trim(emp[i].IsActive) == 'true') {
                            trow += '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId) + '><td id=item_id_' + (i + 1) + '>' + $.trim(ItemId) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity) + '<td id="consumables_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick="consumables_del(' + (i + 1) + ', \'' + $.trim(Id) + '\')"><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-edit btn-xs" onclick="consumables_edit(' + (i + 1) + ', \'' + $.trim(Id) + '\',\'' + $.trim(ItemName) + '\',\'' + $.trim(Quantity) + '\',\'' + $.trim(ItemId) + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></span></td></tr>';
                        } else {
                            trow += '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId) + '><td id=item_id_' + (i + 1) + '>' + $.trim(ItemId) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity) + '<td id="consumables_action_' + (i + 1) + '"><span class="btn deleteicon-btn btn-xs" onclick="consumables_del(' + (i + 1) + ', \'' + $.trim(Id) + '\')"><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-edit btn-xs" onclick="consumables_edit(' + (i + 1) + ', \'' + $.trim(Id) + '\',\'' + $.trim(ItemName) + '\',\'' + $.trim(Quantity) + '\',\'' + $.trim(ItemId) + '\')"><i class="fa fa-pencil" aria-hidden="true"></i></span></td></tr>';
                        }
                    } else {
                        trow += '<tr id=Item_' + (i + 1) + ' data-id=' + $.trim(ItemId) + '><td id=item_id_' + (i + 1) + '>' + $.trim(ItemId) + '<td id=con_name_' + (i + 1) + '>' + $.trim(ItemName) + '<td id=con_quan_' + (i + 1) + '>' + $.trim(Quantity) + '<td id="consumables_action_' + (i + 1) + '"><span class="label label-warning">Consumable Inactived</span></td></tr>';
                    }

                    $("#tbl_consumables tbody").append(trow);


                }
                $('#store_name').attr('disabled', true);
                $('#btn_consumables_Add').html('Update')
            }
        
        }
    });
}

function consumables_edit(i,id, name, qty, itemid) {
    debugger  
    $('#item_name').val(name)
    $('#item_name').attr('disabled', true);
    $('#quantity').val(qty)
}

function consumables_del(i, id) {
    debugger;
    if ($('#master_service_id').val() == '') {
        $('#Item_' + i).remove();
    }
    else {
        var status = "";
       // if (flag == 0) {
            status = "Are You Sure, You Want to Delete the Consumables?";
        //}

        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 () {
                          var data = {
                              Dml_Indicator: 'CD',
                              Id: id,
                          }
                          return $.ajax({
                              async: true,
                              type: 'POST',
                              url: '/Billing/Serviceconsumable',
                              contentType: 'application/json; charset=UTF-8',
                              data: JSON.stringify(data),
                              success: function (data) {
                                  debugger;
                                  $('#Item_' + i).remove();
                                  var data2 = JSON.parse(data);

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

                                  }
                                  else {

                                      if (data2.msg == "Success") {
                                          var data1 = data2.data[0];
                                          var tr = ''
                                          if (data1.status == 'success') {
                                             // if (flag == 0) {
                                                 // $('#Item_' + i).remove();
                                           //   }
                                              //else if (flag == 2) {
                                              //    $('#consumables_action_' + id).empty();
                                              //    tr = '<span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn btn-blue  btn-xs" title="Make Active" onclick=consumables_chk(' + (id) + ',1) ><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></span>'
                                              //    $('#consumables_action_' + id).append(tr);
                                              //}
                                              //else {
                                              //    $('#consumables_action_' + id).empty();
                                              //    tr = '<span class="btn deleteicon-btn btn-xs" onclick=consumables_chk(' + (id) + ',0) ><i class="fa fa-trash-o" aria-hidden="true"></i></span><span class="btn  btn-blue  btn-xs" title="Make Inactive" onclick=consumables_chk(' + (id) + ',2) ><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></span>'
                                              //    $('#consumables_action_' + id).append(tr);
                                              //}
                                          }
                                          else {
                                              toastr.warning('User Mapped already');
                                              //var arr = $('#external_lab').val();
                                              //arr.push(id);
                                              //$('#external_lab').val(arr).change();
                                          }

                                      }
                                  }
                              }
                          })
                      })
                  }
              })

    }
}