var crm_data = []
var smsflag = ''
var smsfield = ''
$(document).ready(function () {
    debugger;

    Hideshow()
    //  CheckCodeTemplate() //one master concept

    // LoadBranch(); //one master concept
    //package_dashboard();
    sessionStorage.clear();

    LoadCategory(0);
    LoadFilterDepartment();
    loadservice_type()
    table_package();
    SchemEntityName()


    // LoadCRMmappingTable()
    // loadCampaigndata();
    // editDiscount();
})


//CheckCodeTemplate
function CheckCodeTemplate() {
    debugger;
    var codeData = {
        //Dml_Indicator: "CT",
        Dml_Indicator: "BCT",
        hospital_id: $('#HospitalId').val(),
        // branch_id: $('#pkg_branch_id').val() //one master concept
        //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('' + $('#pkg_branch_id  option:selected').html() + ' Not Added Code Template. Please Add the Code Template at SetupIds');
                alert('Not Added Code Template. Please Add the Code Template at SetupIds');

                window.location.href = "/Hospitalsetup"
            }
            else {
                //LoadBranch()
                LoadCategory(0);
                LoadFilterDepartment();
                loadservice_type()
                table_package();
            }

        }
    });
}

//Terms and Condition Table binding
$('#btnDPackagetc').click(function () {
    if ($('#DPackagetc').val().length > 0) {
        var input = '';
        var val = $('#DPackagetc').val();
        $('#DPackagetc').val(input);
        var id = "tnctr" + $('#termsandconditions')[0].rows.length;
        row_data = "<tr id=" + id + "><td class='tc_name'>" + val + "</td><td><span class='btn deleteicon-btn btn-xs' id='delPacktc' onclick=delPacktc('" + id + "')><i class='fa fa-trash-o' aria-hidden='true'></i></span></td>";
        $('#termsandconditions').append(row_data);
    }
    else {
        $('#PDPackagetc').show();
        $('#PDPackagetc').fadeOut(8000);
        $('#PDPackagetc').html('Enter Terms & Conditions');
        $('DPackagetc').focus();
    }
});
//Terms and Condition delete
function delPacktc(id) {
    //var check = confirm("Are you sure?");
    //if (check) $("#" + id).remove()
    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 want to delete?',
        {
            closeButton: true,
            progressBar: true,
            allowHtml: true,
            timeOut: 20000000,

            onShown: function (toast) {
                $("#confirmationRevertYes").click(function () {
                    $("#" + id).remove()
                })
                $("#confirmationRevertNo").click(function () {

                })
            }
        })

}
//Service Table Binding
$('#pkg_add_service').click(function () {
    debugger;
    if ($('#Hmaster_service_id').val() == '' || $('#Hmaster_service_id').val() == 0 || $('#pkg_service_id').val() == '') {
        $('#Ppkg_service_id').show();
        $('#Ppkg_service_id').fadeOut(8000);
        $('#Ppkg_service_id').html('Select Service Name');
        $('pkg_service_id').focus();
        return false;
    }
    if ($('#pkg_service_usage').val() == '' || $('#pkg_service_usage').val() == 0) {
        $('#Ppkg_service_usage').show();
        $('#Ppkg_service_usage').fadeOut(8000);
        $('#Ppkg_service_usage').html('Enter the number of usage');
        $('pkg_service_usage').focus();
        return false;
    }
    else {
        var ser_name = $("#pkg_service_id").val();
        var ser_id = $("#Hmaster_service_id").val();
        var ser_code = $('#pkg_service_code').val();
        var ser_base_amt = $('#pkg_base_amount').val();
        var num_use = $('#pkg_service_usage').val();
        var sess_key;
        var rowcount = $.trim($('#ServiceTableRowCount').val());
        var tot_row = (Number(rowcount) + 1);
        var sess_data_ser = ser_name + "," + ser_code + "," + ser_base_amt + "," + num_use;
        var afterInc = '';
        var key = '';

        if ($('table#pkg_service').find('#' + ser_id).length == 0) {
            var value = "<tr id=" + ser_id + "><td>" + ser_name + "</td><td>" + ser_code + "</td><td>" + ser_base_amt + "</td><td>" + num_use + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + ser_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + ser_id + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
        }
        else {
            $('#Ppkg_service_id').show();
            $('#Ppkg_service_id').fadeOut(8000);
            $('#Ppkg_service_id').html('Service Name already selected');
            $('#pkg_service_id').focus();
            //$('#pkg_service_id').val('');
            return false;
        }
        sessionStorage.setItem(ser_id, sess_data_ser);
        $('#pkg_service > tbody:last').append(value);
        //$('#pkg_service').DataTable();
        $('#ServiceTableRowCount').val(tot_row);
        $('#pkg_service_id').val('');
        $('#pkg_service_code').val('');
        $('#pkg_base_amount').val('');
        $('#pkg_service_usage').val('');
        $('#Hmaster_service_id').val('');
    }
})

//Service Table Delete
function Servicedelete(id) {
    sessionStorage.removeItem(id);
    $('#' + id).remove();
    var rowcount = $.trim($('#ServiceTableRowCount').val());
    rowcount = rowcount - 1;
    $('#ServiceTableRowCount').val(rowcount);
}
//Service Table Edit
function serviceedit(id) {
    debugger;
    $('#package_service').addClass('in');
    $('#pkg_add_service').hide();
    $('#pkg_update_service').show();
    $('#service_table_id').val(id);

    var gkey = id;
    var row_data = sessionStorage.getItem(gkey);
    var row_data_split = row_data.split(',');
    $('#pkg_service_id').val(row_data_split[0]);
    $('#Hmaster_service_id').val(id);
    $('#pkg_service_code').val(row_data_split[1]);
    $('#pkg_base_amount').val(row_data_split[2]);
    $('#pkg_service_usage').val(row_data_split[3]);
    $('#pkg_service_id').attr('disabled', true);
}
//Service Table Update
$('#pkg_update_service').click(function () {
    debugger;
    if ($('#pkg_service_usage').val() == '' || $('#pkg_service_usage').val() == 0) {
        $('#Ppkg_service_usage').show();
        $('#Ppkg_service_usage').fadeOut(8000);
        $('#Ppkg_service_usage').html('Enter the number of usage');
        $('pkg_service_usage').focus();
        return false;
    }
    var ser_name = $("#pkg_service_id").val();
    var ser_id = $("#Hmaster_service_id").val();
    var ser_code = $('#pkg_service_code').val();
    var ser_base_amt = $('#pkg_base_amount').val();
    var num_use = $('#pkg_service_usage').val();
    var sess_data_ser = ser_name + "," + ser_code + "," + ser_base_amt + "," + num_use;
    sessionStorage.setItem(ser_id, sess_data_ser);
    $('#pkg_service > tbody:last').empty();
    var tot_row = 0;
    for (let i = 0; i < sessionStorage.length; i++) {
        const key = sessionStorage.key(i);
        var row_data = sessionStorage.getItem(key);
        if (row_data != null) {
            row_data = row_data.split(',');
            var value = "<tr id=" + key + "><td>" + row_data[0] + "</td><td>" + row_data[1] + "</td><td>" + row_data[2] + "</td><td>" + row_data[3] + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + key + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + key + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
            $('#pkg_service > tbody:last').append(value);
            tot_row = tot_row + 1;
        }
        $('#ServiceTableRowCount').val(tot_row);
        $('#pkg_service_id').val('');
        $('#Hmaster_service_id').val('');
        $('#pkg_service_code').val('');
        $('#pkg_base_amount').val('');
        $('#pkg_service_usage').val('');
        $('#pkg_service_id').attr('disabled', false);
    }
    $('#pkg_update_service').hide();
    $('#pkg_add_service').show();
})
//Package File Upload
$('#pkgimgClick').click(function () {
    $('#packageimage').click();
})
$('#packageimage').change(function () {
    packageimageupload();
});


function packageimageupload() {
    debugger;
    //  var branch_id = $('#pkg_branch_id').val(); //one master
    var uploadpath = $('#packageimage').val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $("#packageimage").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 fileData = new FormData();
        var filePath = fileUpload.value;
        var allowedExtensions =
            /(\.jpg|\.jpeg|\.png)$/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], 1024, 512)).
            done(function (Results) {
                debugger;
                if (Results == 'Success') {

                    for (var i = 0; i < files.length; i++) {
                        fileData.append(files[i].name, files[i]);
                    }
                    fileData.append('username', 'Manas');

                    $.ajax({
                        // url: '/PackageDetails/UploadPackageImage?branch_id=' + branch_id + '',//one master concept
                        url: '/PackageDetails/UploadPackageImage',
                        type: "POST",
                        contentType: false,
                        processData: false,
                        data: fileData,
                        success: function (result) {
                            $.each(result, function (i, emp) {
                                $('#photolog').empty();
                                var d, n, drloimage;
                                d = new Date();
                                n = d.getTime();
                                //drloimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/' + $('#pkg_branch_id').val() + '/Package/' + emp + '?' + n;
                                drloimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/Package/' + emp + '?' + n;

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

                                $('#photolog').append('<a href=" ' + drloimage + '" target="_blank" class="another-eye">View</a>');
                                $('#packimageid').val(emp);
                            });
                        }
                    });
                }
                else {
                    $('#packimageid').val('');
                    $('#photolog').empty();
                }  //this code is executed when all ajax calls are done
            });
    }
}
//Package Always Valid Change Function
$('#package_Never_Expiry').change(function () {
    if ($('#package_Never_Expiry').prop("checked") == true) {
        $('#pkg_from_date').val('');
        $("#pkg_from_date").prop("disabled", true);
        $('#pkg_to_date').val('');
        $("#pkg_to_date").prop("disabled", true);
    }
    else {
        $("#pkg_from_date").prop("disabled", false);
        $("#pkg_to_date").prop("disabled", false);
    }
})
//Insert Package /Update Package-Form Validation
$('#btnAddPackage').click(function () {
    debugger;
    if ($.trim($('#is_surgical').val()) == "") {
        $('#Pis_surgical').show();
        $('#Pis_surgical').fadeOut(8000);
        $('#Pis_surgical').html('Select the package For');
        $('#is_surgical').focus();
        $('#is_surgical').val('');
        return false;
    }
    if ($.trim($('#packagename').val()).length == "") {
        $('#Ppackagename').show();
        $('#Ppackagename').fadeOut(8000);
        $('#Ppackagename').html('Enter Package Name');
        $('#packagename').focus();
        $('#packagename').val('');
        return false;
    }
    if ($.trim($('#pkg_short_name').val()).length == "") {
        $('#Ppkg_short_name').show();
        $('#Ppkg_short_name').fadeOut(8000);
        $('#Ppkg_short_name').html('Enter Short Name');
        $('#pkg_short_name').focus();
        $('#pkg_short_name').val('');
        return false;
    }

    if ($.trim($('#pkg_department').val()) == "" || $('#pkg_department').val() == '0') {
        $('#Ppkg_department').show();
        $('#Ppkg_department').fadeOut(8000);
        $('#Ppkg_department').html('Select Department');
        $('#pkg_department').focus();
        $('#pkg_department').val('');
        return false;
    }
    if ($.trim($('#pkg_sub_department').val()) == "" || $('#pkg_sub_department').val() == '0') {
        $('#Ppkg_sub_department').show();
        $('#Ppkg_sub_department').fadeOut(8000);
        $('#Ppkg_sub_department').html('Select Sub Department');
        $('#pkg_sub_department').focus();
        $('#pkg_sub_department').val('');
        return false;
    }

    if ($.trim($('#pkg_category').val()) == "" || $('#pkg_category').val() == '0') {
        $('#Ppkg_category').show();
        $('#Ppkg_category').fadeOut(8000);
        $('#Ppkg_category').html('Select Category');
        $('#pkg_category').focus();
        $('#pkg_category').val('');
        return false;
    }
    if ($.trim($('#pkg_sub_category').val()) == "" || $('#pkg_sub_category').val() == '0') {
        $('#Ppkg_sub_category').show();
        $('#Ppkg_sub_category').fadeOut(8000);
        $('#Ppkg_sub_category').html('Select Sub Category');
        $('#pkg_sub_category').focus();
        $('#pkg_sub_category').val('');
        return false;
    }
    if ($.trim($('#package_type').val()) == "" || $('#package_type').val() == '0') {
        $('#Ppackage_type').show();
        $('#Ppackage_type').fadeOut(8000);
        $('#Ppackage_type').html('Enter Package Type');
        $('#package_type').focus();
        $('#package_type').val('');
        return false;
    }
    var chpackage_Never_Expiry = 0;
    if ($('#package_Never_Expiry').prop("checked") == true) {
        chpackage_Never_Expiry = 1;
    }
    if ($.trim($('#pkg_from_date').val()).length == "" && chpackage_Never_Expiry == 0) {
        $('#Ppackage_from_date').show();
        $('#Ppackage_from_date').fadeOut(8000);
        $('#Ppackage_from_date').html('Select Valid From Date');
        $('#pkg_from_date').focus();
        $('#pkg_from_date').val('');
        return false;
    }
    if ($.trim($('#pkg_to_date').val()).length == "" && chpackage_Never_Expiry == 0) {
        $('#Ppackage_to_date').show();
        $('#Ppackage_to_date').fadeOut(8000);
        $('#Ppackage_to_date').html('Select Valid To Date');
        $('#pkg_to_date').focus();
        $('#pkg_to_date').val('');
        return false;
    }
    if ($.trim($('#packagevalidity').val()).length == "") {
        $('#Ppackagevalidity').show();
        $('#Ppackagevalidity').fadeOut(8000);
        $('#Ppackagevalidity').html('Enter Validity days');
        $('#packagevalidity').focus();
        $('#packagevalidity').val('');
        return false;
    }
    if ($.trim($('#pkg_base_type').val()) == "" || $('#pkg_base_type').val() == '0') {
        $('#Ppkg_base_type').show();
        $('#Ppkg_base_type').fadeOut(8000);
        $('#Ppkg_base_type').html('Select Base Amount Type');
        $('#pkg_base_type').focus();
        $('#pkg_base_type').val('');
        return false;
    }
    if ($.trim($('#packageprice').val()).length == "") {
        $('#Ppackageprice').show();
        $('#Ppackageprice').fadeOut(8000);
        $('#Ppackageprice').html('Enter Package Price');
        $('#packageprice').focus();
        $('#packageprice').val('');
        return false;
    }
    
    if ($('#is_surgical').val() == "") {
        $('#Pis_surgical').show();
        $('#Pis_surgical').fadeOut(8000);
        $('#Pis_surgical').html('Select Surgical');
        $('#is_surgical').focus();
        $('#is_surgical').val('');
        return false;
    }
  //  if ($('#is_surgical').val() != 1 && parseInt($('#mobile_view').val()) == 1) {
        //if ($.trim($('#DPackagehighlights').val()).length == "") {
        //    $('#PDPackagehighlights').show();
        //    $('#PDPackagehighlights').fadeOut(8000);
        //    $('#PDPackagehighlights').html('Enter Package Highlights');
        //    $('#DPackagehighlights').focus();
        //    $('#DPackagehighlights').val('');
        //    return false;
        //}
        //if ($.trim($('#DPackagedescription').val()).length == "") {
        //    $('#PDPackagedescription').show();
        //    $('#PDPackagedescription').fadeOut(8000);
        //    $('#PDPackagedescription').html('Enter Package Description');
        //    $('#DPackagedescription').focus();
        //    $('#DPackagedescription').val('');
        //    return false;
        //}
   // }

    package_details_insert_update_delete();

})
//Insert and Update Package
function package_details_insert_update_delete() {
    debugger;
    $('#shade_slot').show();
    var object = {
        hightight: "",
        description: "",
        salesText: "",
        tmc: []
    }
    $('.tc_name').each(function () {
        var name3 = $(this).text();
        object.tmc.push(name3);
    });
    if ($.trim($('#DPackagehighlights').val()).length > 0) {
        object.hightight = $('#DPackagehighlights').val();
    }
    if ($.trim($('#DPackagedescription').val()).length > 0) {
        object.description = $('#DPackagedescription').val();
    }
    if ($.trim($('#DPackagedescriptionsalestext').val()).length > 0) {
        object.salesText = $('#DPackagedescriptionsalestext').val();
    }
    var msg = ''
    if ($('#btnAddPackage').html() == "Update Package") {
        indicator = "PDU";
        indicator_ser = 'SU';
        msg = 'Package Updated Successfully'
    }
    else {
        indicator = "PDI";
        indicator_ser = 'SI';
        msg = 'Package Saved Successfully'
    }
    var package_Never_Expiry = 0;
    if ($('#package_Never_Expiry').prop("checked") == true) {
        package_Never_Expiry = 1;
    }
    var from_date = null, to_date = null;
    if ($('#pkg_from_date').val() != '') {
        var date1 = $('#pkg_from_date').val().split('/');
        from_date = date1[2] + '-' + date1[1] + '-' + date1[0];
    }
    if ($('#pkg_to_date').val() != '') {
        var date2 = $('#pkg_to_date').val().split('/');
        to_date = date2[2] + '-' + date2[1] + '-' + date2[0]
    }
    var Hdsurgical = $('#is_surgical').val()
    $('#Hdservice_type_id').val(Hdsurgical)

    var package_data = {
        package_name: $('#packagename').val(),
        package_id: $('#package_id').val(),
        package_image_url: $('#packimageid').val(),
        // branch_id: $('#pkg_branch_id').val(),//one master concept
        master_category_id: $('#pkg_category').val(),
        master_sub_category_id: $('#pkg_sub_category').val(),
        master_department_id: $('#pkg_department').val(),
        sub_department_id: $('#pkg_sub_department').val(),
        validity_from_date: from_date,
        validity_to_date: to_date,
        price: $('#packageprice').val(),
        discount: $('#package_discount').val(),
        discount_type: $('#pack_dist_type').val(),
        display_onMobile: $('#mobile_view').val(),
        remarks: $('#remarks').val(),
        highlight_description: JSON.stringify(object),
        doctor_id: $('#HiddenDoctorID').val(),
        never_expiry: package_Never_Expiry,
        package_type: $('#package_type').val(),
        indicator_id: indicator,
        validity_period_date: $('#packagevalidity').val(),
        is_surgical: $('#is_surgical').val(),
        is_activate: $('#is_activate').val(),
        pkg_short_name: $('#pkg_short_name').val(),
        base_amount_type: $('#pkg_base_type').val(),
        range_min: $('#range_min').val(),
        range_max: $('#range_max').val(),
        status: $('#status').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) {
            var data1 = JSON.parse(data);
            console.log(data1);
            $('#shade_slot').hide();
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var b = data1.Table;
                    $('#Hdpserviceid').val(b[0].Service_master)
                    $('#Hdpackageid').val(b[0].packageid);
                    if (b[0].msg == "already") {
                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'The Entered Package Name Already Exists',
                            {
                                closeButton: true,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 20000000,

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

                    }
                    else {
                        toastr.success(msg,
                            {
                                closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            })
                        setTimeout(function () {
                            //  location.reload();
                        }, 2000);
                    }
                    if ($('#Hdpackageid').val() != '') {
                        Servicenext(1);
                    }
                    else {
                        toastr.warning("Sorry, there is no service created.");
                    }
                }              
            }
            else {
                console.log(data1);
            }
        },
    });
}
function servicemapping() {
    debugger;
    var service = [];
    var pac_id = $('#Hdpackageid').val();
    var msg = ''
    if ($('#service_Submit').html() == "Update") {
        indicator_ser = 'SU';
        msg = 'Service Updated Successfully'
    }
    else {
        indicator_ser = 'SI';
        msg = 'Service Inserted Successfully'
    }
    //var pac_id = b[0].packageid;
    debugger;
    var tot_rowM = $.trim($('#ServiceTableRowCount').val());
    if (tot_rowM > 0) {
        var L = 0;
        for (j = 1; j <= tot_rowM; j++) {
            var service_data = {}
            debugger;
            var a = $('#pkg_service tbody').children('tr').eq(L);
            var b = a.prop('id');
            L++;
            var C = b.split('_');
            var gkey = C[0];
            var row_data = sessionStorage.getItem(gkey);
            var K = 0;
            if (row_data == "") {
                console.log(gkey + '--------->' + row_data);
            }
            if (row_data != "" && row_data != null) {
                console.log(gkey + '-------' + row_data);
                row_data = row_data.split(',');


                service_data.master_service_id = gkey,
                    service_data.no_of_services = row_data[3],
                    service_data.package_id = pac_id,
                    service_data.indicator_id = indicator_ser
                service_data.user_created_by = $('#hiddenUser_id').val()

            }
            console.log(service.push(service_data));

        }
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_service',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service),
        success: function (data3) {
            var data1 = JSON.parse(data3);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                var HdserviceId = data1.Table[0].master_service_id
                $('#Hmaster_service_id').val(HdserviceId)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    toastr.success(msg,
                        {
                            closeButton: false,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 0,
                        })
                    setTimeout(function () {
                        //  location.reload();
                    }, 2000);
                }
                Servicenext(1)
            }
            else {
                console.log(data1);
            }
        }
    })
}

$('#service_Submit').click(function () {
    debugger
    //if ($('#pkg_service  >tbody >tr').length == 0) {
    //    $('#Ppkg_service_id').show();
    //    $('#Ppkg_service_id').fadeOut(8000);
    //    $('#Ppkg_service_id').html('Select Service Name');
    //    $('pkg_service_id').focus();
    //    return false;
    //}
    //else {
    servicemapping()
    // }
})

$('#packageprice').change(function () {
    debugger;
    if ($('#pkg_base_type').val() == 3) {
        var range_min = $('#range_min').val();
        var range_max = $('#range_max').val();
        var base_value = $('#packageprice').val();
        if ($.trim((range_min)) == "") {
            $('#Prange_min').show();
            $('#Prange_min').fadeOut(8000);
            $('#Prange_min').html('Enter Range Min');
            $('#packageprice').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');
            $('#packageprice').val('');
            //$('#range_max')[0].scrollIntoView(true);
            return false;
        }
        else {
            if (parseFloat(base_value) >= parseFloat(range_min) && parseFloat(base_value) <= parseFloat(range_max)) {

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

        }
    }

})
$('#pkg_base_type').change(function () {
    debugger;

    var baseinput = $('#pkg_base_type').val()
    $('#Hbase_input').val(baseinput)
    if (basetype == 1 || basetype == 3) {
        //$("#packageprice").attr('disabled', false);
    }
    else {
        // $("#packageprice").attr('disabled', true);
    }
    var basetype = $('#pkg_base_type').val();
    if (basetype == 1 || basetype == 3) {
        $('#activate_div').addClass('hidden');
        $('#is_activate').prop('checked', false);
        $('#is_activate').val(2);
    }
    else {
        $('#activate_div').removeClass('hidden');
    }
    if (basetype == 3) {
        $('.ranges1').show();
    }
    else if (basetype == 1 || basetype == 2) {
        $('.ranges1').hide();
    }
    $('#packageprice').val('')
    $('#pack_dist_type').val(0)
    $('#package_discount').val('')
    $('#range_min').val('')
    $('#range_max').val('')
})

$('#filterbranch_id').change(function () {
    $('#filter_department').empty();
    document.getElementById("filter_sub_department").innerHTML = null;
    LoadFilterDepartment();
});

function LoadFilterDepartment() {
    var department = {
        Dml_Indicator: "DP",
        branch_id: $('#filterbranch_id').val()
    }
    $.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") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Department;
                    $('#filter_department').empty();
                    document.getElementById("filter_sub_department").innerHTML = null;
                    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>';
                    });
                    $('#filter_department').append(default_opt + Department);

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

        }
    });
}

$('#filter_department').change(function () {
    document.getElementById("filter_sub_department").innerHTML = null;

    var subdepartment = {
        Dml_Indicator: "SDP",
        Master_cd_id: $('#filter_department').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) {
            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>';
                    });
                    $('#filter_sub_department').append(default_opt + SubDepartment);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
});

$('#btnfilter').click(function () {
    table_package(1);
});

$('#btnclear').click(function () {
    debugger;
    //if ($('#hiddenRole_id').val() != 1) {
    //    $('#filterbranch_id').val(0);
    //    $('#filter_sub_department').empty();
    //    $('#filter_department').empty();
    //}
    //else {
    //    $('#filter_sub_department').val(0);
    //    $('#filter_department').val(0);
    //}

    if ($('#hiddenRole_id').val() != 1) {
        // LoadBranch() //one master concept
        // $('#filterbranch_id').val($('#HospitalBranchID').val());
        $('#filter_sub_department').empty();
        $('#filter_department').empty();
    }
    else {
        $('#filter_sub_department').val(0);
        $('#filter_department').val(0);
    }
    $('#surgical_investigstion_filter').val('')
    $('#status_filter').val(0)
    table_package();
});

//Package Table Binding
function table_package(val) {
    debugger;
    //$('#shade_slot').show();
    var indicator_id = '';
    //if ($('#hiddenRole_id').val() == 2) {
    //    indicator_id = 'PDST'
    //}
    //else {
    indicator_id = 'PDST'
    //}
    var branch_id = ($('#HospitalBranchID').val() == '') ? 0 : $('#HospitalBranchID').val();
    if (val == 1) {
        var package_data = {
            indicator_id: "PFilter",
            // branch_id: $('#filterbranch_id').val(),
            master_department_id: $('#filter_department').val(),
            sub_department_id: $('#filter_sub_department').val(),
            type: $('#surgical_investigstion_filter').val(),
            status: $('#status_filter1').val()
        }
    }
    else {
        var package_data = {
            indicator_id: indicator_id,
            // branch_id: branch_id
        }
    }

    $.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") {
                            package_discount
                            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><td>" + other_info + "</td><td>" + view_more + "</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><td>" + other_info + "</td><td>" + view_more + "</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><a  data-toggle='tooltip' title='In Active'  class='btn btn-info btn-xs mr-10' href='javascript:void(0);'  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-check-square-o' aria-hidden='true'></i></a></td><td><span></span></td></tr>";
                        }
                    });
                    $('#package_list_table tbody').html(row_data);
                    $('#shade_slot').hide();
                    datatable('package_list_table', 'Package_Details', 'Legal');
                    //$('#package_list_table tbody').append(row_data);
                    //$('#shade_slot').hide();
                    //$('#package_list_table').DataTable()
                    //  datatable('package_list_table', 'Package_Details', 'Legal');
                }
            }
            else {
                console.log(data1);
            }
        },
    });
}
//Package Service Mapping-Subtable-->Table Binding
function servicedetails(e, id) {
    debugger;
    var tr = e.closest('tr');
    var row = $('#package_list_table').DataTable().row(tr);
    console.log(row);
    //var row = $('#request_view').DataTable().row(tr);

    if (row.child.isShown()) {
        // This row is already open - close it
        row.child.hide();
        tr.removeClass('shown');
    }
    else {
        // Open this row
        row.child(getservicedetails(id)).show();
        tr.addClass('shown');
    }
}
function getservicedetails(packageid) {
    div = $('<div/>')
        .addClass('loading')
        .addClass('table_child')
        .addClass('table-responsive');
    var service_data = {
        package_id: packageid,
        indicator_id: 'SD'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_ins_upd_del',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(service_data),
        success: function (data) {
            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 {
                    div.removeClass('loading')

                    var row = 2;
                    var tr, row_data;
                    tr = $('<table class="table table-condensed body-borderless table_borderless">');
                    tr.append('<thead><tr><th>S.No</th><th>Service Code</th><th>Service Name</th><th>Base Amount</th><th>Number of Usage</th></tr></thead><tbody>');
                    $.each(data1.Table, function (i, emp) {
                        row_data = '<tr><td>' + j + '</td><td>' + emp.service_code + '</td><td>' + emp.service_name + '</td><td>' + emp.base_amount_value + '</td><td>' + emp.no_of_services + '</td></tr>';
                        j = j + 1;
                        tr.append(row_data);
                    })
                    tr.append("</tbody>");

                    div.append(tr);

                }
            }
            else {
                console.log(data);
            }
        }
    });
    return div;
}
//Delete Package
function package_delete(val, event, indicator) {
    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;
                    debugger;
                    var status = data1.Table[0].role_rights_add

                    if (status == 0) {

                        return;
                    }
                    else {
                        var msg = '';
                        if (indicator == 'PDD') {
                            msg = 'Are you sure, You want to Delete this Package?'
                        }
                        else if (indicator == 'PAC') {
                            msg = 'Are you sure, You want to Activate this Package?'
                        }
                        else {
                            msg = 'Are you sure, You want to In-activate this Package?'
                        }
                        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>", msg,
                            {
                                closeButton: true,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 20000000,

                                onShown: function (toast) {
                                    debugger;
                                    $("#confirmationRevertYes").click(function () {
                                        debugger;
                                        var package_data = {
                                            indicator_id: indicator,
                                            package_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;
                                                var data = JSON.parse(data);
                                                console.log(data);
                                                debugger;
                                                if (data.msg == "Success") {
                                                    if (data.data.Table[0].StringMsg == 'SUCCESS') {
                                                        // location.reload();
                                                        toastr.success(data.data.Table[0].msg1);
                                                        table_package();
                                                    }
                                                    else {
                                                        toastr.warning('Package Purchased Already. Unable to Delete')
                                                    }
                                                }
                                                else {
                                                    console.log(data);
                                                }
                                            },
                                        });
                                    })
                                    $('#confirmationRevertNo').click(function () {

                                    })
                                }
                            })

                    }
                }
            }
        });
    var r;

    //r = confirm("Are you sure you want to delete this package ?");
    //if (r == true) {
    //    var package_data = {
    //        indicator_id: "PDD",
    //        package_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) {
    //            var data = JSON.parse(data);
    //            if (data.msg == "Success") {
    //                location.reload();
    //            }
    //            else {
    //                console.log(data);
    //            }
    //        },
    //    });
    //}
    //else {
    //    alert("Thank you!!");
    //}
}
//Edit Package
function package_edit(val, event) {
    //$('#add_new_package').click();
    $('#shade_slot').show();
    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;
                    debugger;
                    var status = data1.Table[0].role_rights_add

                    if (status == 0) {

                        return;
                    }
                    else {
                        $('#setup_package_form').show();
                        $('#packagelist').hide();
                        $('#package_details_form').show();
                        $('#div_new_package').show();
                        $('#div_stepper_form').show();
                        $('#add_new_package').hide();
                        $('.progress-container').show();
                        //$('.box').addClass('box-with-trackbar');
                        $('.table_view').hide();
                        $('.filter-btn').hide();
                        $("#radioBtn > a.active").removeClass("active").addClass("not-active");
                        //$('html, body').animate({
                        //    scrollTop: $("#packagenameHead").offset().top
                        //}, 2000);

                        var package_data = {
                            indicator_id: "PDS",
                            package_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) {
                                var data = JSON.parse(data);
                                if (data.msg == "Success") {
                                    console.log(data);
                                    var data1 = data.data;
                                    if (jQuery.isEmptyObject((data1))) {
                                    }
                                    else {
                                        var b = data1.Table;
                                        var c = data1.Table3
                                        var d = data1.Table4
                                        $('#Hdpserviceid').val(c[0].master_service_id)
                                        $('#CD_type').val(1);
                                        $('#package_id').val(b[0].package_auto_id);
                                        $('#Hdpackageid').val(b[0].package_auto_id);
                                        $('#status').val(b[0].package_status);
                                        $('#packagename').val(b[0].package_name);
                                        $('#packagename').prop('disabled', false);
                                        $('#pkg_short_name').val(b[0].pkg_short_name);
                                        //$('#pkg_short_name').prop('disabled', true);
                                        $('#package_type').val(b[0].package_type);
                                        $('#packagevalidity').val(b[0].validity_period_days);
                                        // $('#pkg_branch_id').val(b[0].branch_id); //one master concept
                                        $('#package_type').prop('disabled', true);
                                        $('#pkg_category').prop('disabled', true);
                                        $('#pkg_department').prop('disabled', true);
                                        $('#pkg_sub_category').prop('disabled', true);
                                        $('#pkg_sub_department').prop('disabled', true);
                                        $('#packageprice').prop('disabled', true);
                                        //if ($('#pkg_branch_id').val() == null || $('#pkg_branch_id').val() == 0) { //one master concept
                                        //    $('#pkg_branch_id').attr('disabled', false);
                                        //}
                                        //else {
                                        //    $('#pkg_branch_id').attr('disabled', true);
                                        //}

                                        //LoadPackage(b[0].package_type);

                                        //LoadCategory(b[0].master_category_id);
                                        //LoadDepartment(b[0].master_department_id);
                                        $('#pkg_category').val(b[0].master_category_id);
                                        LoadSubCategory(b[0].master_category_id, b[0].master_sub_category_id);
                                        $('#pkg_department').val(b[0].master_department_id);
                                        LoadSubDepartment(b[0].master_department_id, b[0].sub_department_id);
                                        $('#packageprice').val(b[0].price);
                                        $('#package_discount').val(b[0].discount);
                                        $('#pack_dist_type').val(b[0].discount_type);
                                        $('#pkg_base_type').val(b[0].base_amount_type);
                                        $("#pkg_base_type").val(b[0].base_amount_type)
                                        if ((b[0].base_amount_type != 1 && b[0].base_amount_type != 3)) {
                                            $('#activate_div').removeClass('hidden');
                                        }
                                        else {
                                            $('#activate_div').addClass('hidden');

                                        }
                                        if (b[0].base_amount_type == '3') {
                                            $("#range_min").val(b[0].range_min)
                                            $("#range_max").val(b[0].range_max)
                                            $(".ranges1").show();
                                        }
                                        $('#Hbase_input').val(b[0].base_amount_type);
                                        $('#remarks').val(b[0].remarks);
                                        $('a[data-toggle=mobile_view][data-title=' + b[0].display_onMobile + ']').addClass('active');
                                        $('a[data-toggle=is_surgical][data-title=' + b[0].is_surgical + ']').addClass('active');
                                        $('#is_surgical').val(b[0].is_surgical);
                                        $('#Hdservice_type_id').val(b[0].is_surgical);
                                        $('#is_surgical').prop('disabled', true);
                                        $('#surgery_div').addClass('disabled');
                                        if (b[0].package_type == 3) {
                                            $('#surgery_div').addClass('hidden');
                                        }
                                        else {
                                            $('#surgery_div').removeClass('hidden');
                                        }
                                        if (b[0].is_surgical == 1) {
                                            $('#mobile_div').addClass('hidden');
                                            $('#package_Highlights').addClass('hidden');
                                        }

                                        //if (b[0].is_activate == 1) {
                                        //    $('#is_activate').prop('checked', true);
                                        //    $('#is_activate').val(1);
                                        //    $('#activate_div').attr('disabled',true);
                                        //}
                                        //else {
                                        //    $('#is_activate').prop('checked', false);
                                        //    $('#activate_div').attr('disabled',false);
                                        //    $('#activate_div').attr('disabled',true);
                                        //}

                                        if (b[0].never_expiry == 1) {
                                            $('#pkg_from_date').prop("disabled", true);
                                            $('#pkg_to_date').prop("disabled", true);
                                            $("#package_Never_Expiry").prop("checked", true)
                                        }
                                        else {
                                            $("#package_Never_Expiry").prop("checked", false)
                                            var from_date = b[0].validity_from_date.split('T')[0]
                                            var from = from_date.split('-');
                                            var date1 = from[2] + '/' + from[1] + '/' + from[0]
                                            $('#pkg_from_date').val(date1);
                                            $('#pkg_from_date').prop("disabled", true);
                                            $('#pkg_to_date').prop("disabled", false);
                                            //$("#pkg_from_date").datepicker("setDate", date1);
                                            var to_date = b[0].validity_to_date.split('T')[0]
                                            var to = to_date.split('-');
                                            var date2 = to[2] + '/' + to[1] + '/' + to[0]
                                            $('#pkg_to_date').val(date2);
                                            $("#pkg_to_date").datepicker("setDate", date2);
                                        }
                                        var image = b[0].package_image_url
                                        if (image == null || image == "") {
                                        }
                                        else {
                                            var d, n, drloimage;
                                            d = new Date();
                                            n = d.getTime();
                                            drloimage = $('#hdnfilepath1').val() + $('#HospitalId').val() + '/Package/' + image + '?' + n;
                                            $('#photolog').append('<a href= "' + drloimage + '" target="_blank" class="another-eye">View</a>');
                                            //var imageElement = '<img src="' + drloimage + '">';
                                            //$('.file_upload_image').html(imageElement);
                                            $('#packimageid').val(image);
                                        }
                                        cv = JSON.parse(b[0].hightlights);
                                        $('#DPackagehighlights').val(cv.hightight);
                                        $('#DPackagedescription').val(cv.description);
                                        $('#DPackagedescriptionsalestext').val(cv.salesText);
                                        $('#termsandconditions tbody').empty();
                                        $.each(cv.tmc, function (j, emp1) {
                                            $('#is_package_highlight').prop('checked', true);
                                            $('#package_mobile').show();
                                            var id = "tnctr" + $('#termsandconditions')[0].rows.length;
                                            row_data = "<tr id=" + id + "><td class='tc_name'>" + emp1 + "</td><td><span class='btn btn-delete btn-xs' id='delPacktc' onclick=delPacktc('" + id + "')><i class='fa fa-trash-o' aria-hidden='true'></i></span></td>";
                                            $('#termsandconditions tbody').append(row_data);
                                        });
                                        debugger;
                                        var service = data1.Table1;
                                        var value = '', tot_row = 0;
                                        var purchase_count = data1.Table2[0].purchase_count;
                                        if (data1.Table1.length != 0) {
                                            $('#Hmaster_service_id').val(service[0].master_service_id)
                                        }
                                        else {
                                            $('#Hmaster_service_id').val(0)
                                        }

                                        $('#pkg_service tbody').empty();
                                        if (purchase_count == 0 || b[0].is_surgical == 1) {
                                            $.each(service, function (j, emp2) {
                                                $('#div_service_add').show();
                                                var sess_data_ser = emp2.service_name + "," + emp2.service_code + "," + emp2.base_amount_value + "," + emp2.no_of_services;
                                                sessionStorage.setItem(emp2.master_service_id, sess_data_ser);
                                                value = value + "<tr id=" + emp2.master_service_id + "><td>" + emp2.service_name + "</td><td>" + emp2.service_code + "</td><td>" + emp2.base_amount_value + "</td><td>" + emp2.no_of_services + "</td><td><button class='btn btn-edit btn-xs' onclick=serviceedit('" + emp2.master_service_id + "')><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='delete btn btn-delete btn-xs btn-add' onclick='Servicedelete(\"" + emp2.master_service_id + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";
                                                tot_row = tot_row + 1;
                                            })
                                        }
                                        else {
                                            $('#div_service_add').show();
                                            $.each(service, function (j, emp2) {

                                                var sess_data_ser = emp2.service_name + "," + emp2.service_code + "," + emp2.base_amount_value + "," + emp2.no_of_services;
                                                sessionStorage.setItem(emp2.master_service_id, sess_data_ser);
                                                value = value + "<tr id=" + emp2.master_service_id + "><td>" + emp2.service_name + "</td><td>" + emp2.service_code + "</td><td>" + emp2.base_amount_value + "</td><td>" + emp2.no_of_services + "</td><td>-</td></tr>";
                                                tot_row = tot_row + 1;
                                            })
                                        }
                                        $('#pkg_service > tbody:last').append(value);
                                        $('#ServiceTableRowCount').val(tot_row);
                                        $('#btnAddPackage').html("Update Package");
                                        $('#service_Submit').html("Update");
                                        $('#pkg_service_id').attr('disabled', false);
                                    }
                                    LoadFormmappingTable(1)
                                    loadCampaigndata();
                                    LoadCRMmappingTable()
                                    editSales();
                                    schem_mappingTable();
                                    table_package1()
                                    $('#lblServiceName').html(b[0].package_name)
                                    $('#lblDepartment').html(d[0].name)
                                    $('#lblSubDepartment').html(d[0].sub_cd_name)
                                    $('#lblBaseAmount').html(b[0].price)
                                }
                                else {
                                    console.log(data);
                                }
                                $('#shade_slot').hide();
                            }
                        });


                    }
                }
            }
        });

}

function LoadDepartment(id) {
    // $("#pkg_department").val()
    var department = {
        Dml_Indicator: "DP",
        // branch_id: $('#pkg_branch_id').val(), // one master concept
        name: $('#CD_type').val()
    }
    $.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") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Department;
                    $('#pkg_department').empty();
                    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) {
                        $('#pkg_department').append(Department);
                        if ($('#package_id').val() == '') {
                            $("#pkg_department").change();
                        }
                    }
                    else {
                        $('#pkg_department').append(default_opt + Department);
                    }
                    if (id != 0) {
                        $('#pkg_department').val(id);
                    }
                }
            }
            else {
                console.log(data1);
            }
            // LoadService();
        }
    });
}



//Used for Loading the Sub Department DropDown
$("#pkg_department").change(function () {
    debugger;
    LoadSubDepartment($('#pkg_department').val(), 0);
    $('#pkg_sub_department').prop('disabled', false);
})
function LoadSubDepartment(id, val) {
    debugger;
    var val = val;
    document.getElementById("pkg_sub_department").innerHTML = null;
    var subdepartment = {
        Dml_Indicator: "SDP",
        Master_cd_id: id,
        name: $('#CD_type').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) {
            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) {
                        $('#pkg_sub_department').append(SubDepartment);
                        $("#pkg_sub_department").change();
                    }
                    else {
                        $('#pkg_sub_department').append(default_opt + SubDepartment);
                    }
                    if (val != '' && val != 0) {
                        $('#pkg_sub_department').val(val);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Load Category
function LoadCategory(id) {
    debugger;
    var department = {
        Dml_Indicator: "DPC",
        //  branch_id: $('#pkg_branch_id').val(), //one master concept
        name: $('#CD_type').val()
    }
    $.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;
                    $('#pkg_category').empty();
                    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) {
                        $('#pkg_category').append(Department);
                        $("#pkg_category").change();
                    }
                    else {
                        $('#pkg_category').append(default_opt + Department);
                    }
                    if (id != 0) {
                        $('#pkg_category').val(id);
                    }
                }
            }
            else {

                console.log(data1);
            }
            LoadDepartment(0);
        }
    });
}

//Used for Loading the Sub Category DropDown
$("#pkg_category").change(function () {
    debugger;
    LoadSubCategory($('#pkg_category').val(), 0);
    $('#pkg_sub_category').prop('disabled', false);
})
function LoadSubCategory(id, val) {
    document.getElementById("pkg_sub_category").innerHTML = null;

    var subdepartment = {
        Dml_Indicator: "SDPC",
        Master_cd_id: id,
        name: $('#CD_type').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) {
            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) {
                        $('#pkg_sub_category').append(SubDepartment);
                        $("#pkg_sub_category").change();
                    }
                    else {
                        $('#pkg_sub_category').append(default_opt + SubDepartment);
                    }
                    if (val != 0) {
                        $('#pkg_sub_category').val(val);
                    }
                }
            }
            else {
                console.log(default_opt);
            }
        }
    });
}
////Load Service
//function LoadService() {
//    var service_data = {
//        P_Dml_Indicator: "SL",
//        branch_id: $('#pkg_branch_id').val()
//    }
//    $.ajax({
//        async: true,
//        type: 'POST',
//        url: '/Billing/Service_Master_Ins_upd_sel',
//        contentType: 'application/json; charset=UTF-8',
//        data: JSON.stringify(service_data),
//        success: function (data) {
//            var data1 = JSON.parse(data);
//            if (data1.msg == "Success") {
//                var data1 = data1.data;
//                console.log(data1);
//                $('#pkg_service_id').empty();
//                if (jQuery.isEmptyObject((data1))) {
//                }
//                else {
//                    var Service;
//                    var default_opt = '<option value="0">--Select--</option>';
//                    $.each(data1, function (i, emp) {
//                        Service = Service + '<option value="' + emp.master_service_id + '">' + emp.service_name + '</option>';
//                    });
//                    $('#pkg_service_id').append(default_opt + Service);
//                }
//            }
//            else {
//                console.log(data1);
//            }
//        }
//    })
//}
//Service Name onchange for loading service code
function loadservicedetails(id) {
    debugger;

    var service_data = {
        P_Dml_Indicator: "SLC",
        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(service_data),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    $('#pkg_service_code').val(data1[0].service_code);
                    $('#pkg_base_amount').val(data1[0].base_amount_value);
                }
            }
            else {
                console.log(data1);
            }
        }
    })
}
////Load PackageType
//function LoadPackage(id) {
//    var package_data = {
//        indicator_id: "PL",
//        branch_id: $('#pkg_branch_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) {
//            var data1 = JSON.parse(data);
//            if (data1.msg == "Success") {
//                var data1 = data1.data;
//                console.log(data1);
//                if (jQuery.isEmptyObject((data1))) {
//                }
//                else {
//                    $('#package_type').empty();
//                    var package_type;
//                    var default_opt = '<option value="0">--Select--</option>';
//                    $.each(data1.Table, function (i, emp) {
//                        package_type = package_type + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
//                    });
//                    $('#package_type').append(default_opt + package_type);
//                    if (id != 0) {
//                        $('#package_type').val(id);
//                    }
//                }
//            }
//            else {
//                console.log(data1);
//            }

//        }
//    })
//}
//Load Branch
function LoadBranch() {
    document.getElementById("pkg_branch_id").innerHTML = null;
    document.getElementById("filterbranch_id").innerHTML = null;

    //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) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment = "";
                    var default_opt = '<option value="0">--Select--</option>';
                    var def_opt = '<option value="0">All</option>'
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#pkg_branch_id').append(SubDepartment);
                        $('#filterbranch_id').append(SubDepartment);
                        branch_change();
                        //$('#pkg_branch_id').val(emp.hospital_branch_id);
                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#filterbranch_id').append(SubDepartment);
                        }
                        else {

                            $('#filterbranch_id').append(def_opt + SubDepartment);
                        }

                        $('#pkg_branch_id').append(default_opt + SubDepartment);
                    }

                    //Only KinderSurge
                    //if ($('#hiddenRole_id').val() == 1) {
                    //    $('#pkg_branch_id').val($('#HospitalBranchID').val());
                    //    $('#pkg_service_id').attr('disabled', false);
                    //    $('#package_type').attr('disabled', false);
                    //    $('#pkg_category').attr('disabled', false);
                    //    $('#pkg_department').attr('disabled', false);
                    //    branch_change();
                    //    $('#filterbranch_id').val($('#HospitalBranchID').val());
                    //    $('#filterbranch_id').change();
                    //}
                    //else 
                    if ($('#hiddenRole_id').val() != 2) {
                        $('#pkg_branch_id').val($('#HospitalBranchID').val());
                        $('#pkg_branch_id').attr('disabled', true);
                        $('#pkg_service_id').attr('disabled', false);
                        $('#package_type').attr('disabled', false);
                        $('#pkg_category').attr('disabled', false);
                        $('#pkg_department').attr('disabled', false);
                        branch_change();
                        $('#filterbranch_id').val($('#HospitalBranchID').val());
                        $('#filterbranch_id').attr('disabled', true);
                        $('#filterbranch_id').change();
                    }

                }
            }
            else {
                console.log(data1);
            }
        }
    });
}
//Branch change function
$('#pkg_branch_id').change(function () {
    debugger;
    branch_change();
})
function branch_change() {
    debugger;
    CheckCodeTemplate();
    if ($('#pkg_branch_id').val() == '' || $('#pkg_branch_id').val() == 0) {
        $('#pkg_service_id').attr('disabled', true);
        //$('#package_type').attr('disabled', true);
        $('#pkg_category').attr('disabled', true);
        $('#pkg_department').attr('disabled', true);
    }
    else {
        LoadCategory(0);
        if ($('#package_type').val() == '' || $('#package_type').val() == 0) {
            $('#pkg_service_id').attr('disabled', true);
        }
        else {
            $('#pkg_service_id').attr('disabled', false);
        }
        if ($('#pkg_service  >tbody >tr').length != 0) {
            $('#pkg_service tbody').empty();

        }
        $('#pkg_service_id').val('');
        $('#pkg_service_code').val('');
        $('#pkg_base_amount').val('');
        $('#pkg_service_usage').val('');
        //$('#pkg_service_id').attr('disabled', false);
        //$('#package_type').attr('disabled', false);
        $('#pkg_category').attr('disabled', false);
        $('#pkg_department').attr('disabled', false);
        $('#pkg_sub_category').empty();
        $('#pkg_sub_department').empty();
        $('#package_type').val('0');

    }
}
$('#package_type').change(function () {
    debugger;
    //if ($.trim($('#pkg_branch_id').val()) == "" || $('#pkg_branch_id').val() == '0') { //one master concept
    //    $('#Ppkg_branch_id').show();
    //    $('#Ppkg_branch_id').fadeOut(8000);
    //    $('#Ppkg_branch_id').html('Select Branch');
    //    $('#pkg_branch_id').focus();
    //    $('#pkg_branch_id').val('');
    //    $('#package_type').val(0);
    //    $('#pkg_service_id').attr('disabled', true);
    //    return false;
    //}
    //else {
    if ($('#package_type').val() == 3) {
        $('#surgery_div').addClass('hidden');
        $('a[data-toggle=is_surgical][data-title="2"]').removeClass('active').addClass('not-active');
        $('a[data-toggle=is_surgical][data-title="1"]').removeClass('active').addClass('not-active');
        $('#is_surgical').val(0);
        $('#pkg_service_id').attr('disabled', false);

    }
    else if ($('#package_type').val() == 4) {
        //if ($('#surgery_div').hasClass('hidden')) {
        //    $('#surgery_div').removeClass('hidden');
        //    $('#is_surgical').val('');
        //}
        if ($('#is_surgical').val() != 1) {
            $('#pkg_service_id').attr('disabled', false);

        }
        else {
            $('#pkg_service_id').attr('disabled', true);

        }
    }
    else {
        $('#surgery_div').removeClass('hidden');
        $('#is_surgical').val('');
        $('#pkg_service_id').attr('disabled', true);

    }
    if ($('#pkg_service  >tbody >tr').length != 0) {
        $('#pkg_service tbody').empty();
        $('#ServiceTableRowCount').val(0);
    }
    $('#pkg_service_id').val('');
    $('#pkg_service_code').val('');
    $('#pkg_base_amount').val('');
    $('#pkg_service_usage').val('');

    // }

})

$('#Package_Purchase_Details').click(function () {
    window.location.href = '/PackageDetails/PackagePurchase';

    //$('#PackagePurchase_Details_popup').modal('show');
    //package_dashboard();

});

function package_dashboard() {
    debugger;
    var package_data = {
        indicator_id: "PDASH",
        doctor_id: $('#HiddenDoctorID').val(),
        hospital_id: $('#HospitalId').val()
        //package_type: 3
    }
    $.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) {
            var data1 = JSON.parse(data);
            $('#package_dash_table').empty();
            if (data1.msg == "Success") {
                var data1 = data1.data;


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

                }
                else {


                    var j = 0;

                    var b = data1.Table;
                    var cb = data1.Table1;
                    $('#package_detailsdata').dataTable().fnDestroy();
                    var tr = '';

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

                        var patdata = "-", sold_by = '', pat_numer = '', phlebo_doctor_name = '';
                        //if (emp.created_by == "USD") {
                        //    sold_by = "DOCTOR";
                        //}
                        //else {
                        //    sold_by = "MOBILE APP";
                        //}
                        if (emp.booked_device == 1) {
                            sold_by = "WEB APP";
                        }
                        else {
                            sold_by = "MOBILE APP";
                        }
                        if (emp.phone_number_1 == null || emp.phone_number_1 == '') {
                            pat_numer = "-"
                        }
                        else {
                            pat_numer = emp.phone_number_1;
                        }
                        patdata = emp.first_name + '/' + pat_numer + '/' + emp.patient_id;
                        val = emp.package_typevalue;

                        //tr = tr + "<tr><td>" + j + "</td><td>" + patdata + "</td><td>" + emp.package_name + "</td><td>" + (emp.date_of_purchase) + "</td><td>" + emp.cost_of_package + "</td><td>" + emp.valid_upto + "</td><td>" + sold_by + "</td><td><button class='UM_82 btn btn-primary btn-xs'><span class='' data-toggle='modal' data-target='#urpkgeView' onclick=package_view(" + emp.package_purchase_details_id + "," + val + ")>Coupon Details</span></button></td><td><button onclick=files_package('" + emp.package_purchase_details_id + "')  data-toggle='modal' data-target='#appointment_files'>View Files</button></td></tr>";
                        tr = tr + "<tr><td>" + j + "</td><td>" + patdata + "</td><td>" + emp.package_name + "</td><td>" + (emp.date_of_purchase) + "</td><td>" + emp.cost_of_package + "</td><td>" + emp.valid_upto + "</td><td>" + sold_by + "</td><td><button class='UM_82 btn btn-primary btn-xs'><span class='' data-toggle='modal' data-target='#urpkgeView' onclick=package_view(" + emp.package_purchase_details_id + "," + val + ")>Coupon Details</span></button></td></tr>";


                    });

                    $('#package_dash_table').html(tr);

                    $('#package_detailsdata').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    });

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


//$('#urpkgeView').modal('show');
function package_view(id, val) {

    var package_data = {
        indicator_id: "PVIEW",
        package_purchase_details_id: id,
    }
    $.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) {
            $('#package_coupon_table').empty();
            //$('#urpkgeView').modal('toggle');
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {
                    tr = $('<table class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>Coupon Id</th><th>Coupon Type</th><th>Coupon Status</th><th>Issued Date</th><th>Valid Upto</th><th>Appointment date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                    tr.append("</tbody>");
                }
                else {
                    var image = '', coupon = '', j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '', type = '-';
                    var b = data1.Table;
                    var c = data1.Table1;
                    $.each(b, function (i, emp) {
                        if (emp.photo != "") {
                            image = "https://app.medwayhospitals.com/UserprofileImg/" + emp.photo;
                        }
                        else {
                            image = "/Content/img/profile_icon.png";
                        }
                        if (emp.billing_visit != null && emp.billing_visit != '') {
                            PatientSearch(emp.patient_id, emp.billing_visit_type, emp.billing_branch_id, emp.billing_visit);
                        }
                        else {
                            PatientSearch(emp.patient_id, emp.request_visit_type, emp.request_branch_id, emp.request_visit);
                        }

                        $('#casePhoto1').attr('src', "" + image + "");
                        $('#patname').html(emp.first_name);
                        $('#patnum').html(emp.phone_number_1);
                        $('#packname').html(emp.package_name);
                        $('#packcost').html(emp.cost_of_package);
                        $('#packexdate').html(emp.expire_date);
                        $('#Hdnpatient_id').val(emp.patient_id);
                        package_details_card(emp.package_name, emp.cost_of_package, emp.expire_date);
                    });
                    tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                    tr.append("<thead><tr><th>Coupon Id</th><th>Coupon Type</th><th>Coupon Status</th><th>Issued Date</th><th>Valid Upto</th><th>Appointment date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                    $.each(c, function (i, emp) {
                        j++;
                        if (emp.coupon_status == 1) coupon = "Active";
                        else if (emp.coupon_status == 3) coupon = "Expired";
                        else if (emp.coupon_status == 4) coupon = "Cancelled";
                        else if (emp.coupon_status == 2) coupon = "Used";
                        if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                        else coupon_issued_date = emp.coupon_issued_date;
                        if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                        else coupon_consumed_date = emp.coupon_consumed_date;
                        if (emp.coupon_consumed_by == '' || (emp.coupon_consumed_by) == null) coupon_consumed_by = '-';
                        else coupon_consumed_by = emp.coupon_consumed_by;
                        if (emp.type == "1") type = "Consulting";
                        else if (emp.type == "2") type = "Lab";
                        else if (emp.type == "3") type = "Pharmacy";
                        else type = "Home Visit";
                        if (emp.coupon_useby_date == "" || emp.coupon_useby_date == null) {
                            emp.coupon_useby_date = '-';
                        }
                        if (coupon_consumed_by == '-') {
                            row_data = "<tr><td>" + emp.coupon_id + "</td><td>" + type + "</td><td>" + coupon + "</td><td>" + emp.created_on + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.coupon_useby_date + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view btn btn-submit btn-xs mr-15' title='Change Status to Completed' onclick=patient_package_completed('" + emp.coupon_id + "')><i class='fa fa-check' aria-hidden='true'></i></span><span class='ur-pkge-cancel ur-pkge-view btn btn-danger btn-xs' data-toggle='popover' title='Cancel Coupon' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                        }
                        else {
                            row_data = "<tr><td>" + emp.coupon_id + "</td><td>" + type + "</td><td>" + coupon + "</td><td>" + emp.created_on + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.coupon_useby_date + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                        } tr.append(row_data);
                    });
                    tr.append("</tbody>");
                    $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                        "columnDefs": [{
                            "orderable": false,
                        }]
                    }));
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function patient_package_completed(id) {
    $('#pack_coupon_id').val(id);
    var package_data = {
        indicator_id: "COTPS",
        coupon_id: $('#pack_coupon_id').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_coupon_otp',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                $('#tblotpcheck').modal('toggle');
            }
            else {
                console.log(data);
            }
        }
    });
}

function patient_package_cancel(id) {
    $('#pack_coupon_id').val(id);
    var package_data = {
        indicator_id: "COTPS",
        coupon_id: $('#pack_coupon_id').val(),
        doctor_id: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/PackageDetails/package_coupon_otp',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(package_data),
        success: function (data) {
            var data = JSON.parse(data);
            if (data.msg == "Success") {
                $('#tblotpcheck1').modal('toggle');
            }
            else {
                console.log(data);
            }
        }
    });
}

function otp_check_completed() {
    if ($.trim($('#pack_otp').val()).length == "") {
        $('#Ppack_otp').show();
        $('#Ppack_otp').fadeOut(8000);
        $('#Ppack_otp').html('Please enter OTP');
        $('#pack_otp').focus();
        $('#pack_otp').val('');
        return false;
    }
    if ($.trim($('#pack_otp')).length > 0) {
        var package_data = {
            indicator_id: "COTPV",
            coupon_id: $('#pack_coupon_id').val(),
            patient_id: $('#Hdnpatient_id').val(),
            otp: $('#pack_otp').val(),
            doctor_id: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PackageDetails/package_coupon_otp',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(package_data),
            success: function (data) {
                $('#pack_otp').val('');
                $('#tblotpcheck').modal('toggle');
                debugger;
                var j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '';
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    if (jQuery.isEmptyObject((data1))) {
                    }
                    else {
                        var b = data1.Table;
                        if (b[0].Cid == "failure") {
                            toastr.warning("Invalid OTP");
                        }
                        else {
                            $('#package_coupon_table').empty();
                            tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                            tr.append("<thead><tr><th>S No</th><th>Coupon Id</th><th>Coupon Status</th><th>Coupon Expire Date</th><th>Issued Date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                            $.each(b, function (i, emp) {
                                j++;
                                if (emp.coupon_status == 1) coupon = "Active";
                                else if (emp.coupon_status == 3) coupon = "Expired";
                                else if (emp.coupon_status == 4) coupon = "Cancelled";
                                else if (emp.coupon_status == 2) coupon = "Used";
                                if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                                else coupon_issued_date = emp.coupon_issued_date;
                                if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                                else coupon_consumed_date = emp.coupon_consumed_date;
                                if (emp.coupon_consumed_by == '' || emp.coupon_consumed_by == null) coupon_consumed_by = '-';
                                else coupon_consumed_by = emp.coupon_consumed_by
                                if (coupon_consumed_by == '-') {
                                    row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view' data-toggle='popover' title='Change Status' data-target='#urpkgeView' onclick=patient_package_expired('" + emp.coupon_id + "')><i class='fa fa-eye' aria-hidden='true'></i></span><span class='ur-pkge-cancel' data-toggle='popover' title='Cancell Package' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                                }
                                else {
                                    row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                                }
                                tr.append(row_data);
                            });
                            tr.append("</tbody>");
                            $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                                "columnDefs": [{
                                    "orderable": false,
                                }]
                            }));
                        }
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}

function otp_check_cancel() {
    if ($.trim($('#pack_otp1').val()).length == "") {
        $('#Ppack_otp1').show();
        $('#Ppack_otp1').fadeOut(8000);
        $('#Ppack_otp1').html('Please enter OTP');
        $('#pack_otp1').focus();
        $('#pack_otp1').val('');
        return false;
    }
    if ($.trim($('#pack_otp1')).length > 0) {
        var package_data = {
            indicator_id: "COTPD",
            coupon_id: $('#pack_coupon_id').val(),
            patient_id: $('#Hdnpatient_id').val(),
            otp: $('#pack_otp1').val(),
            doctor_id: $('#HiddenDoctorID').val()
        }
        $.ajax({
            async: true,
            type: 'POST',
            url: '/PackageDetails/package_coupon_otp',
            contentType: 'application/json; charset=UTF-8',
            data: JSON.stringify(package_data),
            success: function (data) {
                $('#pack_otp1').val('');
                $('#tblotpcheck1').modal('toggle');
                debugger;
                var j = 0, coupon_consumed_date = '', coupon_issued_date = '', coupon_consumed_by = '';
                var data1 = JSON.parse(data);
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var b = data1.Table;
                    if (b[0].Cid == "failure") {
                        toastr.warning("Invalid OTP");
                    }
                    else {
                        $('#package_coupon_table').empty();
                        tr = $('<table  class="table-responsive table table-bordered table-striped dataTable" id="pkgecouTable" />');
                        tr.append("<thead><tr><th>S No</th><th>Coupon Id</th><th>Coupon Status</th><th>Coupon Expire Date</th><th>Issued Date</th><th>Consumed Date</th><th>Consumed By</th><th>Actions</th></tr></thead><tbody>");
                        $.each(b, function (i, emp) {
                            j++;
                            if (emp.coupon_status == 1) coupon = "Active";
                            else if (emp.coupon_status == 3) coupon = "Expired";
                            else if (emp.coupon_status == 4) coupon = "Cancelled";
                            else if (emp.coupon_status == 2) coupon = "Used";
                            if ((emp.coupon_issued_date) == null || (emp.coupon_issued_date) == '') coupon_issued_date = '-';
                            else coupon_issued_date = emp.coupon_issued_date;
                            if ((emp.coupon_consumed_date) == null || (emp.coupon_consumed_date) == '') coupon_consumed_date = '-';
                            else coupon_consumed_date = emp.coupon_consumed_date;
                            if (emp.coupon_consumed_by == '' || emp.coupon_consumed_by == null) coupon_consumed_by = '-';
                            else coupon_consumed_by = emp.coupon_consumed_by
                            if (coupon_consumed_by == '-') {
                                row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td><td><span class='ur-pkge-view btn btn-submit btn-xs mr-15' data-toggle='popover' title='Change Status to Completed' data-target='#urpkgeView' onclick=patient_package_completed('" + emp.coupon_id + "')><i class='fa fa-eye' aria-hidden='true'></i></span><span class='ur-pkge-cancel ur-pkge-view btn btn-danger btn-xs' data-toggle='popover' title='Decline Coupon' data-target='#urpkgeCancel' onclick=patient_package_cancel('" + emp.coupon_id + "')><i class='fa fa-ban' aria-hidden='true'></i></span></td></tr>";
                            }
                            else {
                                row_data = "<tr><td>" + j + "</td><td>" + emp.coupon_id + "</td><td>" + coupon + "</td><td>" + emp.coupon_expire_date + "</td><td>" + emp.created_on + "</td><td>" + coupon_consumed_date + "</td><td>" + coupon_consumed_by + "</td></tr>";
                            }
                            tr.append(row_data);
                        });
                        tr.append("</tbody>");
                        $.when($('#package_coupon_table').append(tr)).then($('#pkgecouTable').DataTable({
                            "columnDefs": [{
                                "orderable": false,
                            }]
                        }));
                    }
                }
                else {
                    console.log(data1);
                }
            }
        });
    }
}
//package discount type change function
$('#pack_dist_type').change(function () {
    $('#package_discount').val('');
})
//package discount-->percentange discount restriction -->less than 100
$('#package_discount').keyup(function () {
    if ($('#pack_dist_type').val() == 2) {
        if ($.trim($('#package_discount').val()) > 100 || $.trim($('#package_discount').val()) < 0) {
            $('#Ppackage_discount').show();
            $('#Ppackage_discount').fadeOut(8000);
            $('#Ppackage_discount').html('Enter Discount less than 100');
            $('#package_discount').focus();
            $('#package_discount').val('');
        }
    }
})

//Form Clear
function form_clear() {
    $('#package_id').val('');
    $('#packageprice').prop('disabled', false);
    $('#packagename').prop('disabled', false);
    //$('#pkg_short_name').prop('disabled', false);
    //$('#pkg_branch_id').prop('disabled', false); //one master concept
    $('#package_type').prop('disabled', false);
    $('#pkg_from_date').prop('disabled', false);
    $('#pkg_to_date').prop('disabled', false);
    $('#pkg_category').prop('disabled', false);
    $('#pkg_sub_category').prop('disabled', false);
    $('#pkg_department').prop('disabled', false);
    $('#pkg_sub_department').prop('disabled', false);
    $('#packagename').val('');
    $('#pkg_short_name').val('');
    // $('#pkg_branch_id').val(0); // one master concept
    $('#package_type').val(0);
    $('#pkg_base_type').val(0);
    $('#pkg_category').val(0);
    $('#pkg_sub_category').val(0);
    $('#pkg_department').val(0);
    $('#pkg_sub_department').val(0);
    $('#pkg_from_date').val('');
    $('#pkg_to_date').val('');
    $('#package_Never_Expiry').prop('checked', false);
    $('#packagevalidity').val('');
    $('#packimageid').val('');
    $('#packageprice').val('');
    $('#package_discount').val('');
    $('#remarks').val('');
    $('#DPackagehighlights').val('');
    $('a[data-toggle=mobile_view][data-title=1]').addClass('active');

    $('#status').val(1);
    $('#is_surgical').val('');
    $('#DPackagedescription').val('');
    $('#DPackagetc').val('');
    $('#termsandconditions tbody').empty();
    $('#pkg_service tbody').empty();
    $('#ServiceTableRowCount').val(0);
    $('#pkg_service_id').val('');
    $('#pkg_service_id').attr('disabled', true);
    $('#pkg_service_code').val('');
    $('#pkg_base_amount').val('');
    $('#pkg_service_usage').val('');
    $('#DPackagedescriptionsalestext').val('');
    $('#div_service_add').show();
    $('#btnAddPackage').html("Save Package");
    $('#service_Submit').html("submit");
    $('#is_activate').prop('checked', false);
    $('#activate_div').attr('disabled', false);

    $('#mobile_div').removeClass('hidden');
    $('#mobile_view').val('1');
    $('a[data-toggle=mobile_view][data-title=2]').addClass('not-active').removeClass('active');
    $('a[data-toggle=mobile_view][data-title=1]').addClass('active').removeClass('not-active');
    $('#package_Highlights').removeClass('hidden');
    $('#surgery_div').removeClass('disabled');
    $('#surgery_div').removeClass('hidden');

    //$('#pkg_category').empty();//one master concept
    $('#pkg_sub_category').empty();
    //$('#pkg_department').empty();//one master concept
    $('#pkg_sub_department').empty();

    $('#CD_type').val('');
    $('#pack_dist_type').val(0);


    //  LoadBranch();//one master concept
}

function files_package(package_id) {
    debugger;
    var package_data = {
        indicator_id: "FP",
        package_id: package_id,
    }
    $.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) {
            var data = JSON.parse(data);
            console.log(data);
            if (data.msg == "Success") {
                var data = data.data;
                $('#tblAppointmentFiles_body').empty();
                if (jQuery.isEmptyObject((data))) {
                }
                else {
                    if (data.Table[0].package_files != '' && data.Table[0].package_files != null) {
                        $('#health_concern').html(data.Table[0].health_concern);
                    }
                    else {
                        $('#health_concern').html("    -");
                    }
                    if (data.Table[0].package_files != '' && data.Table[0].package_files != null) {

                        var files = data.Table[0].package_files.split("&&");

                        var file_tr = '', k = 1;
                        for (var i = 0; i < files.length; i++) {
                            var d, n, drloimage;
                            d = new Date();
                            n = d.getTime();
                            var file = $('#hdnfilepath1').val() + "HomeCareFiles/ParvathyFiles/" + files[i] + "?" + n;
                            file_tr = file_tr + '<tr><td>' + k + '</td><td><a href = ' + file + ' target=_blank> File </a></td></tr>';

                            k = k + 1;
                        }
                        $('#tblAppointmentFiles_body').html(file_tr);


                    }
                    else {
                        $('#tblAppointmentFiles_body').html(Norecord);
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

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

}).change();

//surgery change function
$('#is_surgical').change(function () {
    debugger;
    //if ($('#pkg_branch_id').val() != '' && $('#pkg_branch_id').val() != 0 && $('#package_type').val() != '' && $('#package_type').val() != 0)
    if ($('#package_type').val() != '' && $('#package_type').val() != 0)

        $('#pkg_service_id').attr('disabled', false);
    if ($('#pkg_service  >tbody >tr').length != 0) {
        $('#pkg_service tbody').empty();
        $('#ServiceTableRowCount').val(0);

    }
    $('#pkg_service_id').val('');
    $('#pkg_service_code').val('');
    $('#pkg_base_amount').val('');
    $('#pkg_service_usage').val('');
    var surgery = $('#is_surgical').val();
    if (surgery == 1) {
        debugger;
        $('#mobile_div').addClass('hidden');
        $('#mobile_view').val('2');
        $('a[data-toggle=mobile_view][data-title=1]').addClass('not-active').removeClass('active');
        $('a[data-toggle=mobile_view][data-title=2]').addClass('active').removeClass('not-active');
        $('#package_Highlights').addClass('hidden');
    }
    else {
        $('#mobile_div').removeClass('hidden');
        $('#mobile_view').val('1');
        $('a[data-toggle=mobile_view][data-title=2]').addClass('not-active').removeClass('active');
        $('a[data-toggle=mobile_view][data-title=1]').addClass('active').removeClass('not-active');
        $('#package_Highlights').removeClass('hidden');
    }
})


// Udhayadharani
$('#mobile_view').change(function () {
    debugger;
    if ($('#mobile_view').val() == 1) {
        $('#package_Highlights').removeClass('hidden');

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

})


//load Service type
function loadservice_type() {
    var data = {
        P_Dml_Indicator: 'STP'
    }
    $.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") {
                    $('#package_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>"
                    })
                    $('#package_type').append(default_option + option);
                }
            }
        }
    })
}

//package wise report
function package_wise_report(package_auto_id, branchid, hospitalid, event) {
    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");
    var chkprevilige = check_previlige(did, navigation, name, columntype);
    $.when(chkprevilige)
        .then(function (data) {
            debugger;
            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 load_data = {
                            formid: '131',
                            packageid: package_auto_id,
                            branchid: branchid,
                            hospitalid: hospitalid,
                        }
                        //window.open("/reports/PrintCrystalReport?data=" + JSON.stringify(load_data))

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

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

                    }
                }
            }
        })

}
function Hideshow() {
    debugger;
    var show = {
        dml_indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/IP_OP_Billings',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(show),
        success: function (data) {
            debugger;
            var data = JSON.parse(data);
            $('#hstatus').empty();
            $('#hvisit').empty();
            if (jQuery.isEmptyObject((data.data))) {
            }
            else {
                debugger;

                var status = data.data.Table[1].status;
                var visit = data.data.Table[1].master_vist_type_id;
                $('#hstatus').val(status);
                $('#hvisit').val(visit);
                if ($('#hstatus').val() == 0 && $('#hvisit').val() == 2) {
                    debugger;
                    $('#surgery_div').hide();
                }

            }
        }
    });
}
//Form Mapping start

//load Select Form
function loadserviceForm() {
    debugger;
    var data = {
        Dml_Indicator: 'FSP',
        Packageid: $('#Hdpackageid').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()
    var selectedOptionText = $(this).find('option:selected').text();

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

})


//load WhereToDisplay
function loadWhereToDisplay() {
    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);
                    $('#wheretodisplay').append(default_option + option);
                }
            }
        }
    })
}



//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);

    }
});

$("#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 ($.trim($('#selectfrom').val()) == 0) {
        $('#Pselectfrom').show();
        $('#Pselectfrom').fadeOut(8000);
        $('#Pselectfrom').html('Select Form Name');
        $('#selectfrom').focus();
        return false;
    }
    if ($.trim($('#applicationto').val()) == 0 || $.trim($('#applicationto').val()) == '') {
        $('#Papplicationto').show();
        $('#Papplicationto').fadeOut(8000);
        $('#Papplicationto').html('Select ApplicableTo');
        $('#applicationto').focus();
        return false;
    }
    if ($.trim($('#selectapplication').val()) == 0 || $.trim($('#selectapplication').val()) == '') {
        $('#Pselectapplication').show();
        $('#Pselectapplication').fadeOut(8000);
        $('#Pselectapplication').html('Select Application');
        $('#selectapplication').focus();
        return false;
    }
    if ($.trim($('#wheretodisplay').val()) == 0 || $.trim($('#wheretodisplay').val()) == '') {
        $('#Pwheretodisplay').show();
        $('#Pwheretodisplay').fadeOut(8000);
        $('#Pwheretodisplay').html('Select Where to display');
        $('#Pwheretodisplay').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 HdPackageid = $('#Hdpackageid').val()
    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: $('#Hdpserviceid').val(),
        //$('#master_service_id').val(),
        IsUpload: saveValue,
        AccessRights: RightsValue,
        ConsultingType: tabValue,
        MessageClassId: messageclass,
        Hospital_id: $('#HospitalId').val(),
        Packageid: parseInt(HdPackageid),
        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)
        },
    });
});

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

    loadWhereToDisplay()
})

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()
}


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

    formmappingedit(Id)

});

function formmappingedit(Id) {
    debugger;

    $('#Htformid').val(Id)
    //$('#formmapping_form').show();
    //$('#formmapping_table').hide();
    //$('#formmapping_div').hide();


    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);
            $("#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.SMS_flag == 1) {
                $('#smsid').prop('checked', "checked");
                Loadsms(emp.MessageClassId, 0)
            }
            else {
                $('#smsid').prop('checked', false);
                $('#SMS').empty()
            }


            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, Packageid) {
    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: 'DD',
                          Id: Id,
                          Packageid: Packageid,
                      }

                      $.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: "PS",
        ServiceId: $('#Hdpackageid').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>' +
                            '<h3 class="pform_name">' + emp.Form_Name + '</h3>' + // 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 + ' ,' + $('#Hdpackageid').val() + ')"></i>' +
                            '</div></div><p class="papplicable">APPLICABLE TO: <span>' + applicableto + '<span>' +
                            '</p><p class="papplicable">WHERE TO DISPLAY: <span>' + emp.form_displayname + '</span></p>' +
                            '<div class="smsoveralldiv">' +
                            '<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

$('#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_filter').val() == "" || $('#status_filter').val() == '0') {
        $('#Pstatus_filter').show();
        $('#Pstatus_filter').fadeOut(8000);
        $('#Pstatus_filter').html('Select The Status');
        $('#Pstatus_filter').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 HdPackageId = $('#Hdpackageid').val()
    var submit = {
        Id: Id,
        URL: $('#campaign_urlname').val(),
        Plateform: $('#campaign_type').val(),
        ActiveForm: from_date,
        ActiveTo: to_date,
        Status: $('#status_filter').val(),
        QR: uploadfile,
        Dml_Indicator: Dml_Indicator,
        masterserviceid: $('#Hmaster_service_id').val(),
        Packageid: parseInt(HdPackageId)

    }

    $.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: "PCS",
        masterserviceid: $('#Hdpackageid').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_filter").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_filter').val(''),
        $('#qr_image').val('')

};

//-- Campaign Ends---


//Package Mapping Start
function table_package1() {
    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: $('#Hmaster_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_table1 tbody').empty();
                    $('#package_list_table1').dataTable().fnClearTable();
                    $('#package_list_table1').dataTable().fnDraw();
                    $('#package_list_table1').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_table1 tbody').append(row_data);
                    $('#shade_slot').hide();
                    $('#package_list_table1').DataTable()
                    //  datatable('package_list_table', 'Package_Details', 'Legal');
                }
            }
            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">
                                    <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-chevron-down pull-right" 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 CRMArray = [];
    var Crmtaskcreationindays = ''
    if ($("#crm_taskcreationindays").val() == '') {
        Crmtaskcreationindays = 0
    }
    else {
        Crmtaskcreationindays = $("#crm_taskcreationindays").val()
    }
    // 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 = $('#Hdpserviceid').val()
    Obj.Id = CRM_Id
    Obj.ServiceTypeId = $('#Hdservice_type_id').val()
    Obj.Packageid = $('#Hdpackageid').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: "CRMP",
        //    master_service_id: $('#Hmaster_service_id').val(),
        is_package: $('#Hdpackageid').val()
    }
    $.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">
                                    <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-chevron-down pull-right" 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('Surgery Package')
            }
            else if (emp[0].ServiceTypeId == 0) {
                $('.crmservicetype').html('General Package')
            }
            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('')
}
$('#AddCRM').click(function () {
    CRMClear();
    $("#HCRMMapping").val('')
    if ($('#Hdservice_type_id').val() == 1) {
        $('.crmservicetype').html('Surgery Package')
    }
    else if ($('#Hdservice_type_id').val() == 0) {
        $('.crmservicetype').html('General Package')
    }
    else {
        $('.crmservicetype').html('-')
    }

    loadtasktype($('#Hdservice_type_id').val())

    $('#crm_mapping_save').html('Add')
});

function loadtasktype(type, id) {
    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 (id != '' || id != null) {
                    $('#crm_mapping_type').val(id)
                }
            }
        }
    })
}

$('#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 HdPackageId = $('#Hdpackageid').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'),
        Packageid: parseInt(HdPackageId)

    };

    $.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, sectionFlag) {
    $('#div_mobilediscountenable').removeClass('hidden');
    debugger;
    var sales = {
        masterserviceid: $('#Hdpackageid').val(),
        Dml_Indicator: "SE"
    };

    $.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 Servicenext(n) {
    $('#btnAddPackage').html('Update Package')
    $('#crm_mapping_search').val('')
    if ($('#Hdpackageid').val() != '') {
        var x = document.getElementsByClassName("stepper_tab");

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

        currentTab = currentTab + n;

        if (currentTab >= x.length) {

            return false;
        }

        showTab(currentTab);

        var ids = ['#servicetypeval', '#servicetypeval1', '#servicetypeval2', '#servicetypeval3'];
        if ($('#is_surgical').val() == 0) {
            ids.forEach(function (id) {
                $(id).html('General');
            });
        }
        else if ($('#is_surgical').val() == 1) {
            ids.forEach(function (id) {
                $(id).html('Surgery');
            });
        }
    }
    else {
        toastr.warning("Sorry, there is no Package created.");
    }

}
// schem mapping  start //
function packstepperclick(n) {
    var ids = ['#servicetypeval', '#servicetypeval1', '#servicetypeval2', '#servicetypeval3'];
    if ($('#is_surgical').val() == 0) {
        ids.forEach(function (id) {
            $(id).html('General');
        });
    }
    else if ($('#is_surgical').val() == 1) {
        ids.forEach(function (id) {
            $(id).html('Surgery');
        });
    }
    var x = document.getElementsByClassName("stepper_tab");

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

    currentTab = n;
    showTab(currentTab);
}

function schem_mappingTable() {
    var servicevalues = {
        P_Dml_Indicator: "SMSEL",
        master_service_id: $('#Hmaster_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) {

            $('#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 () {


    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.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: $('#Hmaster_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.');

                    // schem_mappingTable($('#Hdnserviceid').val());
                }
                Servicenext(1)
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

// schem mapping end //