//Filename:HospitalSetup.js
//Frontenddeveloper:seetharaman.
//Backenddeveloper:
//Description:File used for validation and integration for all pages in hospital setup menu 
//Created date on:25/11/2021


$(document).ready(function () {
    debugger;
    $('#Hos_UploadFile').attr('disabled', true)
    HospitalFileType();
    loadcountry();
    TableHospitalDetails();
    LoadCasesheetType();
    LoadChargeType();

    if (parseInt($('#hiddenRole_id').val()) == 0) {
        $('#add_new_hospital').removeClass('hidden');
        $('#appflag_div').show();
        $('#div_MobileApp').show();
        $('#div_is_formbuilder').show();
        $('#div_is_PrintType').show();
    }

    if ($('#hiddenRole_id').val() == 0) {
        $('.disabled_column').removeClass('disabled');       
    }
    else {
        $('.disabled_column').addClass('disabled');
    }

})

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

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

            }
        }
    });
}

// load city
function load_city() {
    var state = {
        state_id: $("#HdnState").val(),
        Dml_Indicator: "CI"
    }

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

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

            }
        }
    });
}

//load country and defaultly selected to india
function loadcountry() {

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

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

                    $('#txtCountry').append(default_opt + Country);
                    $('#ddbranch_Country').append(default_opt + Country);
                }
                else {
                    console.log(data);
                }
            }
        }
    });
}

//Hospital Detail Table Function
function TableHospitalDetails() {
    debugger;
    $('#shade_slot').show();

    var HosTbldata = {

        Dml_Indicator: 'HOSTS',
        roleid: $('#hiddenRole_id').val(),
        hospital_id: $('#HospitalId').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(HosTbldata),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            $('#shade_slot').hide();
            if (jQuery.isEmptyObject(data)) {

            }
            else {

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

                    tr = $('<table id="example1" class="table table-bordered table-striped dataTable dt-responsive tablecolumnsticky" />');


                    tr.append("<thead><tr><th>Hospital Name</th><th>Reg No</th><th>Contact No</th><th>Email ID</th><th>Branches</th><th>Address</th><th class='tbl-action'>Actions</th></tr></thead><tbody>");

                    var id = 0;
                    $.each(data1.Table, function (i, emp) {



                        var Branch_Count = '', HBranch = '', view = '', Del = '', Ctemplates = '', HInAorAct = '', HAutomatedCharges = '';



                        id = id + 1;



                        //Del = '<button type="button" data-toggle="tooltip" data-placement="bottom" title="Delete" class="btn btn-delete btn-xs Hide_btn" data-id="GD_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_GeneralDetails_form" onclick=DELHospital(this,"' + emp.hospitalid + '");><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                        //view = '<button type="button" data-toggle="tooltip" data-placement="bottom" title="Edit" class="btn btn-edit btn-xs" data-id="GD_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="edit_GeneralDetails_form" onclick=HospitalEdit(this,"' + emp.hospitalid + '");><i class="fa fa-pencil" aria-hidden="true"></i></button>';
                        //Ctemplates = '<button type="button" data-toggle="modal" data-placement="bottom" title="Setup" class="btn btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick="LoadCodeTemplatesList(this, \'' + emp.hospital_id + '\');">Setup IDs';
                        //payment = '<button type="button" data-toggle="modal" data-placement="bottom" title="Payment_Details" class="btn  btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=PaymentDetails(this,"' + emp.hospital_id + '");  data-toggle="modal" data-target="#payment">Payment Details</button>'
                       // HAutomatedCharges = '<button type="button" data-toggle="modal" data-placement="bottom"  title="Hospital Automated Charges" class="btn  btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=HospitalAutomatedCharges(this,"' + emp.hospital_id + '");  data-toggle="modal" data-target="#hospital_automated_charges">Automated Charges</button>';

                        Del = '<a  class="delete_icon"  title="Delete" class="btn btn-delete btn-xs Hide_btn" data-id="GD_D1" data-type="role_rights_delete" data-nav="sp_div" data-name="delete_GeneralDetails_form" onclick=DELHospital(this,"' + emp.hospitalid + '");><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        //view = '<a  class="edit_icon" title="Edit" data-id="CD_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="edit_CategoryDepartment_form" onclick=CategoryorDtitle="Edit" data-id="OS_E1"  data-type="role_rights_edit" data-nav="sp_div" data-name="add_new_servicetype_form"   onclick=service_edit(this,"' + emp.master_servie_type_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        view = '<a  class="edit_icon" data-toggle="tooltip" data-placement="bottom" title="Edit" class="btn btn-edit btn-xs" data-id="GD_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="edit_GeneralDetails_form" onclick=HospitalEdit(this,"' + emp.hospitalid + '");><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        Ctemplates = '<a type="button" data-toggle="modal" data-placement="bottom" title="Setup" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick="LoadCodeTemplatesList(this, \'' + emp.hospital_id + '\');">Setup IDs</a>';
                        payment = '<a type="button" data-toggle="modal" data-placement="bottom" title="Payment_Details" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=PaymentDetails(this,"' + emp.hospital_id + '");  data-toggle="modal" data-target="#payment">Payment Details</a>'
                       HAutomatedCharges = '<a type="button" data-toggle="modal" data-placement="bottom"  title="Hospital Automated Charges" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=HospitalAutomatedCharges(this,"' + emp.hospital_id + '");  data-toggle="modal" data-target="#hospital_automated_charges">Automated Charges</a>';


                        if (emp.BranchCount > 0) {

                            Branch_Count = "<span class='mr-15'>" + emp.BranchCount + "</span><span class='fa fa-angle-double-down table-arrow-size pull-right' onclick=Branchdetails(\'brn_" + id + "\',\'" + emp.hospitalid + "\');></span>";
                        }
                        else {
                            Branch_Count = "<span class='mr-15'>" + emp.BranchCount + "</span><span class='fa fa-angle-double-down table-arrow-size pull-right' onclick=Branchdetails(\'brn_" + id + "\',\'" + emp.hospitalid + "\');></span>";
                        }

                        if (emp.is_branches == 1) {
                            HBranch = '<button type="button" class="btn  btn-xs Hide_btn" data-id="GD_A1" data-type="role_rights_add" data-nav="sp_div" data-name="add_GeneralDetails_form" onclick=HBranch_popup(this,\"' + emp.hospitalid + '\",\"' + emp.hospital_logo + '\",\"' + emp.product_code + '\")><i class="fa fa-plus" aria-hidden="true">&nbsp;&nbsp;<input type="hidden" id="' + emp.hospitalid + '" value="' + emp.hospital_name + '" /></i>Add Branch</button>'
                        }

                        if (emp.hospital_status == 1) {
                            HInAorAct = '<button id="btnHInAorAct_' + emp.hospitalid + '" type="button" class="btn  btn-xs Hide_btn" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=HosInActorAct(this,"' + emp.hospitalid + '");>InActive</button>';
                        }
                        else if (emp.hospital_status == 2) {
                            HInAorAct = '<button id="btnHInAorAct_' + emp.hospitalid + '" type="button" class="btn  btn-xs Hide_btn" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=HosInActorAct(this,"' + emp.hospitalid + '");>Active</button>';
                            HBranch = '', view = '', Ctemplates = '';
                        }
                        else {
                            HInAorAct = '';
                        }


   
                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + view + ' ' + 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-new" id=""><p class="text-left">' + HInAorAct + '</p><p class="text-left">' + HBranch + '</p><p class="text-left">' + Ctemplates + '</p></ul></div></div>';


                        row_data = "<tr><td  class='tbl-name'>" + emp.hospital_name + "</td><td>" + emp.registeration_number + "</td><td>" + emp.phone_number_1 + "</td><td>" + emp.email + "</td><td data-toggle='collapse' data-target='#h_" + id + "' class='accordion-toggle'>" + Branch_Count + "</td><td>" + emp.Address + "</td><td>" + other_info + "</td></tr><tr class='hiddenRow accordian-body collapse' id='brn_" + id + "'></tr>";


                        tr.append(row_data);

                    });
                    tr.append("</tbody></table>");
                    //$('#hptl_tbl_body').append(row_data);
                    $('#TblHospitalDetails').html(tr);
                    //datatable('example1');

                    //var table = $('#example1').DataTable({

                    //});
                    //$('a.toggle-vis').on('click', function (e) {
                    //    e.preventDefault();

                    //    var column = table.column($(this).attr('data-column'));
                    //    column.visible(!column.visible());
                    //});

                    //if ($('#hiddenRole_id').val() == 2) {
                    //    $('.Hide_btn').addClass('hidden');
                    //}
                    //else {
                    //    $('.Hide_btn').removeClass('hidden');
                    //}

                    if ($('#hiddenRole_id').val() == 0) {

                        $('.Hide_btn').removeClass('hidden');  
                    }
                    else {
                        $('.Hide_btn').addClass('hidden');
                    }
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}


// added by nandhini on 04/08/2022
// hospital automated charges add function start--------
function HospitalAutomatedCharges(event, hospital_id) {
    debugger
    $('#SelectedHospitalID_AC').val(hospital_id);
    $('#SelHospitalBranch').empty();
    $('#tblHospitalCharges_body').empty();

    var codeData = {
        Dml_Indicator: "BL",
        hospital_id: $('#SelectedHospitalID_AC').val(),
        //branch_id: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        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, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.length == 1) {
                        $('#SelHospitalBranch').append(SubDepartment);
                        LoadHospitalAutomatedCharges();
                    }
                    else {
                        $('#SelHospitalBranch').append(default_opt + SubDepartment);
                    }
                    if ($('#hiddenRole_id').val() == 1) {
                        $('#SelHospitalBranch').val($('#HospitalBranchID').val());
                        $('#SelHospitalBranch').attr('disabled', true);
                        LoadHospitalAutomatedCharges();
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#SelHospitalBranch').change(function () {
    $('#Hidden_master_service_id').val('');
    $('#txtServiceAmount').val('');
    $('#SelServices').val('');
    LoadHospitalAutomatedCharges();
});

function clear() {
    $('#Hidden_master_service_id').val('');
    $('#txtServiceAmount').val('');
    $('#SelServices').val(''); 
    $('#SelChargeType').val(0); 
    $('#txtpercentage').val('');
    $('#SelChargeType').attr('disabled', false);
    $('#btnAddHospitalCharges').html('Add')
}

function LoadHospitalAutomatedCharges(event, hospital_id, branch_id, branch_name, flag) {
    debugger;

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");

    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)) {
                // Handle empty data if needed
            } else {
                var j = 0;
                var status = data1.Table[0].role_rights_add;
                if (status == 0) {
                    return;
                } else {
                    $('#hospital_automated_charges').modal();
                    $('#SelectedHospitalID_AC').val(hospital_id);
                    if (flag == '1') {
                        clear();
                        $('#SelHospitalBranch').empty();

                        var SubDepartment = '<option value="' + branch_id + '">' + branch_name + '</option>';
                        $('#SelHospitalBranch').append(SubDepartment);
                    }

                    LoadAutomatedCharges(hospital_id, branch_id);
                }
            }
        }
    });
}
function DeleteHospitalCharges(hospital_automated_charge_id) {
    var codeData = {
        Dml_Indicator: "D",
        hospital_automated_charge_id: hospital_automated_charge_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Hospital_Automated_Charges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {

            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                toastr.success('Deleted Successfully');
                LoadAutomatedCharges($('#SelectedHospitalID_AC').val(), $('#SelHospitalBranch').val());
            }
        }
    });
}

function HospitalsetupEdit(hospital_automated_charge_id) {
    debugger;
    var codeData = {
        Dml_Indicator: "E",
        hospital_automated_charge_id: hospital_automated_charge_id
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Hospital_Automated_Charges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data;
            //$("#SelHospitalBranch").val(emp[0].branch_id);

            $("#SelChargeType").val(emp[0].charge_type);
            $("#SelChargeType").prop('disabled', true);
            $("#SelServices").val(emp[0].service_name);
            $("#txtpercentage").val(emp[0].percentage);
            $("#txtServiceAmount").val(emp[0].base_amount_value);
            $("#Hidden_master_service_id").val(emp[0].master_service_id);
            $('#btnUpdateHospitalCharges')
            LoadHospitalAutomatedCharges($('#HospitalId').val(), $('#SelHospitalBranch').val());
            $('#Hdnhospitalautoid').val(emp[0].hospital_automated_charges_id)
            $('#btnAddHospitalCharges').html('Update');
        }

    })
}


$('#btnAddHospitalCharges').click(function () {
    debugger;

    if ($('#SelHospitalBranch').val() == "" || $('#SelHospitalBranch').val() == null || $('#SelHospitalBranch').val() == 0) {
        $('#PSelHospitalBranch').show();
        $('#PSelHospitalBranch').fadeOut(8000);
        $('#PSelHospitalBranch').html('Select Branch Name');
        $('#SelHospitalBranch').val('');
        $('#SelHospitalBranch').focus();
        return false;
    }

    if ($('#SelChargeType').val() == "" || $('#SelChargeType').val() == null || $('#SelChargeType').val() == 0) {
        $('#PSelChargeType').show();
        $('#PSelChargeType').fadeOut(8000);
        $('#PSelChargeType').html('Select Charge Type');
        $('#SelChargeType').val('');
        $('#SelChargeType').focus();
        return false;
    }
    if ($('#Hidden_master_service_id').val() == null || $('#Hidden_master_service_id').val() == "") {
        $('#PSelServices').show();
        $('#PSelServices').fadeOut(8000);
        $('#PSelServices').html('Select Service');
        $('#SelServices').val('');
        $('#SelServices').focus();
        return false;
    }
    var perc = $("#txtpercentage").val();
    if (perc > 100) {
        toastr.warning('Please enter less than 100');
        $("#txtpercentage").val('');
        $('#SelServices').focus();
        return false;
    }
    var indicator_id = $('#btnAddHospitalCharges').html() == 'Add' ? 'I' : 'U';

    var codeData = {
        hospital_automated_charge_id: $('#Hdnhospitalautoid').val(),
        Dml_Indicator: indicator_id,
        hospital_id: $('#SelectedHospitalID_AC').val(),
        branch_id: $('#SelHospitalBranch').val(),
        charge_type: $('#SelChargeType').val(),
        master_service_id: $('#Hidden_master_service_id').val(),
        base_amount_value: $('#txtServiceAmount').val(),
        percentage: $('#txtpercentage').val()
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Hospital_Automated_Charges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var stringMsg = data1.data[0].StringMsg;
                if (stringMsg == "Already") {
                    toastr.warning('Selected Charge type is already exists for this Branch');
                } else {
                    toastr.success('Saved Successfully');
                }

                resetFormFields();
                LoadAutomatedCharges($('#SelectedHospitalID_AC').val(), $('#SelHospitalBranch').val());
            } else {
                if ($('#btnAddHospitalCharges').html() == 'Update') {
                    toastr.success('Updated Successfully');
                    resetFormFields();
                    $('#btnAddHospitalCharges').html('Add');
                    LoadAutomatedCharges($('#SelectedHospitalID_AC').val(), $('#SelHospitalBranch').val());
                }
            }
        }
    });

    function resetFormFields() {
        $('#Hidden_master_service_id').val('');
        $('#SelChargeType').val('');
        $('#txtServiceAmount').val('');
        $('#SelServices').val('');
        $('#txtpercentage').val('');
    }
});
function LoadAutomatedCharges(hospital_id, branch_id) {
    var codeData = {
        Dml_Indicator: "S",
        hospital_id: hospital_id,
        branch_id: branch_id
    };
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Hospital_Automated_Charges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        success: function (data) {
            var data1 = JSON.parse(data);
            $('#tblHospitalCharges_body').empty();

            $('#SelHospitalBranch').prop('disabled', true);

            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject(data1)) {
                    // Handle empty data if needed
                } else {
                    if (data1.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data1.length; i++) {
                            var Del = '<button type="button" class="btn btn-delete btn-xs" onclick="DeleteHospitalCharges(\'' + data1[i].hospital_automated_charges_id + '\', \'' + hospital_id + '\', \'' + branch_id + '\');"><i class="fa fa-trash-o" aria-hidden="true"></i></button>';
                            var view = '<button type="button" class="btn btn-edit btn-xs" onclick="HospitalsetupEdit(\'' + data1[i].hospital_automated_charges_id + '\');"> <i class="fa fa-pencil" aria-hidden="true"></i></button>';
                            tr = tr + '<tr><td>' + (i + 1) + '</td><td>' + data1[i].service_name + '</td><td>' + data1[i].master_service_name + '</td><td>' + data1[i].percentage + '</td><td>' + data1[i].base_amount_value + '</td><td>' + view + Del + '</td></tr>';
                        }

                        $('#tblHospitalCharges_body').append(tr);
                    }
                }
            } else {
                console.log(data1);
            }
        }
    });
}


// hospital automated charges end--------------------------

function codetemp(event, hospital_id) {

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    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 {

                     $('#SelectedHospitalID').val(hospital_id);
                     LoadBranch();

                 }
             }
         }
     });


}

function Branchdetails(id, Hospitalid) {

    $('#HdnBranHospital_id').val('');
    var id = id;
    var Branch_data = {
        hospitalid: Hospitalid,
        Dml_Indicator: 'HBRNS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Branch_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 {

                    var trhead = '<td colspan="12"><div><table class="table table-bordered dt-responsive"><thead><tr class="info"><th>Branch Name</th><th>Address</th><th>Contact Person</th><th>Contact No</th><th>No.of.Licenses</th><th>Email ID</th><th>Actions</th></tr></thead><tbody>';
                    $.each(data1.Table, function (i, emp) {

                        var BranchInAorAct = '', view = '', Del = '';

                        Del = '<button type="button" class="btn btn-delete btn-xs Hide_btn" onclick=DELBranch("' + emp.hospital_branch_id + '");><i class="fa fa-trash-o" aria-hidden="true"></i></button>';

                        if (emp.hospital_status == 1) {
                            view = '<button type="button" class="btn btn-edit btn-xs" onclick=HBranchEdit("' + emp.hospital_branch_id + '");><i class="fa fa-pencil" aria-hidden="true"></i></button>'

                         

                            if (emp.Branch_status == 1) {
                                BranchInAorAct = '<button id="btnBInAorAct_' + emp.hospital_branch_id + '" type="button" class="btn  btn-xs Hide_btn" onclick=HBInActorAct("' + emp.hospital_branch_id + '","' + id + '","' + Hospitalid + '");>InActive</button>';
                            }
                            else if (emp.Branch_status == 2) {
                                BranchInAorAct = '<button id="btnBInAorAct_' + emp.hospital_branch_id + '" type="button" class="btn btn-xs Hide_btn" onclick=HBInActorAct("' + emp.hospital_branch_id + '","' + id + '","' + Hospitalid + '");>Active</button>';
                                view = '';
                            }
                            else {
                                BranchInAorAct = '';
                            }
                        }
                        else {
                            BranchInAorAct = '', view = '';
                        }
                        //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + view + ' ' + Del + '<a href="#" class="dropdown-toggle btn btn-info-dots btn-xs Hide_btn" 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=""><li class="text-left">' + BranchInAorAct + '</li></ul></div></div>';

                        Ctemplates = '<button type="button" data-toggle="modal" data-placement="bottom" title="Setup" class="btn btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick="LoadCodeTemplatesList1( this,\'' + emp.hospital_id + '\', \'' + emp.hospital_branch_id + '\', \'' + emp.branch_name + '\');">Setup IDs';

                        //payment = '<button type="button" data-toggle="modal" data-placement="bottom" title="Payment_Details" class="btn btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick=PaymentDetails(this,"' + emp.hospital_id + '"); data-toggle="modal" data-target="#payment">Payment Details';
                        var payment = '<button type="button" data-toggle="modal" data-placement="bottom" title="Payment_Details" class="btn btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick="PaymentDetails(this, \'' + emp.hospital_id + '\', \'' + emp.hospital_branch_id + '\', \'' + emp.branch_name + '\');">Payment Details</button>';

                        //HAutomatedCharges = '<button type="button" data-toggle="modal" data-placement="bottom" title="Hospital Automated Charges" class="btn btn-xs" onclick=HospitalAutomatedCharges(this,"' + emp.hospital_id + '"); data-toggle="modal" data-target="#hospital_automated_charges">Automated Charges';
                        HAutomatedCharges = '<button type="button" data-toggle="modal" data-placement="bottom" title="Hospital Automated Charges" class="btn btn-xs" data-id="GD_F1" data-type="role_rights_function" data-nav="sp_div" data-name="function_GeneralDetails_form" onclick="LoadHospitalAutomatedCharges(this,\'' + emp.hospital_id + '\', \'' + emp.hospital_branch_id + '\', \'' + emp.branch_name + '\', \'' + '1' + '\');">Automated Charges';

                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + view + ' ' + 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=""><p class="text-left">' + Ctemplates + '</p><p class="text-left">' + HAutomatedCharges + '</p><p class="text-left">' + payment + '</p></div></div>';

                        tr = tr + "<tr><td>" + emp.branch_name + "</td><td>" + emp.Address + "</td><td>" + emp.contact_personname + "</td><td>" + emp.mobile_no + "</td><td>" + emp.no_of_license + "</td><td>" + emp.email + "</td><td class='col-sm-1'>" + other_info + "</td></tr>";
                        j = j + 1;
                    })
                    var trend = '</tbody></table></div></td>';
                    $('#' + id).html(trhead + tr + trend);
                    if ($('#' + id).hasClass('in') == true) {
                        $('#' + id).removeClass('in');
                    }
                    else {
                        $('#' + id).addClass('in');
                    }

                    //if ($('#hiddenRole_id').val() == 2) {
                    //    $('.Hide_btn').addClass('hidden');
                    //}
                    //else {
                    //    $('.Hide_btn').removeClass('hidden');
                    //}

                    if ($('#hiddenRole_id').val() == 0) {
                        $('.Hide_btn').removeClass('hidden');   
                    }
                    else {
                        $('.Hide_btn').addClass('hidden');
                    }
                }
            }
            else {
                console.log(data);
            }
        }
    });

}

function LoadCodeTemplatesList1(event,hospital_id, SelBranch, branch_name) {

    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) {

         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 {



    $('#code_templates').modal()
    $('#SelectedHospitalID').val(hospital_id);
    debugger;
    $('#SelBranch').empty();

    var SubDepartment = '<option value="' + SelBranch + '">' + branch_name + '</option>';
    $('#SelBranch').append(SubDepartment);
    var SelectedHospitalID = hospital_id;
    var SelBranch11 = SelBranch;
    var codeData = {
        Dml_Indicator: "BS",
        hospital_id: SelectedHospitalID,
        branch_id: SelBranch11
    }
    $.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);
            $('#tblCodeTemplates').empty();

            $('#SelBranch').closest('.col-md-3').show();
            $('#SelBranch').prop('disabled', true);

            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    if (data1.length > 0) {
                        var tr = "";
                        for (var i = 0; i < data1.length; i++) {
                            tr = tr + '<tr><td style="display:none" id="formid_' + (i + 1) + '">' + data1[i].form_id + '</td><td class="pt-20" id="formname_' + (i + 1) + '">' + data1[i].form_name + '</td><td><div class="form-group"><input type="text" class="form-control  prefixformid_' + data1[i].form_id + ' " id="prefix_' + (i + 1) + '" placeholder="Prefix" autocomplete="off" value="' + data1[i].prefix + '"><p id="Pprefix_' + data1[i].form_id + '" style="color:red"></p></div></td>'
                                + '<td><div class="form-group"><input type="text" class="form-control" id="suffix_' + (i + 1) + '" placeholder="Suffix" autocomplete="off" value="' + ((data1[i].suffix == null || data1[i].suffix == "") ? "" : data1[i].suffix) + '"></div></td>'
                                + '<td><div class="form-group"><input type="text" class="form-control" id="no_of_digits_' + (i + 1) + '" placeholder="No.of.digits" autocomplete="off" value="' + data1[i].no_of_digits + '" onkeyup=checkDigitsValue("' + (i + 1) + '")><p id="Pno_of_digits_' + (i + 1) + '" style="color:red"></p></div></td>'
                                + '<td><div class="form-group"><input type="number" maxlength="5" class="form-control" id="startvalue_' + (i + 1) + '" placeholder="Start Value" autocomplete="off" value="' + data1[i].start_value + '" onkeyup=checkStartValue("' + (i + 1) + '")><p id="Pstartvalue_' + (i + 1) + '" style="color:red"></p></div></td>'
                                + '<td class="codetemp-year"><input type="checkbox" id="ckhyearwise_' + (i + 1) + '" onchange=ChangeYearWise(' + (i + 1) + ');>'
                                + '<div class="form-group" id="divradio_' + (i + 1) + '" style="display:none;"><select class="form-control" id="year_type_' + (i + 1) + '"><option value="0">-Select-</option><option value="1">Date Month Year</option><option value="2">Month Year</option><option value="3">Year</option><option value="4">Financial Year</option></select><p id="Pyeartype_' + (i + 1) + '" style="color:red"></p><div>'
                                //+ '<div class="form-group cust_codetemplates_radio" id="divradio_' + (i + 1) + '" style="display:none;"><input type="radio" class="code-rdo" id="datemonthyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="1"><label for="datemonthyear_' + (i + 1) + '" class="mr-10"> DateMonthYear</label><input type="radio" class="code-rdo" id="monthyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="2"><label for="monthyear_' + (i + 1) + '" class="mr-10">MonthYear</label><input type="radio" class="code-rdo" id="year_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="3"><label for="year_' + (i + 1) + '" class="mr-10">Year</label><input type="radio" class="code-rdo" id="financialyear_' + (i + 1) + '" name="year_type_' + (i + 1) + '" value="4"><label for="financialyear_' + (i + 1) + '" class="mr-10">FinancialYear</label></div> '
                                + '</td>'
                                + '</tr>'
                        }

                        $('#tblCodeTemplates').append(tr);

                        //setting checkbox value
                        for (var j = 0; j < data1.length; j++) {
                            $("#ckhyearwise_" + (j + 1)).prop('checked', ((data1[j].is_year_wise == "1" || data1[j].is_year_wise == 1) ? true : false));

                            if (data1[j].is_year_wise == "1" || data1[j].is_year_wise == 1) {
                                $('#divradio_' + (j + 1)).show();
                                if (data1[j].year_type != "" && data1[j].year_type != null) {
                                    $('#year_type_' + (j + 1)).val(data1[j].year_type);
                                    //$('input[name="year_type_' + (j + 1) + '"][value="' + data1[j].year_type + '"]').attr('checked', true);
                                }
                            }
                            else {
                                $('#divradio_' + (j + 1)).hide();
                            }
                        }
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    })
                 }
             }
         }
     })
}

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

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

            }
        }
    });
});


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

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

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

            }
        }
    });
});

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

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

            }
        }
    });
});


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

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

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

            }
        }
    });
});


//Saved All Hospital upload file
function AllPackageimageupload(id) {
    debugger;
    var UploadFileid = id;
    var photo = id + '_photo';
    var pathvalue = id + '_pathvalue';

    var uploadpath = $('#' + id).val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $('#' + id).get(0);
        var files = fileUpload.files;

        if (files[0].size > 5e+6) {

            toastr.warning('Upto 5 MB Per File!');
            return false;
        };
        var filePath = fileUpload.value;
        // Allowing file type
        var allowedExtensions =
                /(\.jpg|\.jpeg|\.png)$/i;

        if (!allowedExtensions.exec(filePath)) {
            toastr.warning('Invalid File Type');
            fileInput.value = '';
            return false;
        }
        $.when(checkimagedimensionvalidation(fileUpload.files[0], 512, 512)).
       done(function (Results) {

           if (Results == 'Success') {
               var fileData = new FormData();
               for (var i = 0; i < files.length; i++) {
                   fileData.append(files[i].name, files[i]);
               }
               fileData.append('username', 'Manas');
               $.ajax({
                   url: '/Hospitalsetup/UploadHospitalandBrancheFiles',
                   type: "POST",
                   contentType: false,
                   processData: false,
                   data: fileData,
                   success: function (result) {
                       $.each(result, function (i, emp) {

                           $('#' + photo).empty();
                           $('#' + photo).show();
                           $('#' + pathvalue).val(emp);
                           $('#' + photo).append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp + '" target="_blank">' + UploadFileid + '</a>');
                       });
                   }
               });
           }
           else {
               //$('#HospitalLogo').val('');
               //$('#HospitalFavicon').val('');
               //$('#photolog').empty();

               $('#' + id).val('');
               $('#' + pathvalue).val('');
               $('#' + photo).empty();
           }
       });
    }
}

//save Multifile Upload

function AllMultifileimageupload(id) {
    debugger;
    var UploadFileid = $('#ddUPFileType option:selected').data('id');
    //var UploadFileid = id;
    if (UploadFileid == "0") {
        $('#PddUPFileType').show();
        $('#PddUPFileType').fadeOut(8000);
        $('#PddUPFileType').html('Select File Type');
        $('#ddUPFileType').val(0);
        $('#ddUPFileType').focus();
        $('#ddUPFileType').enabled();
        return false;
    }
    var photo = id + '_photo';
    var pathvalue = id + '_pathvalue';

    var uploadpath = $('#' + id).val();
    var fileExtension = uploadpath.substring(uploadpath.lastIndexOf(".") + 1, uploadpath.length);
    if (window.FormData !== undefined) {
        var fileUpload = $('#' + id).get(0);
        var files = fileUpload.files;
        var fileData = new FormData();

        //var filePath = fileUpload.value;
        var allowedExtensions =
           /(\mp4|\m4v|\mov)$/i;
        //if (!allowedExtensions.exec(filePath)) {
        if (fileExtension.match(allowedExtensions)) {
            //if (allowedExtensions == /(\.mp4|\.m4v|\.mov)$/i) {

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

            fileData.append('username', 'Manas');
            $.ajax({
                url: '/Hospitalsetup/UploadHospitalandBrancheFiles',
                type: "POST",
                contentType: false,
                processData: false,
                data: fileData,
                success: function (result) {
                    $.each(result, function (i, emp) {

                        $('#' + photo).empty();
                        $('#' + photo).show();
                        $('#' + pathvalue).val(emp);
                        $('#' + photo).append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp + '" target="_blank">' + UploadFileid + '</a>');
                    });
                }
            });
        }

        else {

            var allowedExtensions =
               /(\.jpg|\.jpeg|\.png)$/i;

            $.when(checkimagedimensionvalidation(fileUpload.files[0], 512, 512)).
        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: '/Hospitalsetup/UploadHospitalandBrancheFiles',
                    type: "POST",
                    contentType: false,
                    processData: false,
                    data: fileData,
                    success: function (result) {
                        $.each(result, function (i, emp) {

                            $('#' + photo).empty();
                            $('#' + photo).show();
                            $('#' + pathvalue).val(emp);
                            $('#' + photo).append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp + '" target="_blank">' + UploadFileid + '</a>');
                        });
                    }
                });
            }
            else {
                $('#Hos_UploadFile').val('');
                //  $('#HospitalFavicon').val('');
                //$('#' + photo).empty();
            }
        });
        }
    }
}


//Showing Save File
function id_image_show(id) {
    window.open(id, '_blank');
}

//google review link check
function ISValidLink(url) {

    var Link = url;
    if (/^(http|https|ftp):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(:[0-9]{1,5})?(\/.*)?$/i.test(Link)) {
        return 1;
    } else {
        return 0;
    }
}

//Insert and Update Hospital Details
function HospitalCreation() {

    debugger;
    // Hospital Details validation Start//
    var HospitalName = $.trim($("#txtHospitalName").val());
    var Registration = $.trim($("#txtRegistration").val());
    var ContactPersonName = $.trim($("#txtContactPersonName").val());


    if ($.trim(HospitalName) == "") {
        $('#PtxtHospitalName').show();
        $('#PtxtHospitalName').fadeOut(8000);
        $('#PtxtHospitalName').html('Enter Hospital Name');
        $('#txtHospitalName').val('');
        $('#txtHospitalName').focus();
        return false;
    }

    if ($.trim($("#txtShortHName").val()) == "") {
        $('#PtxtShortHName').show();
        $('#PtxtShortHName').fadeOut(8000);
        $('#PtxtShortHName').html('Enter Hospital Short Name');
        //$('#txtShortHName').val('');
        $('#txtShortHName').focus();
        return false;
    }

    if (parseInt($('#txtShortHName').val().length) < 3) {
        $('#PtxtShortHName').show();
        $('#PtxtShortHName').fadeOut(8000);
        $('#PtxtShortHName').html('Hospital Short Name minimum and maximum Three letters');
        $('#txtShortHName').focus();
        return false;
    }
    if ($.trim($("#HospitalLogo_pathvalue").val()) == "") {
        $('#PHospitalLogo_err').show();
        $('#PHospitalLogo_err').fadeOut(8000);
        $('#PHospitalLogo_err').html('Choose Hospital Logo');
        $('#HospitalLogo_pathvalue').val('');
        $('#HospitalLogo_pathvalue').focus();
        return false;
    }
    if ($.trim(Registration) == "") {
        $('#PtxtRegistration').show();
        $('#PtxtRegistration').fadeOut(8000);
        $('#PtxtRegistration').html('Enter Registration No');
        $('#txtRegistration').val('');
        $('#txtRegistration').focus();
        return false;
    }
    if ($.trim(ContactPersonName) == "") {
        $('#PtxtContactPersonName').show();
        $('#PtxtContactPersonName').fadeOut(8000);
        $('#PtxtContactPersonName').html('Enter Contact Person Name');
        $('#txtContactPersonName').val('');
        $('#txtContactPersonName').focus();
        return false;
    }
    if ($.trim($("#txthospi_mob_no").val()) == "") {
        $('#Ptxthospi_mob_no').show();
        $('#Ptxthospi_mob_no').fadeOut(8000);
        $('#Ptxthospi_mob_no').html('Enter Hospital contact No');
        $('#txthospi_mob_no').val('');
        $('#txthospi_mob_no').focus();
        return false;
    }
    if ($.trim($("#txthospi_email").val()) == "") {
        $('#Ptxthospi_email').show();
        $('#Ptxthospi_email').fadeOut(8000);
        $('#Ptxthospi_email').html('Enter Email Id');
        $('#txthospi_email').val('');
        $('#txthospi_email').focus();
        return false;
    }
    if ($.trim($("#txthospiAdmin_email").val()) == "") {
        $('#PtxthospiAdmin_email').show();
        $('#PtxthospiAdmin_email').fadeOut(8000);
        $('#PtxthospiAdmin_email').html('Enter Admin Email Id');
        $('#txthospiAdmin_email').val('');
        $('#txthospiAdmin_email').focus();
        return false;
    }
    if ($.trim($("#HosSelProductCode").val()) == 0) {
        $('#PHosSelProductCode').show();
        $('#PHosSelProductCode').fadeOut(8000);
        $('#PHosSelProductCode').html('Select Product Code');
        $('#HosSelProductCode').val(0);
        $('#HosSelProductCode').focus();
        return false;
    }
    //Added by Tharuni
    if ($('#Branches').val() == 0 && $('#HdnHospital_id').val() == '') {
        if ($.trim($("#is_otp").val()) == '') {
            $('#Pis_otp').show();
            $('#Pis_otp').fadeOut(8000);
            $('#Pis_otp').html('Select Discount Authorization');
            $('#is_otp').val('');
            $('#is_otp').focus();
            return false;
        }
        if ($('#is_otp').val() == 1) {
            if ($('#txt_Phone_number').val() == '') {
                $('#Ptxt_Phone_number').show();
                $('#Ptxt_Phone_number').fadeOut(8000);
                $('#Ptxt_Phone_number').html('Enter Phone Number');
                $('#txt_Phone_number').val('');
                $('#txt_Phone_number').focus();
                return false;
            }
        }
    }

    if (parseInt($("#is_app").val()) == 0) {
        $('#Pis_app').show();
        $('#Pis_app').fadeOut(8000);
        $('#Pis_app').html('Select Mobile App');
        $('#is_app').val(0);
        $('#is_app').focus();
        return false;
    }

    if (parseInt($("#is_formbuilder").val()) == 2) {
        $('#Pis_formbuilder').show();
        $('#Pis_formbuilder').fadeOut(8000);
        $('#Pis_formbuilder').html('Select Form Builder Yes/ No');
        $('#is_formbuilder').val(0);
        $('#is_formbuilder').focus();
        return false;
    }

    if (parseInt($("#is_app").val()) == 1) {
        if ($.trim($("#txtAppLink").val()) == '') {
            $('#PtxtAppLink').show();
            $('#PtxtAppLink').fadeOut(8000);
            $('#PtxtAppLink').html('Enter App Link');
            $('#txtAppLink').val('');
            $('#txtAppLink').focus();
            return false;
        }
    }

    // Hospital Details validation End//

    // Hospital Address Details validation Start //
    if ($('#txthospi_addr_line1').val() == '') {
        $('#Phospi_addr_line1_err').show();
        $('#Phospi_addr_line1_err').fadeOut(8000);
        $('#Phospi_addr_line1_err').html('Enter Address Line 1');
        $('#txthospi_addr_line1').val('');
        $('#txthospi_addr_line1').focus();
        return false;
    }
    if ($('#txthospi_area').val() == '') {
        $('#Ptxthospi_area').show();
        $('#Ptxthospi_area').fadeOut(8000);
        $('#Ptxthospi_area').html('Enter Area');
        $('#txthospi_area').val('');
        $('#txthospi_area').focus();
        return false;
    }
    if ($('#txtCountry').val() == '' || $('#txtCountry').val() == null || $('#txtCountry').val() == 0) {
        $('#PCountry_err').show();
        $('#PCountry_err').fadeOut(8000);
        $('#PCountry_err').html('Select Country');
        $('#txtCountry').val('');
        $('#txtCountry').focus();
        return false;
    }

    if ($('#txtState').val() == '' || $('#txtState').val() == null || $('#txtState').val() == 0) {
        $('#PtxtState_err').show();
        $('#PtxtState_err').fadeOut(8000);
        $('#PtxtState_err').html('Select State');
        $('#txtState').val('');
        $('#txtState').focus();
        return false;
    }
    if ($('#txtCity').val() == '' || $('#txtCity').val() == null || $('#txtCity').val() == 0) {
        $('#PtxtCity_err').show();
        $('#PtxtCity_err').fadeOut(8000);
        $('#PtxtCity_err').html('Select City');
        $('#txtCity').val('');
        $('#txtCity').focus();
        return false;
    }
    // Hospital Address Details validation End //

    // Hospital Other Details validation Start //    

    if ($.trim($('#txthospi_story').val()) == '') {
        $('#Ptxthospi_story_err').show();
        $('#Ptxthospi_story_err').fadeOut(8000);
        $('#Ptxthospi_story_err').html('Enter Hospital story');
        $('#txthospi_story').val('');
        $('#txthospi_story').focus();
        return false;
    }

    if ($.trim($('#txthospi_MissGoal').val()) == '') {
        $('#Ptxthospi_MissGoal_err').show();
        $('#Ptxthospi_MissGoal_err').fadeOut(8000);
        $('#Ptxthospi_MissGoal_err').html('Enter Vision, Mission and Goals');
        $('#txthospi_MissGoal').val('');
        $('#txthospi_MissGoal').focus();
        return false;
    }

    if ($.trim($('#txtgoogle_revlink').val()) != '') {

        if (ISValidLink($('#txtgoogle_revlink').val()) == 0) {
            $('#Ptxtgoogle_revlink').show();
            $('#Ptxtgoogle_revlink').fadeOut(8000);
            $('#Ptxtgoogle_revlink').html('Enter valid link');
            $('#txtgoogle_revlink').val('');
            $('#txtgoogle_revlink').focus();
            return false;
        }

    }

    // Hospital Other Details validation End // 



    //var Accomplishments_value = '';
    //if ($('#Accomplishments').val() == 1) {
    //    Accomplishments_value = $('#HospitalAccomplishments_pathvalue').val();
    //}
    //else if ($('#Accomplishments').val() == 2) {
    //    Accomplishments_value = $('#txtAccomplishments').val();
    //}
    //else {
    //    Accomplishments_value = '';
    //}


    var HospitalCreationData = {

        Dml_Indicator: "HI",
        hospitalid: $('#HdnHospital_id').val(),
        hospital_name: $('#txtHospitalName').val(),
        hospital_logo: $('#HospitalLogo_pathvalue').val(),
        hospital_favicon: $('#HospitalFavicon_pathvalue').val(),
        registeration_number: $('#txtRegistration').val(),
        contact_person_name: $('#txtContactPersonName').val(),
        contact_no: $('#txthospi_mob_no').val(),
        email_id: $('#txthospi_email').val(),
        is_branches: $('#Branches').val(),
        product_code: $('#HosSelProductCode').val(),
        admin_email_id: $('#txthospiAdmin_email').val(),


        address_line_one: $('#txthospi_addr_line1').val(),
        address_line_two: $('#txthospi_addr_line2').val(),
        area: $('#txthospi_area').val(),
        country: $('#txtCountry').val(),
        state: $('#txtState').val(),
        city: $('#txtCity').val(),


        hospital_story: $('#txthospi_story').val(),
        vision_mission_goals: $('#txthospi_MissGoal').val(),
        google_review_link: $('#txtgoogle_revlink').val(),
        is_discount_authorization: ($('#is_otp').val() == '') ? 2 : $('#is_otp').val(),
        auth_phone_number: $('#txt_Phone_number').val(),
        color_code: $('#Hospital_colorcode').val(),
        casesheet_type: $("#Casesheet_type").val(),
        is_pharmacy: $("#is_pharma").val(),
        hospital_shortname: $('#txtShortHName').val(),
        is_app: $("#is_app").val(),
        app_link: $("#txtAppLink").val(),
        is_formbuilder: $('#is_formbuilder').val(),
        print_type: $('#is_PrintType').val(),
        default_medicine_store: $("#SelStore").val()
    }

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

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

            }
            else {

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

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

                        var result = emp.StringMsg;
                        if (result == 'Moblie Number Already Exist') {
                            $('#Ptxthospi_mob_no').show();
                            $('#Ptxthospi_mob_no').fadeOut(8000);
                            $('#Ptxthospi_mob_no').html(emp.StringMsg);
                            $('#txthospi_mob_no').focus();
                            return false;
                        }
                            //else if (result == 'EmailId Already Exist') {
                            //    $('#Ptxthospi_email').fadeOut(8000);
                            //    $('#Ptxthospi_email').html(emp.StringMsg);
                            //    $('#txthospi_email').focus();
                            //    return false;
                            //}
                        else if (result == 'Admin EmailId Already Exist') {
                            $('#PtxthospiAdmin_email').show();
                            $('#PtxthospiAdmin_email').fadeOut(8000);
                            $('#PtxthospiAdmin_email').html(emp.StringMsg);
                            $('#txthospiAdmin_email').focus();
                            return false;
                        }
                        else {
                            $("#HdnContactHid").val('');
                            $("#HdnContactHid").val(emp.Hospital_Id);
                            Savecontact_details();
                            SaveHosFileUpload_details();
                            if ($('#HdnHospital_id').val() == '') {
                                toastr.success('Hospital Details Added Successfully',
                                {
                                    //closeButton: false,
                                    progressBar: true,
                                    allowHtml: true,
                                    timeOut: 0,
                                });

                            }
                            else {
                                toastr.success('Hospital Details Updated Successfully',
                               {
                                   //closeButton: false,
                                   progressBar: true,
                                   allowHtml: true,
                                   timeOut: 0,
                               });
                            }

                            Hospital_Clear();
                            TableHospitalDetails();
                            myFunction();
                        }


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

    });
}

$("#btnhospi_submit").click(function () {
    HospitalCreation();
})

//Edit Hospital Details
function HospitalEdit(event, id) {
    debugger;
    if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 0) {

        var did = $(event).attr("data-id");
        var navigation = $(event).attr("data-nav");
        var name = $(event).attr("data-name");
        var columntype = $(event).attr("data-type");
        $('#divtype').addClass('disabled')
        $('#divsubdis').addClass('disabled')
        // $('#divdptlb').addClass('disabled')

        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 {

                         AddNewHospital();
                         $('#HdnHospital_id').val(id);

                         $('.Edit_disabled').addClass('disabled');

                         var HosTbldata = {

                             Dml_Indicator: "HES",
                             hospitalid: $('#HdnHospital_id').val()
                         }

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

                                 }
                                 else {

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


                                         $.each(data1.Table, function (i, emp) {
                                             $('#otpflag_div').hide();
                                             $('#phonenumber_div').hide();

                                             $('#txtHospitalName').val(emp.hospital_name),
                                             $('#HosSelProductCode').val(emp.product_code),
                                             $('#txthospiAdmin_email').val(emp.admin_email),
                                             $('#txtRegistration').val(emp.registeration_number),
                                              $('#Casesheet_type').val(emp.casesheet_type),
                                             LoadStore(emp.default_medicine_store);
                                              //$("#SelStore").val(emp.default_medicine_store),
                                             $('#txtContactPersonName').val(emp.first_name),
                                             $('#txthospi_mob_no').val(emp.phone_number_1),
                                             $('#txthospi_email').val(emp.email),
                                             $('a[data-toggle=Branches][data-title="' + 0 + '"]').removeClass('active');
                                             $('a[data-toggle=Branches][data-title="' + 0 + '"]').addClass('not-active');
                                             $('a[data-toggle=Branches][data-title="' + 1 + '"]').removeClass('active');
                                             $('a[data-toggle=Branches][data-title="' + 1 + '"]').addClass('not-active');
                                             $('#Branches').val(emp.is_branches);
                                             $('a[data-toggle=Branches][data-title="' + emp.is_branches + '"]').removeClass('not-active');
                                             $('a[data-toggle=Branches][data-title="' + emp.is_branches + '"]').addClass('active');
                                             $('#txthospi_addr_line1').val(emp.address_line_1);
                                             $('#HdnBranch_count').val(emp.HosBranch_count);
                                             $('#txthospi_addr_line2').val(emp.address_line_2);
                                             $('#txthospi_area').val(emp.town_village);
                                             $('#txtCountry').val(emp.country);
                                             $('#HdnCountry').val(emp.country);
                                             $('#HdnState').val(emp.state);
                                             $('#HdnCity').val(emp.city);
                                             if ($('#txtCountry').val != '') {
                                                 load_state();
                                             }

                                             if ($('#hiddenRole_id').val() == "0") {
                                                 $('#div_colorcode').removeClass('hidden')
                                                 $('#Hospital_colorcode').val(emp.color_code)

                                                 $('#div_is_formbuilder').removeClass('hidden')
                                                 if (emp.is_formbuilder == 1) {
                                                     $('a[data-toggle=is_formbuilder][data-title="1"]').removeClass('not-active');
                                                     $('a[data-toggle=is_formbuilder][data-title="1"]').addClass('active');
                                                     $('a[data-toggle=is_formbuilder][data-title="0"]').removeClass('active');
                                                     $('a[data-toggle=is_formbuilder][data-title="0"]').addClass('not-active');
                                                 }
                                                 else {
                                                     $('a[data-toggle=is_formbuilder][data-title="1"]').removeClass('active');
                                                     $('a[data-toggle=is_formbuilder][data-title="1"]').addClass('not-active');
                                                     $('a[data-toggle=is_formbuilder][data-title="0"]').removeClass('not-active');
                                                     $('a[data-toggle=is_formbuilder][data-title="0"]').addClass('active');
                                                 }

                                                 $('#is_formbuilder').val(emp.is_formbuilder)

                                                 if (emp.casesheet_print_type == 1) {
                                                     $('a[data-toggle=is_PrintType][data-title="1"]').removeClass('not-active');
                                                     $('a[data-toggle=is_PrintType][data-title="1"]').addClass('active');
                                                     $('a[data-toggle=is_PrintType][data-title="0"]').removeClass('active');
                                                     $('a[data-toggle=is_PrintType][data-title="0"]').addClass('not-active');
                                                 }
                                                 else {
                                                     $('a[data-toggle=is_PrintType][data-title="1"]').removeClass('active');
                                                     $('a[data-toggle=is_PrintType][data-title="1"]').addClass('not-active');
                                                     $('a[data-toggle=is_PrintType][data-title="0"]').removeClass('not-active');
                                                     $('a[data-toggle=is_PrintType][data-title="0"]').addClass('active');
                                                 }

                                                 $('#is_PrintType').val(emp.casesheet_print_type)
                                             }
                                             else {
                                                 $('#div_colorcode').addClass('hidden')
                                                 $('#div_is_formbuilder').addClass('hidden')
                                                 $('#div_is_PrintType').addClass('hidden')
                                             }

                                             if (emp.is_pharmacy == 1) {

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

                                             }
                                             else if (emp.is_pharmacy == 2) {
                                                 $('a[data-toggle=is_pharma][data-title="1"]').removeClass('active');
                                                 $('a[data-toggle=is_pharma][data-title="1"]').addClass('not-active');
                                                 $('a[data-toggle=is_pharma][data-title="2"]').removeClass('not-active');
                                                 $('a[data-toggle=is_pharma][data-title="2"]').addClass('active');

                                             }

                                             $('#txtShortHName').val(emp.hospital_shortname);
                                             $('#is_app').val(emp.is_app);
                                             $('#txtAppLink').val(emp.app_link);

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

                                             if (emp.is_app == 1 && parseInt($('#hiddenRole_id').val()) == 0) {
                                                 $('#div_AppLink').show();
                                             }
                                             else {
                                                 $('#div_AppLink').hide();
                                             }

                                             $('#txthospi_story').val(emp.hospital_story);
                                             $('#txthospi_MissGoal').val(emp.vision_mission_goals);
                                             $('#txtgoogle_revlink').val(emp.google_review_link);
                                             $('a[data-toggle=Accomplishments][data-title="' + 0 + '"]').removeClass('active');
                                             $('a[data-toggle=Accomplishments][data-title="' + 0 + '"]').addClass('not-active');
                                             $('#Accomplishments').val(emp.hospital_accomplishments_awards_type);
                                             $('a[data-toggle=Accomplishments][data-title="' + emp.hospital_accomplishments_awards_type + '"]').removeClass('not-active');
                                             $('a[data-toggle=Accomplishments][data-title="' + emp.hospital_accomplishments_awards_type + '"]').addClass('active');
                                             $('#txtAccomplishments').val(emp.hospital_Accomplishments_awards_Values);

                                             if (emp.hospital_accomplishments_awards_type == 1) {
                                                 $('#divAwardsupload_file').show();
                                                 $('#txtAccomplishments').hide();
                                             }
                                             else if (emp.hospital_accomplishments_awards_type == 2) {
                                                 $('#divAwardsupload_file').hide();
                                                 $('#txtAccomplishments').show();
                                             }
                                             else {
                                                 $('#divAwardsupload_file').hide();
                                                 $('#txtAccomplishments').hide();
                                             }


                                             if (emp.hospital_logo != null && emp.hospital_logo != "") {
                                                 $('#HospitalLogo_photo').show();
                                                 $('#HospitalLogo_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.hospital_logo + '" target="_blank">View</a>');
                                                 $('#HospitalLogo_pathvalue').val(emp.hospital_logo);
                                                 //$('#HospitalLogo').val(emp.hospital_logo);
                                             }
                                             if (emp.hospital_favicon != null && emp.hospital_favicon != "") {
                                                 $('#HospitalFavicon_photo').show();
                                                 $('#HospitalFavicon_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.hospital_favicon + '" target="_blank">View</a>');
                                                 $('#HospitalFavicon_pathvalue').val(emp.hospital_favicon);
                                                 // $('#HospitalFavicon').val(emp.hospital_favicon);
                                             }
                                             if (emp.hospital_images_videos != null && emp.hospital_images_videos != "") {
                                                 $('#Hospital_ImagesVideos_photo').show();
                                                 $('#Hospital_ImagesVideos_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.hospital_images_videos + '" target="_blank">Hospital_ImagesVideos</a>');
                                                 $('#Hospital_ImagesVideos_pathvalue').val(emp.hospital_images_videos);
                                                 // $('#Hospital_ImagesVideos').val(emp.hospital_images_videos);
                                             }
                                             if (emp.accreditation != null && emp.accreditation != "") {
                                                 $('#Accreditation_photo').show();
                                                 $('#Accreditation_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.accreditation + '" target="_blank">Accreditation</a>');
                                                 $('#Accreditation_pathvalue').val(emp.accreditation);
                                                 //$('#Accreditation').val(emp.accreditation);
                                             }
                                             if (emp.news_media != null && emp.news_media != "") {
                                                 $('#NewsMedia_photo').show();
                                                 $('#NewsMedia_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.news_media + '" target="_blank">NewsMedia</a>');
                                                 $('#NewsMedia_pathvalue').val(emp.news_media);
                                                 //$('#NewsMedia').val(emp.news_media);
                                             }
                                             if (emp.featured_services_facilities != null && emp.featured_services_facilities != "") {
                                                 $('#Featured_Services_Facilities_photo').show();
                                                 $('#Featured_Services_Facilities_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.featured_services_facilities + '" target="_blank">Featured_Services_Facilities</a>');
                                                 $('#Featured_Services_Facilities_pathvalue').val(emp.featured_services_facilities);
                                                 // $('#Featured_Services_Facilities').val(emp.featured_services_facilities);
                                             }

                                             if (emp.hospital_Accomplishments_awards_Values != null && emp.hospital_Accomplishments_awards_Values != "") {
                                                 $('#HospitalAccomplishments_photo').show();
                                                 $('#HospitalAccomplishments_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.hospital_Accomplishments_awards_Values + '" target="_blank">HospitalAccomplishments</a>');
                                                 $('#HospitalAccomplishments_pathvalue').val(emp.hospital_Accomplishments_awards_Values);
                                                 // $('#HospitalAccomplishments').val(emp.hospital_Accomplishments_awards_Values);
                                             }
                                         });


                                         $('#tblMobileNo tbody').empty();
                                         if (data1.Table1.length > 0) {
                                             $.each(data1.Table1, function (i, emp) {

                                                 var ikey = i + 1;
                                                 var sno = 1 + i;

                                                 var value = "<tr class='tr_input number' data-id='" + ikey + "' id='td" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdotherMobileid_" + ikey + "' value='" + emp.contact_details_id + "' /><input type='hidden' id='tdMobilenoTypeid_" + ikey + "' value=" + emp.contact_type + " /><input type='hidden' id='tdotherMobileno_" + ikey + "' value=" + emp.contact_number + " /><td id='tdMobilenoType_" + ikey + "'>" + emp.contact_type_name + "</td><td id='tdotherMobileno" + ikey + "'>" + emp.contact_number + "</td><td><button class='btn-xs btn btn-edit btn-add' onclick='OMobileedit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn-xs btn btn-delete btn-add' onclick='OMobiledelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";

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

                                         $('#tblHSFileUP tbody').empty();
                                         if (data1.Table2.length > 0) {
                                             $.each(data1.Table2, function (i, emp) {

                                                 var ikey = i;
                                                 var sno = 1 + i;

                                                 var value = "<tr class='tr_input number' data-id='" + ikey + "' id='td_" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdfiletype_detailsid_" + ikey + "' value=" + emp.filetype_detailsid + " /><input type='hidden' id='tdFileTypeid_" + ikey + "' value=" + emp.filetype_id + " /><input type='hidden' id='tdFileDescription_" + ikey + "' value=" + emp.file_description + " /><input type='hidden' id='tdFilePath_" + ikey + "' value=" + emp.upload_file + " /><td id='tdFileTypeName_" + ikey + "'>" + emp.filetype_name + "</td><td id='tdFileDescription" + ikey + "'>" + emp.file_description + "</td><td id='tdFilePath" + ikey + "'>" + emp.upload_file + "</td><td><button class='btn btn-edit  btn-xs btn-add' onclick='FilePathEdit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn btn-delete btn-xs' onclick='FilePathDelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";

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



                                     }
                                     else {
                                         console.log(data);
                                     }
                                 }
                             },
                             error: function (data) {

                             }
                         });

                     }
                 }
             }
         });
    }
    else {
        toastr.warning('You dont have rights to access this page',

           {
          //closeButton: false,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,
           });
    }

}

//Clear All Hospital Details Screen Fields
function Hospital_Clear() {

    //$('#tblMobileNo tbody').empty();
    //$('#tblHSFileUP tbody').empty();
    $('.Edit_disabled').removeClass('disabled');
    $('#HdnHospital_id').val('');
    $('#HdnState').val('');
    $('#HdnCity').val('');
    $('#txtHospitalName').val('');
    $('#txtRegistration').val('');
    $('#txtContactPersonName').val('');
    $('#txthospi_mob_no').val('');
    $('#txthospi_email').val('');
    $('a[data-toggle=Branches][data-title="' + $('#Branches').val() + '"]').removeClass('active');
    $('a[data-toggle=Branches][data-title="' + $('#Branches').val() + '"]').addClass('not-active');
    $('a[data-toggle=Branches][data-title="' + 0 + '"]').removeClass('not-active');
    $('a[data-toggle=Branches][data-title="' + 0 + '"]').addClass('active');
    $('#Branches').val(0);
    $('#txthospi_addr_line1').val('');

    $('#Hospital_colorcode').val('');

    $('#txthospi_addr_line2').val('');
    $('#txthospi_area').val('');
    $('#txtState').val('');
    $('#txtCity').val('');
    $('#txtCountry').val(0);
    $('#txthospi_story').val('');
    $('#txthospi_MissGoal').val('');
    $('#txtgoogle_revlink').val('');
    $('a[data-toggle=Accomplishments][data-title="' + $('#Accomplishments').val() + '"]').removeClass('active');
    $('a[data-toggle=Accomplishments][data-title="' + $('#Accomplishments').val() + '"]').addClass('not-active');
    $('a[data-toggle=Accomplishments][data-title="' + 0 + '"]').removeClass('not-active');
    $('a[data-toggle=Accomplishments][data-title="' + 0 + '"]').addClass('active');
    $('#Accomplishments').val(0);
    $('#txtAccomplishments').val('');

    $('#divAwardsupload_file').hide();
    $('#txtAccomplishments').hide();

    $('#HospitalLogo_photo').hide();
    $('#HospitalLogo_photo').empty();
    $('#HospitalLogo_pathvalue').val('');
    $('#HospitalLogo').val('');


    $('#HospitalFavicon_photo').hide();
    $('#HospitalFavicon_photo').empty();
    $('#HospitalFavicon_pathvalue').val('');
    $('#HospitalFavicon').val('');

    $('#Hospital_ImagesVideos_photo').hide();
    $('#Hospital_ImagesVideos_photo').empty();
    $('#Hospital_ImagesVideos_pathvalue').val('');
    $('#Hospital_ImagesVideos').val('');

    $('#Accreditation_photo').hide();
    $('#Accreditation_photo').empty();
    $('#Accreditation_pathvalue').val('');
    $('#Accreditation').val('');

    $('#NewsMedia_photo').hide();
    $('#NewsMedia_photo').empty();
    $('#NewsMedia_pathvalue').val('');
    $('#NewsMedia').val('');


    $('#Featured_Services_Facilities_photo').hide();
    $('#Featured_Services_Facilities_photo').empty();
    $('#Featured_Services_Facilities_pathvalue').val('');
    $('#Featured_Services_Facilities').val('');

    $('#HospitalAccomplishments_photo').hide();
    $('#HospitalAccomplishments_photo').empty();
    $('#HospitalAccomplishments_pathvalue').val('');
    $('#HospitalAccomplishments').val('');
    $('#HdnBranHospital_id').val('');

    $('#HosSelProductCode').val(0);
    $('#txthospiAdmin_email').val('');
    $('#tblHSFileUP tbody').empty();
    $('#tblMobileNo tbody').empty();

    $('#Hos_UploadFile_pathvalue').val('');
    $('#Hos_UploadFile_photo').empty();
    $('#txtUPDescription').val('');
    $('#ddUPFileType').val(0);
    $('#Hos_UploadFile').val('');

    $('#txt_Phone_number').val('');
    $('#is_otp').val('');
    $('#phonenumber_div').hide();
    $('a[data-toggle=is_otp][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=is_otp][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');

    $('#txtShortHName').val('');
    $('#is_app').val(0);
    $('#txtAppLink').val('');
    $('#div_AppLink').hide();
    $('a[data-toggle=is_app][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=is_app][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    $('#HdnBranch_count').val('');
    $('#otpflag_div').show();

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

}

// Delete Hospital details
function DELHospital(event, id) {

    $('#HdnHospital_id').val(id);

    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    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 {
                     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 Hospital?',
                         {
                             closeButton: true,
                             progressBar: true,
                             allowHtml: true,
                             timeOut: 0,

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

                                     var HOSDEl = {

                                         Dml_Indicator: 'HDUC',
                                         hospitalid: $('#HdnHospital_id').val()
                                     }

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

                                             }
                                             else {

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

                                                     if (data1.Table[0].User_count > 0) {
                                                         ConfirmHospitalDel();
                                                     }
                                                     else {
                                                         toastr.success('Hospital Details Deleted Successfully',
                                                          {
                                                              //closeButton: false,
                                                              progressBar: true,
                                                              allowHtml: true,
                                                              timeOut: 0,
                                                          });

                                                         $('#HdnHospital_id').val('');
                                                         TableHospitalDetails();
                                                     }

                                                 }
                                                 else {
                                                     console.log(data);
                                                 }

                                             }
                                         },
                                         error: function (data) {

                                         }
                                     });
                                 });
                             }
                         });
                 }
             }
         }
     });
}

function ConfirmHospitalDel() {
    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>", 'This Hospital has more Patients and Users. Do you still want to Delete?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

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

                  var HOSDEl = {

                      Dml_Indicator: 'HOSDEL',
                      hospitalid: $('#HdnHospital_id').val()
                  }

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

                          }
                          else {

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

                                  toastr.success('Hospital Details Deleted Successfully',
                                   {
                                       //closeButton: false,
                                       progressBar: true,
                                       allowHtml: true,
                                       timeOut: 0,
                                   });

                                  $('#HdnHospital_id').val('');
                                  TableHospitalDetails();

                              }
                              else {
                                  console.log(data);
                              }

                          }
                      },
                      error: function (data) {

                      }
                  });
              });
          }
      });
}

// Show Hospital Name and Logo
function HBranch_popup(event, Hospitalid, Hospitallogo, product_code) {
    Branch_Clear();
    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    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 {

                     $('#branchcreation_popup').modal('show');

                     //$("#imgHospital_Logo").attr("src", "" + $('#hdnShowHospital_Logo').val() + "" + $('#HospitalId').val() + "/" + 1 + "/" + "HospitalandBranches/" + Hospitallogo);
                     $("#imgHospital_Logo").attr("src", "" + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + Hospitallogo);
                     $('#lbl_HospitalName').html($('#' + Hospitalid).val());
                     $('#HdnBranHospital_id').val(Hospitalid);
                     $('#SelProductCode').val(product_code);
                     $('#SelProductCode').prop('disabled', true);
                     TableBranchDetails();

                 }
             }
         }
     });


}

//Hospital Branch functions Start //

$("#btnBranch_Submit").click(function () {

    if ($.trim($("#txtBranchName").val()) == "") {
        $('#PtxtBranchName').show();
        $('#PtxtBranchName').fadeOut(8000);
        $('#PtxtBranchName').html('Enter Branch Name');
        $('#txtBranchName').val('');
        $('#txtBranchName').focus();
        return false;
    }
    if ($.trim($("#txtBranch_ContactPerson").val()) == "") {
        $('#PtxtBranch_ContactPerson').show();
        $('#PtxtBranch_ContactPerson').fadeOut(8000);
        $('#PtxtBranch_ContactPerson').html('Enter Contact Person Name');
        $('#txtBranch_ContactPerson').val('');
        $('#txtBranch_ContactPerson').focus();
        return false;
    }
    if ($.trim($("#txtbranch_MobileNo").val()) == "") {
        $('#Ptxtbranch_MobileNo').show();
        $('#Ptxtbranch_MobileNo').fadeOut(8000);
        $('#Ptxtbranch_MobileNo').html('Enter Mobile No');
        $('#txtbranch_MobileNo').val('');
        $('#txtbranch_MobileNo').focus();
        return false;
    }
    if ($.trim($("#txtbranch_EmailId").val()) == "") {
        $('#Ptxtbranch_EmailId').show();
        $('#Ptxtbranch_EmailId').fadeOut(8000);
        $('#Ptxtbranch_EmailId').html('Enter Email Id');
        $('#txtbranch_EmailId').val('');
        $('#txtbranch_EmailId').focus();
        return false;
    }
    if ($.trim($("#is_otpbr").val()) == '') {
        $('#Pis_otpbr').show();
        $('#Pis_otpbr').fadeOut(8000);
        $('#Pis_otpbr').html('Select Discount Authorization');
        $('#is_otpbr').val('');
        $('#is_otpbr').focus();
        return false;
    }
    if ($('#is_otpbr').val() == 1) {
        if ($('#txt_Phone_numberbr').val() == '') {
            $('#Ptxt_Phone_numberbr').show();
            $('#Ptxt_Phone_numberbr').fadeOut(8000);
            $('#Ptxt_Phone_numberbr').html('Enter Phone Number');
            $('#txt_Phone_numberbr').val('');
            $('#txt_Phone_numberbr').focus();
            return false;
        }
    }
    if ($.trim($("#txtBranch_Address1").val()) == "") {
        $('#PtxtBranch_Address1').show();
        $('#PtxtBranch_Address1').fadeOut(8000);
        $('#PtxtBranch_Address1').html('Enter Address line 1');
        $('#txtBranch_Address1').val('');
        $('#txtBranch_Address1').focus();
        return false;
    }
    if ($.trim($("#txtBranch_Area").val()) == "") {
        $('#PtxtBranch_Area').show();
        $('#PtxtBranch_Area').fadeOut(8000);
        $('#PtxtBranch_Area').html('Enter Area');
        $('#txtBranch_Area').val('');
        $('#txtBranch_Area').focus();
        return false;
    }
    if ($.trim($("#ddbranch_Country").val()) == "") {
        $('#Pddbranch_Country').show();
        $('#Pddbranch_Country').fadeOut(8000);
        $('#Pddbranch_Country').html('Select Country ');
        $('#ddbranch_Country').val('');
        $('#ddbranch_Country').focus();
        return false;
    }
    if ($.trim($("#ddbranch_State").val()) == "") {
        $('#Pddbranch_State').show();
        $('#Pddbranch_State').fadeOut(8000);
        $('#Pddbranch_State').html('Select State');
        $('#ddbranch_State').val('');
        $('#ddbranch_State').focus();
        return false;
    }
    if ($.trim($("#ddbranch_City").val()) == "") {
        $('#Pddbranch_City').show();
        $('#Pddbranch_City').fadeOut(8000);
        $('#Pddbranch_City').html('Select City');
        $('#ddbranch_City').val('');
        $('#ddbranch_City').focus();
        return false;
    }
    if ($.trim($("#is_checkin").val()) == '') {
        $('#Pis_checkin').show();
        $('#Pis_checkin').fadeOut(8000);
        $('#Pis_checkin').html('Select Is Bill CheckIn');
        $('#is_checkin').val('');
        $('#is_checkin').focus();
        return false;
    }

    // Hospital Branch License Details validation Start //

    var subscription_start_date = '';
    var subscription_end_date = '';
    if ($('#txtSubscriptionStartDate').val() != '' && $('#txtSubscriptionStartDate').val() != null) {
        var startdate = $('#txtSubscriptionStartDate').val();
        var splitdate = startdate.split('/');
        var formated_date = splitdate[2] + '-' + splitdate[1] + '-' + splitdate[0];
        subscription_start_date = (formated_date);
    }
    if ($('#txtSubscriptionEndDate').val() != '' && $('#txtSubscriptionEndDate').val() != null) {
        var startdate = $('#txtSubscriptionEndDate').val();
        var splitdate = startdate.split('/');
        var formated_date = splitdate[2] + '-' + splitdate[1] + '-' + splitdate[0];
        subscription_end_date = (formated_date);
    }

    if ($('#txtSubscriptionStartDate').val() == '' || $('#txtSubscriptionStartDate').val() == null) {
        $('#Pstdate_err').show();
        $('#Pstdate_err').fadeOut(8000);
        $('#Pstdate_err').html('Select Subscription Start Date');
        $('#txtSubscriptionStartDate').val('');
        $('#txtSubscriptionStartDate').focus();
        return false;
    }

    if ($('#txtSubscriptionEndDate').val() == '' || $('#txtSubscriptionEndDate').val() == null) {
        $('#Penddate_err').show();
        $('#Penddate_err').fadeOut(8000);
        $('#Penddate_err').html('Select Subscription End Date');
        $('#txtSubscriptionEndDate').val('');
        $('#txtSubscriptionEndDate').focus();
        return false;
    }

    if ($('#txtNoofLicense').val() == '' || $('#txtNoofLicense').val() == null) {
        $('#PtxtNoofLicense').show();
        $('#PtxtNoofLicense').fadeOut(8000);
        $('#PtxtNoofLicense').html('Enter No of License');
        $('#txtNoofLicense').val('');
        $('#txtNoofLicense').focus();
        return false;
    }

    if ($('#SelProductCode').val() == '' || $('#SelProductCode').val() == 0) {
        $('#Phospi_SelProductCode_err').show();
        $('#Phospi_SelProductCode_err').fadeOut(8000);
        $('#Phospi_SelProductCode_err').html('Select Product');
        $('#SelProductCode').val('');
        $('#SelProductCode').focus();
        return false;
    }

    // Hospital License Details validation End //


    var BranchCreationData = {

        Dml_Indicator: "HBI",
        hospitalid: $('#HdnBranHospital_id').val(),
        branch_id: ($('#HdnBranch_id').val() == '') ? 0 : $('#HdnBranch_id').val(),
        hospital_name: $('#lbl_HospitalName').html(),
        branch_name: $('#txtBranchName').val(),
        branch_description: $('#txtBranchDescription').val(),
        branch_image: $('#BranchImage_pathvalue').val(),
        short_name: $('#txtshtBranchName').val(),
        contact_person_name: $('#txtBranch_ContactPerson').val(),
        contact_no: $('#txtbranch_MobileNo').val(),
        email_id: $('#txtbranch_EmailId').val(),


        address_line_one: $('#txtBranch_Address1').val(),
        address_line_two: $('#txtBranch_Address2').val(),
        area: $('#txtBranch_Area').val(),
        country: $('#ddbranch_Country').val(),
        state: $('#ddbranch_State').val(),
        city: $('#ddbranch_City').val(),

        subscription_start_date: subscription_start_date,
        subscription_end_date: subscription_end_date,
        no_of_license: $('#txtNoofLicense').val(),
        product_code: $('#SelProductCode').val(),
        is_discount_authorization: ($('#is_otpbr').val() == '') ? 2 : $('#is_otpbr').val(),
        auth_phone_number: $('#txt_Phone_numberbr').val(),
        enable_casesheet_edit: (($('#chkEnableCasesheetEdit').prop('checked')) ? 1 : 0),
        is_billcheckin: ($('#is_checkin').val() == '') ? 2 : $('#is_checkin').val()
    }

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

            }
            else {

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

                    if (data1.Table[0].message == "already") {

                        toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>OK</button>", 'The Entered Short Name Already Exists',
                        {
                            closeButton: true,
                            progressBar: true,
                            allowHtml: true,
                            timeOut: 20000000,

                            onShown: function (toast) {
                                $("#confirmationRevertYes").click(function () {
                                })
                            }
                        })
                        $('#txtshtBranchName').val('');
                        $('#txtshtBranchName').focus();
                        return false;
                    }
                    $.each(data1.Table, function (i, emp) {

                        if ($('#HdnBranch_id').val() == '') {
                            toastr.success('Branch Details Added Successfully',
                            {
                                //closeButton: false,
                                progressBar: true,
                                allowHtml: true,
                                timeOut: 0,
                            });
                        }
                        else {
                            toastr.success('Branch Details Updated Successfully',
                           {
                               //closeButton: false,
                               progressBar: true,
                               allowHtml: true,
                               timeOut: 0,
                           });
                        }

                    });
                    Branch_Clear();
                    TableBranchDetails();
                    TableHospitalDetails();

                    if ($('#hiddenRole_id').val() == 2) {
                        $('#btnBranch_Submit').addClass('hidden');
                    }
                }
                else {
                    console.log(data);
                }
            }
        }

    });

})

//Branch Detail Table Function
function TableBranchDetails() {


    var HosTbldata = {

        Dml_Indicator: 'BCHTS',
        hospitalid: $('#HdnBranHospital_id').val()
    }

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

            }
            else {

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

                    tr = $('<table class="table table-bordered dt-responsive" />');

                    tr.append("<thead><tr><th>Branch Name</th><th>Address</th><th>Contact Person</th><th>Contact No</th><th>No.of.Licenses</th><th>Email ID</th><th>Actions</th></tr></thead><tbody>");

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

                        var BranchInAorAct = '';

                        view = '<button type="button" class="btn btn-edit btn-xs" onclick=HBranchEdit("' + emp.hospital_branch_id + '");><i class="fa fa-pencil" aria-hidden="true"></i></button>'

                        Del = '<button type="button" class="btn btn-delete btn-xs Hide_btn" onclick=DELBranch("' + emp.hospital_branch_id + '");><i class="fa fa-trash-o" aria-hidden="true"></i></button>';

                        if (emp.Branch_status == 1) {
                            BranchInAorAct = '<button id="btnBInAorAct_' + emp.hospital_branch_id + '" type="button" class="btn btn-xs Hide_btn" onclick=BranchInActorAct("' + emp.hospital_branch_id + '");>InActive</button>';
                        }
                        else if (emp.Branch_status == 2) {
                            BranchInAorAct = '<button id="btnBInAorAct_' + emp.hospital_branch_id + '" type="button" class="btn btn-xs Hide_btn" onclick=BranchInActorAct("' + emp.hospital_branch_id + '");>Active</button>';
                            view = '';
                        }
                        else {
                            BranchInAorAct = '';
                        }

                        other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + view + ' ' + 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=""><li class="text-left">' + BranchInAorAct + '</li></ul></div></div>';

                        Branch_data = "<tr><td>" + emp.branch_name + "</td><td>" + emp.Address + "</td><td>" + emp.contact_personname + "</td><td>" + emp.mobile_no + "</td><td>" + emp.no_of_license + "</td><td>" + emp.email + "</td><td class='col-sm-1'>" + other_info + "</td></tr>";
                        tr.append(Branch_data);

                    });

                    tr.append("</tbody></table>");
                    $('#TblHospitalBranch').html(tr);

                    //if ($('#hiddenRole_id').val() == 2) {
                    //    $('.Hide_btn').addClass('hidden');
                    //}
                    //else {
                    //    $('.Hide_btn').removeClass('hidden');
                    //}

                    if ($('#hiddenRole_id').val() == 0) {
                        $('.Hide_btn').removeClass('hidden');
                        
                    }
                    else {
                        $('.Hide_btn').addClass('hidden');
                    }
                }
                else {
                    console.log(data);
                }

            }
        },
        error: function (data) {

        }
    });

}

//Edit Hospital Details
function HBranchEdit(id) {
    debugger
    //if ($('#HdnBranHospital_id').val() == '') {
    //    $('#branchcreation_popup').modal('show');
    //}
    if ($('#hiddenRole_id').val() == 2 || $('#hiddenRole_id').val() == 0 || $('#HospitalBranchID').val() == id) {

        $('#branchcreation_popup').modal('show');
        $('#btnBranch_Submit').removeClass('hidden');
        $('#HdnBranch_id').val(id);

        var HosTbldata = {

            Dml_Indicator: "BCHES",
            branch_id: $('#HdnBranch_id').val()
        }

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

                }
                else {

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

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

                            $('#HdnBranHospital_id').val(emp.hospitalid),
                            $('#lbl_HospitalName').html(emp.hospital_name),
                            $('#txtBranchName').val(emp.branch_name),
                              $('#txtshtBranchName').val(emp.short_name),
                            $('#txtBranchDescription').val(emp.description);
                            if (emp.image != null && emp.image != "") {
                                $('#BranchImage_photo').show();
                                $('#BranchImage_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + emp.image + '" target="_blank"><i class="fa fa-eye" aria-hidden="true"></i></a>');
                                $('#BranchImage_pathvalue').val(emp.image);
                            }
                            $('#txtBranch_ContactPerson').val(emp.contact_personname),
                            $('#txtbranch_MobileNo').val(emp.mobile_no),
                            $('#txtbranch_EmailId').val(emp.email),

                            $('#chkEnableCasesheetEdit').prop('checked', (emp.enable_previous_casesheet_edit == 1 || emp.enable_previous_casesheet_edit == "1") ? true : false);

                            $('#txtBranch_Address1').val(emp.address_line_1),
                            $('#txtBranch_Address2').val(emp.address_line_2),
                            $('#txtBranch_Area').val(emp.town_village),
                            $('#ddbranch_Country').val(emp.country),
                            $('#HdnCountry').val(emp.country);
                            $('#ddbranch_State').val(emp.state),
                            $('#ddbranch_City').val(emp.city)
                            $('#HdnState').val(emp.state);
                            $('#HdnCity').val(emp.city);
                            $('#txtSubscriptionStartDate').val(emp.subscription_start_date);
                            $('#txt_Phone_numberbr').val(emp.auth_phone_number);

                            $('#is_otpbr').val('');
                            $('a[data-toggle=is_otpbr][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
                            $('a[data-toggle=is_otpbr][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
                            $('#is_otpbr').val(emp.is_discount_authorization);
                            $('a[data-toggle=is_otpbr][data-title="' + emp.is_discount_authorization + '"]').removeClass('not-active');
                            $('a[data-toggle=is_otpbr][data-title="' + emp.is_discount_authorization + '"]').addClass('active');                            
                            if (emp.is_discount_authorization == 1) {
                                $('#phonenumber_divbr').show();
                            }
                            else {
                                $('#phonenumber_divbr').hide();
                            }

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

                            $('#txtSubscriptionEndDate').val(emp.subscription_end_date);
                            $('#txtNoofLicense').val(emp.no_of_license);
                            $('#SelProductCode').val(emp.product_code).attr('disabled', true);
                            //$('#SelProductCode').prop('disabled', true);
                            if ($('#ddbranch_Country').val != '') {
                                load_state();
                            }
                            $("#imgHospital_Logo").attr("src", "" + $('#hdnShowHospital_Logo').val() + "HospitalandBranchesImage/" + emp.hospital_logo);

                        });
                        TableBranchDetails();

                    }
                    else {
                        console.log(data);
                    }

                }
            },
            error: function (data) {

            }
        });
    }
    else {
        toastr.warning('You dont have rights to access this page',

           {
               //closeButton: false,
               progressBar: true,
               allowHtml: true,
               timeOut: 0,
           });
    }
}

//Clear All Branch Details Popup Fields
function Branch_Clear() {

    $('#HdnBranch_id').val('');
    $('#txtBranchName').val('');
    $('#txtBranchDescription').val('');
    $('#txtshtBranchName').val('');
    $('#BranchImage_photo').hide();
    $('#BranchImage_photo').empty();
    $('#BranchImage_pathvalue').val('');

    $('#txtBranch_ContactPerson').val('');
    $('#txtbranch_MobileNo').val('');
    $('#txtbranch_EmailId').val('');
    $('#chkEnableCasesheetEdit').prop('checked', false);

    $('#txtBranch_Address1').val('');
    $('#txtBranch_Address2').val('');
    $('#txtBranch_Area').val('');

    $('#txtSubscriptionStartDate').val('');

    $('#txtSubscriptionEndDate').val('');
    $('#txtNoofLicense').val('');
    //$('#SelProductCode').val('');
    $('#ddbranch_Country').val(0);
    $('#ddbranch_State').val(0);
    $('#ddbranch_City').val(0);
    $('#txt_Phone_numberbr').val('');
    $('#is_otpbr').val('');
    $('#is_checkin').val('');
    $('#phonenumber_divbr').hide();
    $('a[data-toggle=is_otpbr][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=is_otpbr][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=is_checkin][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
    $('a[data-toggle=is_checkin][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
}

function DELBranch(id) {
    $('#HdnBranch_id').val(id);

    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 Branch?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

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

                  var HOSDEl = {

                      Dml_Indicator: 'HBPC',
                      branch_id: $('#HdnBranch_id').val()
                  }

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

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

                          }
                          else {

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

                                  if (data1.Table[0].User_count > 0) {
                                      ConfirmDELBranch(id);
                                  }
                                  else if (data1.Table[0].message == 'notdelete') {

                                      toastr.warning('You have no rights to Delete this Branch.',
                                       {
                                           //closeButton: false,
                                           progressBar: true,
                                           allowHtml: true,
                                           timeOut: 0,
                                       });
                                  }
                                  else {
                                      toastr.success('Hospital Branch Details Deleted Successfully',
                                       {
                                           //closeButton: false,
                                           progressBar: true,
                                           allowHtml: true,
                                           timeOut: 0,
                                       });

                                      $('#HdnHospital_id').val('');
                                      TableBranchDetails();
                                      TableHospitalDetails();
                                  }

                              }
                              else {
                                  console.log(data);
                              }

                          }
                      },
                      error: function (data) {

                      }
                  });
              });
          }
      });

}

// Delete Branch details
function ConfirmDELBranch(id) {
    $('#HdnBranch_id').val(id);

    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>", 'This branch has more Patients and Users. Do you still want to Delete the Branch?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

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

                  var HOSDEl = {

                      Dml_Indicator: 'BCHDEL',
                      branch_id: $('#HdnBranch_id').val()
                  }

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

                          }
                          else {

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

                                  toastr.success('Branch Details Deleted Successfully',
                                   {
                                       //closeButton: false,
                                       progressBar: true,
                                       allowHtml: true,
                                       timeOut: 0,
                                   });

                                  $('#HdnBranch_id').val('');
                                  TableBranchDetails();
                                  TableHospitalDetails();

                              }
                              else {
                                  console.log(data);
                              }

                          }
                      },
                      error: function (data) {

                      }
                  });
              });
          }
      });

}

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

    var MobilenoType = $('#ddMobilenoType option:selected').data('id');

    var MobilenoTypeid = $('#ddMobilenoType').val();
    var otherMobileno = $('#txtotherMobileno').val();


    if ($('#ddMobilenoType').val() == 0) {
        $('#PddMobilenoType').show();
        $('#PddMobilenoType').fadeOut(8000);
        $('#PddMobilenoType').html('Select Mobile No');
        $('#ddMobilenoType').val(0);
        $('#ddMobilenoType').focus();
        return false;
    }

    if ($('#txtotherMobileno').val() == '') {
        $('#PtxtotherMobileno').show();
        $('#PtxtotherMobileno').fadeOut(8000);
        $('#PtxtotherMobileno').html('Enter Mobile No');
        $('#txtotherMobileno').val('');
        $('#txtotherMobileno').focus();
        return false;
    }

    if (otherMobileno.length < 10) {
        $('#PtxtotherMobileno').show();
        $('#PtxtotherMobileno').fadeOut(8000);
        $('#PtxtotherMobileno').html('Enter correct Mobile No');
        $('#txtotherMobileno').val('');
        $('#txtotherMobileno').focus();
        return false;
    }

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

    //    var max = 0;

    //    //$('.number').each(function () {
    //    //    debugger;
    //    //    var value = parseInt($(this).data('id'));

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

    //    //});
    //    var Tblcount = $('#tblMobileNo tbody').length();
    //    var ikey = Tblcount + 1;
    //    sno = ikey;
    //}

    var value = "<tr class='' data-id='" + ikey + "' id='td" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdotherMobileid_" + ikey + "' value='0' /><input type='hidden' id='tdMobilenoTypeid_" + ikey + "' value=" + MobilenoTypeid + " /><input type='hidden' id='tdotherMobileno_" + ikey + "' value=" + otherMobileno + " /><td id='tdMobilenoType_" + ikey + "'>" + MobilenoType + "</td><td id='tdotherMobileno" + ikey + "'>" + otherMobileno + "</td><td><button class='btn-xs btn btn-edit btn-add' onclick='OMobileedit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn-xs btn btn-delete btn-add' onclick='OMobiledelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#tblMobileNo > tbody:last').append(value);
    $('#ddMobilenoType').val('0');
    $('#txtotherMobileno').val('');

});

function OMobileedit(val) {


    var tdMobilenoTypeid = $('#tdMobilenoTypeid_' + val).val();
    var tdotherMobileno = $('#tdotherMobileno' + val).html() == '/' ? '' : $('#tdotherMobileno' + val).html();

    $('#ddMobilenoType').val(tdMobilenoTypeid);
    $('#txtotherMobileno').val(tdotherMobileno);
    $('#Hdnrowid').val(val);

    $('#Btn_otherMobileno').hide();
    $('#Btn_editMobileno').removeClass('hidden');

}

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

    var MobilenoType = $('#ddMobilenoType option:selected').data('id');

    var MobilenoTypeid = $('#ddMobilenoType').val();
    var otherMobileno = $('#txtotherMobileno').val();

    if ($('#ddMobilenoType').val() == 0) {
        $('#PddMobilenoType').show();
        $('#PddMobilenoType').fadeOut(8000);
        $('#PddMobilenoType').html('Select Mobile No');
        $('#ddMobilenoType').val(0);
        $('#ddMobilenoType').focus();
        return false;
    }

    if ($('#txtotherMobileno').val() == '') {
        $('#PtxtotherMobileno').show();
        $('#PtxtotherMobileno').fadeOut(8000);
        $('#PtxtotherMobileno').html('Enter Mobile No');
        $('#txtotherMobileno').val('');
        $('#txtotherMobileno').focus();
        return false;
    }

    if (otherMobileno.length < 10) {
        $('#PtxtotherMobileno').show();
        $('#PtxtotherMobileno').fadeOut(8000);
        $('#PtxtotherMobileno').html('Enter correct Mobile No');
        $('#txtotherMobileno').val('');
        $('#txtotherMobileno').focus();
        return false;
    }

    var rowid = $('#Hdnrowid').val();
    $('#tdMobilenoType_' + rowid).html(MobilenoType);
    $('#tdotherMobileno' + rowid).html(otherMobileno);
    $('#tdMobilenoTypeid_' + rowid).val(MobilenoTypeid);
    $('#tdotherMobileno_' + rowid).val(otherMobileno);

    $('#ddMobilenoType').val('0');
    $('#txtotherMobileno').val('');
    $('#Btn_otherMobileno').show();
    $('#Btn_editMobileno').addClass('hidden');
    //$('#Btn_editMobileno').hide();

    $('#Hdnrowid').val('');

});


// delete 
function OMobiledelete(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 Mobile No?',
       {

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

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

                   var OMBid = $("#tdotherMobileid_" + val).val();
                   if (OMBid != "0") {

                       var servicevalues = {
                           Dml_Indicator: "HOCDL",
                           contact_details_id: $("#tdotherMobileid_" + val).val()

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

                   }
               });
           }
       });
}

function Savecontact_details() {

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

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

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

        debugger;

        var count_OCdetails_id = $('#tdotherMobileid_' + (i)).val();
        var count_OCcontact_number = $('#tdotherMobileno_' + (i)).val();
        var count_OCcontact_type = $('#tdMobilenoTypeid_' + (i)).val();

        var OCdetails_id = $('#tdotherMobileid_' + (i)).val();
        var OCcontact_number = $('#tdotherMobileno_' + (i)).val();
        var OCcontact_type = $('#tdMobilenoTypeid_' + (i)).val();

        if (typeof OCdetails_id === "undefined") {
            OCdetails_id = $('#tdotherMobileid_' + (i + 1)).val();
        }
        else {
            OCdetails_id = $('#tdotherMobileid_' + (i)).val();
        }

        if (typeof OCcontact_number === "undefined") {
            OCcontact_number = $('#tdotherMobileno_' + (i + 1)).val()
        }
        else {
            OCcontact_number = $('#tdotherMobileno_' + (i)).val();
        }

        if (typeof OCcontact_type === "undefined") {
            OCcontact_type = $('#tdMobilenoTypeid_' + (i + 1)).val();
        }
        else {
            OCcontact_type = $('#tdMobilenoTypeid_' + (i)).val();
        }

        if (typeof count_OCdetails_id === "undefined" && typeof count_OCcontact_number === "undefined" && typeof count_OCcontact_type === "undefined") {
            i++;
            count++;
        }

        Contact_details.push({
            contact_details_id: OCdetails_id,
            contact_number: OCcontact_number == '/' ? '' : OCcontact_number,
            contact_type: OCcontact_type,
            created_by: $("#hiddenUser_id").val(),
            hospital_id: $("#HdnContactHid").val(),
            Dml_Indicator: "HCI"
        })
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalOther_ContactDetails_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;
                $('#tblMobileNo tbody').empty();
                //$("#HdnContactHid").val('');
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

//Hospital File Upload Type Dropdown.

function HospitalFileType() {
    var FileType = {
        Dml_Indicator: "HFUS"
    }

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

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

                    var default_opt = '<option value="0" data-id="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        FileType = FileType + '<option value="' + emp.filetype_id + '" data-id="' + emp.filetype_name + '">' + emp.filetype_name + '</option>';
                    });
                    $('#ddUPFileType').append(default_opt + FileType);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

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

    var FileTypeName = $('#ddUPFileType option:selected').data('id');

    var FileTypeid = $('#ddUPFileType').val();
    var FileDescription = $('#txtUPDescription').val();
    var FilePath = $('#Hos_UploadFile_pathvalue').val();
    var FilePathName = $('#Hos_UploadFile_pathvalue').val();


    if ($('#ddUPFileType').val() == 0) {
        $('#PddUPFileType').show();
        $('#PddUPFileType').fadeOut(8000);
        $('#PddUPFileType').html('Select File Type');
        $('#ddUPFileType').val(0);
        $('#ddUPFileType').focus();
        return false;
    }

    if ($('#Hos_UploadFile_pathvalue').val() == '') {
        $('#PHos_UploadFile').show();
        $('#PHos_UploadFile').fadeOut(8000);
        $('#PHos_UploadFile').html('Choose File');
        $('#Hos_UploadFile_pathvalue').val('');
        $('#Hos_UploadFile_pathvalue').focus();
        return false;
    }

    var ikey = "0";
    var sno = 1;
    var rowcount = $('#tblHSFileUP >tbody >tr').length;
    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;
    }

    var value = "<tr class='tr_input number' data-id='" + ikey + "' id='td_" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdfiletype_detailsid_" + ikey + "' value='0' /><input type='hidden' id='tdFileTypeid_" + ikey + "' value=" + FileTypeid + " /><input type='hidden' id='tdFileDescription_" + ikey + "' value=" + FileDescription + " /><input type='hidden' id='tdFilePath_" + ikey + "' value=" + FilePath + " /><input type='hidden' id='tdFileName_" + ikey + "' value=" + $('#Hos_UploadFile').val() + " /><td id='tdFileTypeName_" + ikey + "'>" + FileTypeName + "</td><td id='tdFileDescription" + ikey + "'>" + FileDescription + "</td><td id='tdFilePath" + ikey + "'>" + FilePath + "</td><td class='disp_if'><button class='btn-xs btn btn-edit btn-add' onclick='FilePathEdit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button> <button class='btn-xs btn btn-delete btn-add' onclick='FilePathDelete(\"" + ikey + "\")'><i class='fa fa-trash-o' aria-hidden='true'></i></button></td></tr>";

    $('#tblHSFileUP > tbody:last').append(value);
    //$('#ddMobilenoType').val('0');
    $('#Hos_UploadFile').val('');
    $('#Hos_UploadFile_pathvalue').val('');
    $('#Hos_UploadFile_photo').empty();
    $('#txtUPDescription').val('');
    $('#ddUPFileType').val(0);

});

function FilePathEdit(val) {


    $('#Hos_UploadFile').attr('disabled', false);
    var tdFileDescription = '';

    var tdFileTypeid = $('#tdFileTypeid_' + val).val();
    tdFileDescription = $('#tdFileDescription_' + val).val() == '/' ? '' : $('#tdFileDescription_' + val).val();
    var tdFilePath = $('#tdFilePath_' + val).val();

    var FileTypeName = $('#tdFileTypeName_' + val).html();

    if (tdFilePath != null && tdFilePath != "") {
        $('#Hos_UploadFile_photo').empty();
        $('#Hos_UploadFile_photo').show();
        $('#Hos_UploadFile_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "HospitalandBranchesImage/" + tdFilePath + '" target="_blank">"' + FileTypeName + '"</a>');
        $('#Hos_UploadFile_pathvalue').val(tdFilePath);
    }

    $('#ddUPFileType').val(tdFileTypeid);
    $('#txtUPDescription').val(tdFileDescription);
    $('#Hdnrowid').val(val);

    $('#Btn_AddFileUP').hide();
    $('#Btn_editFileUP').removeClass('hidden');

}

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


    var FileTypeName = $('#ddUPFileType option:selected').data('id');

    var FileTypeid = $('#ddUPFileType').val();
    var FileDescription = $('#txtUPDescription').val();
    var FilePath = $('#Hos_UploadFile_pathvalue').val();


    if ($('#ddUPFileType').val() == 0) {
        $('#PddUPFileType').show();
        $('#PddUPFileType').fadeOut(8000);
        $('#PddUPFileType').html('Select File Type');
        $('#ddUPFileType').val(0);
        $('#ddUPFileType').focus();
        return false;
    }

    if ($('#Hos_UploadFile_pathvalue').val() == '') {
        $('#PHos_UploadFile').show();
        $('#PHos_UploadFile').fadeOut(8000);
        $('#PHos_UploadFile').html('Choose File');
        $('#Hos_UploadFile_pathvalue').val('');
        $('#Hos_UploadFile_pathvalue').focus();
        return false;
    }

    var rowid = $('#Hdnrowid').val();
    $('#tdFileTypeName_' + rowid).html(FileTypeName);
    $('#tdFileDescription' + rowid).html(FileDescription);
    $('#tdFilePath' + rowid).html(FilePath);
    $('#tdFileTypeid_' + rowid).val(FileTypeid);
    $('#tdFileDescription_' + rowid).val(FileDescription);
    $('#tdFilePath_' + rowid).val(FilePath);

    $('#txtUPDescription').val('');
    $('#Btn_AddFileUP').show();
    $('#Btn_editFileUP').addClass('hidden');
    $('#Hos_UploadFile_pathvalue').val('');
    $('#Hos_UploadFile').val('');
    $('#Hos_UploadFile_photo').empty();
    $('#Hdnrowid').val('');
    $('#ddUPFileType').val(0);

});


// delete 
function FilePathDelete(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 File?',
       {

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

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

                       var servicevalues = {
                           Dml_Indicator: "HFUDEL",
                           contact_details_id: $("#tdfiletype_detailsid_" + val + "").val()

                       }
                       $.ajax({
                           async: true,
                           type: 'POST',
                           url: '/Hospitalsetup/HospitalCreation',
                           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") {
                                       //sessionStorage.removeItem(val);
                                       $('#td_' + val).remove();
                                       toastr.success("Removed Successfully");
                                   }
                               }
                           }
                       });

                   }

                   else {
                       //sessionStorage.removeItem(val);
                       $('#td_' + val).remove();
                       toastr.success("Removed Successfully");

                   }
               });
           }
       });
}

function SaveHosFileUpload_details() {

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

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

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

        var HUfiletype_detailsid = $('#tdfiletype_detailsid_' + (i)).val();
        var HUfiletype = $('#tdFileTypeid_' + (i)).val();
        var HUfile_description = $('#tdFileDescription_' + (i)).val();
        var HUupload_file = $('#tdFilePath_' + (i)).val();

        Contact_details.push({
            filetype_detailsid: HUfiletype_detailsid,
            file_description: HUfile_description == "/" ? '' : HUfile_description,
            upload_file: HUupload_file,
            filetype: HUfiletype,
            created_by: $("#hiddenUser_id").val(),
            hospital_id: $("#HdnContactHid").val(),
            Dml_Indicator: "HFUI"
        })
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalFilesUpload_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;
                $('#tblHSFileUP tbody').empty();
                //$("#HdnContactHid").val('');
            }
            else {
                console.log(data);
            }
        },
        error: function (data) {
            toastr.warning('some issue');
        }
    });
}

function HosInActorAct(event, id) {


    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    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 values = $('#btnHInAorAct_' + id).html();
                     var Hstaus = '';

                     if (values == 'InActive') {
                         Hstaus = 2;
                     }
                     else {
                         Hstaus = 1;
                     }

                     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 ' + values + ' Hospital..?',
                       {
                           closeButton: true,
                           progressBar: true,
                           allowHtml: true,
                           timeOut: 0,

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

                                   var HOSDEl = {

                                       Dml_Indicator: 'HOSACT',
                                       hospitalid: id,
                                       hospital_status: Hstaus
                                   }

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

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

                                           }
                                           else {

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

                                                   toastr.success('Hospital ' + values + ' Successfully',
                                                        {
                                                            //closeButton: false,
                                                            progressBar: true,
                                                            allowHtml: true,
                                                            timeOut: 0,
                                                        });

                                                   TableHospitalDetails();

                                               }
                                               else {
                                                   console.log(data);
                                               }

                                           }
                                       },
                                       error: function (data) {

                                       }
                                   });
                               });
                           }
                       });

                 }
             }
         }
     });

}

function BranchInActorAct(id) {


    var values = $('#btnBInAorAct_' + id).html();
    var Hstaus = '';

    if (values == 'InActive') {
        Hstaus = 2;
    }
    else {
        Hstaus = 1;
    }

    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 ' + values + ' Branch?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

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

                  var HOSDEl = {

                      Dml_Indicator: 'BRNACT',
                      branch_id: id,
                      hospital_status: Hstaus
                  }

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

                          }
                          else {

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

                                  toastr.success('Branch' + values + ' Successfully',
                                       {
                                           //closeButton: false,
                                           progressBar: true,
                                           allowHtml: true,
                                           timeOut: 0,
                                       });
                                  TableBranchDetails();
                                  //TableHospitalDetails();

                              }
                              else {
                                  console.log(data);
                              }

                          }
                      },
                      error: function (data) {

                      }
                  });
              });
          }
      });

}

function HBInActorAct(branch_id, id, hospitalid) {

    var values = $('#btnBInAorAct_' + branch_id).html();
    var Hstaus = '';

    if (values == 'InActive') {
        Hstaus = 2;
    }
    else {
        Hstaus = 1;
    }

    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 ' + values + ' Branch?',
      {
          closeButton: true,
          progressBar: true,
          allowHtml: true,
          timeOut: 0,

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

                  var HOSDEl = {

                      Dml_Indicator: 'BRNACT',
                      branch_id: branch_id,
                      hospital_status: Hstaus
                  }

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

                          }
                          else {

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

                                  toastr.success('Branch ' + values + ' Successfully',
                                       {
                                           //closeButton: false,
                                           progressBar: true,
                                           allowHtml: true,
                                           timeOut: 0,
                                       });
                                  Branchdetails(id, hospitalid);
                                  //TableHospitalDetails();

                              }
                              else {
                                  console.log(data);
                              }

                          }
                      },
                      error: function (data) {

                      }
                  });
              });
          }
      });

}

$('#Branches').change(function () {

    if ($('#Branches').val() == 0) {
        if ($('#HdnBranch_count').val() > 1) {

            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>", 'This Hospital have more branches. Do you want change this to "Does not have Branches"?',
                {
                    closeButton: true,
                    progressBar: true,
                    allowHtml: true,
                    timeOut: 0,

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

                            $('a[data-toggle=Branches][data-title="' + 1 + '"]').removeClass('not-active');
                            $('a[data-toggle=Branches][data-title="' + 1 + '"]').addClass('active');
                            $('a[data-toggle=Branches][data-title="' + 0 + '"]').removeClass('active');
                            $('a[data-toggle=Branches][data-title="' + 0 + '"]').addClass('not-active');
                            $('#otpflag_div').hide();
                            $('#phonenumber_div').hide();
                            $('a[data-toggle=is_otp][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
                            $('a[data-toggle=is_otp][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
                            $('#is_otp').val('');
                            $('#txt_Phone_number').val('');

                        });

                    }

                });
        }
        else {
            if ($('#HdnHospital_id').val() == '') {
                $('#otpflag_div').show();
            }

        }
    }
    else {
        $('#otpflag_div').hide();
        $('#phonenumber_div').hide();
        $('a[data-toggle=is_otp][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
        $('a[data-toggle=is_otp][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
        $('#is_otp').val('');
        $('#txt_Phone_number').val('');
    }

});

//function PaymentDetails(event, hospital_id) {
//    var did = $(event).attr("data-id");
//    var navigation = $(event).attr("data-nav");
//    var name = $(event).attr("data-name");
//    var columntype = $(event).attr("data-type");
//    $('#divtype').addClass('disabled')
//    $('#divsubdis').addClass('disabled')
//    // $('#divdptlb').addClass('disabled')

//    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 {
//                     $('#BtnPayment_Add').show();
//                     $('#BtnPayment_Edit').addClass('hidden');
//                     $('#Hdnrowid').val('');
//                     $('#ddTestLiveKey').removeClass('disabled');
//                     $('#ddMulti_Branch').removeClass('disabled');

//                     $('#SelectedHospitalID').val(hospital_id);
//                     LoadMultipleBranch();
//                     PaymentName()  // one master concept
//                     Hospital_PaymentDetailsTBL();

//                 }
//             }
//         }
//     });


//}

function PaymentDetails(event, hospital_id,SelBranch,branch_name) {
    $('#SelectedHospitalID').val(hospital_id);
    debugger;
    $('#ddMulti_Branch').empty();

    var SubDepartment = '<option value="' + SelBranch + '">' + branch_name + '</option>';
    $('#ddMulti_Branch').append(SubDepartment);
    var SelectedHospitalID = hospital_id;
    var SelBranch11 = SelBranch;


    var did = $(event).attr("data-id");
    var navigation = $(event).attr("data-nav");
    var name = $(event).attr("data-name");
    var columntype = $(event).attr("data-type");
    $('#divtype').addClass('disabled')
    $('#divsubdis').addClass('disabled')
    // $('#divdptlb').addClass('disabled')

    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 {
                     $('#payment').modal();
                     $('#BtnPayment_Add').show();
                     $('#BtnPayment_Edit').addClass('hidden');
                     $('#Hdnrowid').val('');
                     $('#ddTestLiveKey').removeClass('disabled');
                     $('#ddMulti_Branch').removeClass('disabled');
                     $('#ddMulti_Branch').prop('disabled', true);
                     $('#SelectedHospitalID').val(hospital_id);
                     //LoadMultipleBranch();
                     PaymentName()  // one master concept
                     Hospital_PaymentDetailsTBL();

                 }
             }
         }
     });


}

function PaymentName() {
    var PaymentMethod = {
        Dml_Indicator: "PMS",
        hospital_id: $('#SelectedHospitalID').val(),
        //branch_id: $('#ddMulti_Branch').val()  // one master concept
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(PaymentMethod),
        success: function (data) {
            $('#ddPaymentName').empty();
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {

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

                    var data1 = data1.data;
                    var PaymentsName;
                    
                    var default_opt = '<option value="">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        PaymentsName = PaymentsName + '<option value="' + emp.master_servie_type_id + '">' + emp.master_service_name + '</option>';
                    });
                    $('#ddPaymentName').append(default_opt + PaymentsName);
                }
                else {
                    console.log(data);
                }

            }
        }
    });
}

function LoadMultipleBranch() {
    $('#ddMulti_Branch').empty();
    var codeData = {
        Dml_Indicator: "BL",
        hospital_id: $('#SelectedHospitalID').val(),
        branch_id: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Code_Templates_Sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        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, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.length == 1) {
                        $('#ddMulti_Branch').append(SubDepartment);

                    }
                    else {
                        $('#ddMulti_Branch').append(default_opt + SubDepartment);
                    }
                    if ($('#hiddenRole_id').val() == 1) {
                        $('#ddMulti_Branch').val($('#HospitalBranchID').val());
                        $('#ddMulti_Branch').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#ddMulti_Branch').change(function () {

    if (parseInt($('#ddMulti_Branch').val()) != 0) {

        //PaymentName(); // one master concept
    }
    else
    {
      //  $('#ddPaymentName').empty(); // one master concept
    }

});


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



    var PaymentName = $('#ddPaymentName option:selected').html();
    var TestLiveKey = $('#ddTestLiveKey option:selected').html();;

    var PaymentNameid = $('#ddPaymentName').val();
    var TestLiveKeyid = $('#ddTestLiveKey').val();

    var MultiBranchID = $('#ddMulti_Branch').val();
    var MultiBranchName = $('#ddMulti_Branch option:selected').html();

    if ($("#ddMulti_Branch ").val() == "" || $('#ddMulti_Branch').val() == null || $('#ddMulti_Branch').val() == 0) {
        $('#PddMulti_Branch').show();
        $('#PddMulti_Branch').fadeOut(8000);
        $('#PddMulti_Branch').html('Select Branch Name');
        $('#ddMulti_Branch').val('0');
        $('#ddMulti_Branch').focus();
        return false;
    }

    if ($('#ddPaymentName').val() == "" || $('#ddPaymentName').val() == null || $('#ddPaymentName').val() == 0) {
        $('#PddPaymentName').show();
        $('#PddPaymentName').fadeOut(8000);
        $('#PddPaymentName').html('Select Payment Name');
        $('#ddPaymentName').val('');
        $('#ddPaymentName').focus();
        return false;
    }

    if ($('#ddTestLiveKey').val() == '' || $('#ddTestLiveKey').val() == null || $('#ddTestLiveKey').val() == 0) {
        $('#PddTestLiveKey').show();
        $('#PddTestLiveKey').fadeOut(8000);
        $('#PddTestLiveKey').html('Select Test/Live Key');
        $('#ddTestLiveKey').val('');
        $('#ddTestLiveKey').focus();
        return false;
    }

    if ($('#txtKey').val() == '') {
        $('#PtxtKey').show();
        $('#PtxtKey').fadeOut(8000);
        $('#PtxtKey').html('Enter Key');
        $('#txtKey').val('');
        $('#txtKey').focus();
        return false;
    }

    if ($('#txtKeyValue').val() == '') {
        $('#PtxtKeyValue').show();
        $('#PtxtKeyValue').fadeOut(8000);
        $('#PtxtKeyValue').html('Enter Key Value');
        $('#txtKeyValue').val('');
        $('#txtKeyValue').focus();
        return false;
    }


    if (parseInt($('#HdnPayBranchid').val()) == MultiBranchID && parseInt($('#HdnPayTLKeyid').val()) == TestLiveKeyid && parseInt($('#HdnPaymentNameid').val()) == PaymentNameid) {
        MultiBranchName = "";
    }


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

    var value = "<tr class='' data-id='" + ikey + "' id='td" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdPaymentDetailsid_" + ikey + "' value='0' /><input type='hidden' id='tdPaymentNameid_" + ikey + "' value=" + PaymentNameid + " /><input type='hidden' id='tdTestLiveKeyid_" + ikey + "' value=" + TestLiveKeyid + " /><input type='hidden' id='tdMultiBranchID_" + ikey + "' value=" + MultiBranchID + " /><td id='tdPaymentName_" + ikey + "'>" + PaymentName + "</td><td id='tdtxtKey_" + ikey + "'>" + $('#txtKey').val() + "</td><td id='tdtxtKeyValue_" + ikey + "'>" + $('#txtKeyValue').val() + "</td><td id='tdTestLiveKey_" + ikey + "'>" + TestLiveKey + "</td><td id='tdBranchName_" + ikey + "'>" + MultiBranchName + "</td><td><span class='label label-success'>Active</span></td><td><button class='btn-xs btn btn-delete btn-add' onclick='Paymentdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button></td></tr>";

    $('#HosPaymentDetails > tbody:last').append(value);
    $('#txtKey').val('');
    $('#txtKeyValue').val('');
    $('#HdnPayBranchid').val(MultiBranchID);
    $('#HdnPayTLKeyid').val(TestLiveKeyid);
    $('#HdnPaymentNameid').val(PaymentNameid);

});

function Paymentedit(val) {



    var PaymentName = "", Key = "", KeyValue = "", TestLiveKey = "", MultiBranch = "";

    PaymentName = $('#tdPaymentNameid_' + val).val();
    TestLiveKey = $('#tdTestLiveKeyid_' + val).val();
    MultiBranch = $('#tdMultiBranchID_' + val).val();
    Key = $('#tdtxtKey_' + val).html();
    KeyValue = $('#tdtxtKeyValue_' + val).html();

    $('#ddPaymentName').val(PaymentName);
    $('#txtKey').val(Key);
    $('#Hdnrowid').val(val);
    $('#txtKeyValue').val(KeyValue);
    $('#ddTestLiveKey').val(TestLiveKey).addClass('disabled');
    $('#ddMulti_Branch').val(MultiBranch).addClass('disabled');


    $('#BtnPayment_Add').hide();
    $('#BtnPayment_Edit').removeClass('hidden');

}

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


    var PaymentName = $('#ddPaymentName option:selected').html();
    var TestLiveKey = $('#ddTestLiveKey option:selected').html();;

    var PaymentNameid = $('#ddPaymentName').val();
    var TestLiveKeyid = $('#ddTestLiveKey').val();

    var MultiBranchID = $('#ddMulti_Branch').val();
    var MultiBranchName = $('#ddMulti_Branch option:selected').html();

    var key = $('#txtKey').val();
    var keyvalue = $('#txtKeyValue').val();

    if ($("#ddMulti_Branch ").val() == "" || $('#ddMulti_Branch').val() == null || $('#ddMulti_Branch').val() == 0) {
        $('#PddMulti_Branch').show();
        $('#PddMulti_Branch').fadeOut(8000);
        $('#PddMulti_Branch').html('Select Branch');
        $('#ddMulti_Branch').val('0');
        $('#ddMulti_Branch').focus();
        return false;
    }

    if ($('#ddPaymentName').val() == "" || $('#ddPaymentName').val() == null || $('#ddPaymentName').val() == 0) {
        $('#PddPaymentName').show();
        $('#PddPaymentName').fadeOut(8000);
        $('#PddPaymentName').html('Select Payment Name');
        $('#ddPaymentName').val('');
        $('#ddPaymentName').focus();
        return false;
    }

    if ($('#ddTestLiveKey').val() == '' || $('#ddTestLiveKey').val() == null || $('#ddTestLiveKey').val() == 0) {
        $('#PddTestLiveKey').show();
        $('#PddTestLiveKey').fadeOut(8000);
        $('#PddTestLiveKey').html('Select Test/Live Key');
        $('#ddTestLiveKey').val('');
        $('#ddTestLiveKey').focus();
        return false;
    }

    if ($('#txtKey').val() == '') {
        $('#PtxtKey').show();
        $('#PtxtKey').fadeOut(8000);
        $('#PtxtKey').html('Enter Key');
        $('#txtKey').val('');
        $('#txtKey').focus();
        return false;
    }

    if ($('#txtKeyValue').val() == '') {
        $('#PtxtKeyValue').show();
        $('#PtxtKeyValue').fadeOut(8000);
        $('#PtxtKeyValue').html('Enter Key Value');
        $('#txtKeyValue').val('');
        $('#txtKeyValue').focus();
        return false;
    }

   
    var rowid = $('#Hdnrowid').val();
    $('#tdPaymentNameid_' + rowid).val(PaymentNameid);
    $('#tdPaymentName_' + rowid).html(PaymentName);
    $('#tdTestLiveKeyid_' + rowid).val(TestLiveKeyid);
    $('#tdTestLiveKey_' + rowid).html(TestLiveKey);
    $('#tdtxtKey_' + rowid).html(key);
    $('#tdtxtKeyValue_' + rowid).html(keyvalue);

    $('#tdBranchName_' + rowid).html(MultiBranchName);
    $('#tdMultiBranchID_' + rowid).val(MultiBranchID);

    $('#ddPaymentName').val('');
    $('#txtKey').val('');
    $('#txtKeyValue').val('');
    $('#BtnPayment_Add').show();
    $('#BtnPayment_Edit').addClass('hidden');

    $('#Hdnrowid').val('');

    $('#ddTestLiveKey').removeClass('disabled');
    $('#ddMulti_Branch').removeClass('disabled');

});


// delete 
function Paymentdelete(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 Do You want Delete Payment Details ?',
       {

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

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

                   var HPAYid = $("#tdPaymentDetailsid_" + val).val();
                   if (HPAYid != "0") {

                       var Paymentvalues = {
                           Dml_Indicator: "HPAYD",
                           paymentint: $("#tdPaymentDetailsid_" + val).val()

                       }
                       $.ajax({
                           async: true,
                           type: 'POST',
                           url: '/Hospitalsetup/HospitalCreation',
                           contentType: 'application/json; charset=UTF-8',
                           data: JSON.stringify(Paymentvalues),
                           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");
                                       Hospital_PaymentDetailsTBL()
                                   }
                               }
                           }
                       });

                   }

                   else {

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

                   }
               });
           }
       });
}

$('#btnPayment_Submit').click(function () {
    SavePayment_details();
});

function SavePayment_details() {



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



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

    var Payment_details = [];
    for (var i = 1; i <= count; i++) {



        var PaymentDetailsid = $('#tdPaymentDetailsid_' + (i)).val();
        var PaymentNameid = $('#tdPaymentNameid_' + (i)).val();
        var TestLiveKeyid = $('#tdTestLiveKeyid_' + (i)).val();
        var Key = $('#tdtxtKey_' + (i)).html();
        var KeyValue = $('#tdtxtKeyValue_' + (i)).html();
        var MultiBranchID = $('#tdMultiBranchID_' + (i)).val();


        Payment_details.push({
            paymentid: PaymentDetailsid,
            payment_name: PaymentNameid,
            test_live_Key: TestLiveKeyid,
            keys: Key,
            key_value: KeyValue,
            created_by: $("#hiddenUser_id").val(),
            hospital_id: $('#SelectedHospitalID').val(),
            Dml_Indicator: "I",
            branch_id: MultiBranchID
        })
    }


    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalPaymentDetails_Ins',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Payment_details),
        success: function (data) {
            debugger;
            var data2 = JSON.parse(data);
            if (data2.msg == "Success") {
                var data1 = data2.data;


                if (data1.Table.length > 0) {
                    $('#HosPaymentDetails tbody').empty();
                    toastr.success("Payment Details Added Successfully.");
                    Hospital_PaymentDetailsTBL();
                }


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

function Hospital_PaymentDetailsTBL() {

    var Paymentvalues = {
        Dml_Indicator: "HPAYTBL",
        hospital_id: $('#SelectedHospitalID').val()

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


            var data2 = JSON.parse(data);

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

            }
            else {

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

                    var branch_name = "", new_oldbranch = "", new_oldtestkey = "", testkeyid = "", HPayInAorAct = "", status = '', PaymentName = '', old_PaymentName = '';

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

                        var ikey = i + 1;
                        var sno = ikey;

                        branch_name = emp.branch_name;
                        testkeyid = emp.test_live_Key;
                        PaymentName = emp.payment_name;

                        if (emp.status == 1) {
                            HPayInAorAct = '<button id="btnHPayInAorAct_' + emp.branch_id + '" type="button" class="btn btn-xs btn-blue" data-toggle="tooltip" title="Make In Active" onclick=HosPaymentInActorAct("' + emp.branch_id + '","' + 2 + '","' + emp.test_live_Key + '");><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i>In Active</button>';
                        }
                        else if (emp.status == 2) {
                            HPayInAorAct = '<button id="btnHPayInAorAct_' + emp.branch_id + '" type="button" class="btn btn-xs btn-blue" data-toggle="tooltip" title="Make Active" onclick=HosPaymentInActorAct("' + emp.branch_id + '","' + 1 + '","' + emp.test_live_Key + '");><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i>Active</button>';
                        }

                        if (emp.status == 1)
                        {
                            status='<span class="label label-success">Active</span>';
                        }
                        else {
                            status='<span class="label label-warning">Inactive</span>';
                        }

                        if (branch_name == new_oldbranch && testkeyid == new_oldtestkey && PaymentName == old_PaymentName) {
                            branch_name = "", HPayInAorAct = "";
                        }


                        var value = "<tr class='' data-id='" + ikey + "' id='td" + ikey + "'><td>" + sno + "</td><input type='hidden' id='tdPaymentDetailsid_" + ikey + "' value=" + emp.paymentid + " /><input type='hidden' id='tdPaymentNameid_" + ikey + "' value=" + emp.payment_name + " /><input type='hidden' id='tdTestLiveKeyid_" + ikey + "' value=" + emp.test_live_Key + " /><input type='hidden' id='tdMultiBranchID_" + ikey + "' value=" + emp.branch_id + " /><td id='tdPaymentName_" + ikey + "'>" + emp.HosPaymentName + "</td><td id='tdtxtKey_" + ikey + "'>" + emp.keys + "</td><td id='tdtxtKeyValue_" + ikey + "'>" + emp.key_value + "</td><td id='tdTestLiveKey_" + ikey + "'>" + emp.testlive_KeyName + "</td><td id='tdBranchName_" + ikey + "'>" + branch_name + "</td><td>" + status + "</td><td style='width:100%;' class='disp_if'><button class='btn-xs btn btn-edit btn-add' onclick='Paymentedit(\"" + ikey + "\")' data-id=" + ikey + " ><i class='fa fa-pencil' aria-hidden='true'></i></button><button class='btn-xs btn btn-delete btn-add' onclick='Paymentdelete(\"" + ikey + "\")'><i class='fa fa-trash' aria-hidden='true'></i></button> " + HPayInAorAct + "</td></tr>";

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

                        new_oldbranch = emp.branch_name;
                        new_oldtestkey = emp.test_live_Key;
                        old_PaymentName = emp.payment_name;
                    });
                }
            }
        }
    });
}

function HosPaymentInActorAct(branchid, status, test_liveKeyid) {
    var Paymentvalues = {
        Dml_Indicator: "PAYINA",
        branch_id: branchid,
        hospital_status: status,
        test_livekeyid: test_liveKeyid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/HospitalCreation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Paymentvalues),
        success: function (data) {


            var data2 = JSON.parse(data);

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

            }
            else {

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

                    //if (status == 1) {
                    //    ActiveStatus = "Activated"
                    //}
                    //else {
                    //    ActiveStatus = "In Activated"
                    //}

                    if (status == 1) {
                        toastr.success("Payment Details Activated Successfully");
                    }
                    else {
                        toastr.warning("Payment Details In Activated Successfully");
                    }
                    Hospital_PaymentDetailsTBL();
                }
            }
        }
    });
}
// upload photos and videos 
$("#ddUPFileType").change(function () {

    if ($("#ddUPFileType").val() != 0) {
        $('#Hos_UploadFile').attr('disabled', false);
    }
    else {
        $('#Hos_UploadFile').attr('disabled', true);

    }
})
//Discount Authorization OTP concept-Added by Tharuni
$('#is_otp').change(function () {
    var is_otp = $('#is_otp').val();
    if (is_otp == 1) {
        $('#phonenumber_div').show();
    }
    else {
        $('#phonenumber_div').hide();
        $('a[data-toggle=is_otp][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
        $('a[data-toggle=is_otp][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
        //$('#is_otp').val('');
        $('#txt_Phone_number').val('');
    }
})
$('#is_otpbr').change(function () {
    var is_otp = $('#is_otpbr').val();
    if (is_otp == 1) {
        $('#phonenumber_divbr').show();
    }
    else {
        $('#phonenumber_divbr').hide();
        $('a[data-toggle=is_otpbr][data-title="' + 1 + '"]').removeClass('active').addClass('not-active');
        $('a[data-toggle=is_otpbr][data-title="' + 2 + '"]').removeClass('active').addClass('not-active');
        //$('#is_otpbr').val('');
        $('#txt_Phone_numberbr').val('');
    }
})

$('#is_app').change(function () {

    if (parseInt($('#is_app').val()) == 1) {
        $('#div_AppLink').show();
    }
    else {
        $('#div_AppLink').hide();
        $('#txtAppLink').val('');
    }

});

$('#txtShortHName').change(function () {

    if ($('#txtShortHName').val().length < 3) {
        $('#PtxtShortHName').show();
        $('#PtxtShortHName').fadeOut(8000);
        $('#PtxtShortHName').html('Hospital Short Name minimum and maximum Three letters');
        return false;
    }

});

function LoadCasesheetType() {
    debugger;
    var casesheetConfig = {
        Dml_Indicator: 'HS'
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/CaseStudy/Casesheet_Configuration',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(casesheetConfig),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                if (jQuery.isEmptyObject((data1))) {

                }
                else {
                    debugger;

                    $('#Casesheet_type').empty();
                    var default_opt = '<option value="0">--Select--</option>';
                    var SelType = "";
                    if (data1 != null) {
                        if (data1.Table.length > 0) {

                            for (var i = 0; i < data1.Table.length; i++) {
                                SelType = SelType + '<option value="' + data1.Table[i].casesheet_type_id + '">' + data1.Table[i].casesheet_type_name + '</option>';
                            }
                            $('#Casesheet_type').html(default_opt + SelType);


                            //set default casesheet type value if exists
                            var casesheetdetails = getCookie("casesheetdetails");

                            casesheetdetails = casesheetdetails.split('=');
                            var temp3 = casesheetdetails[1];
                            var casesheetType = temp3.split(',');
                            var casesheet_type_id = casesheetType[0];                           

                        }

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

    //added by nandhini for dhanwanthralaya req
    LoadStore();
}

function LoadStore(store_id) {
    debugger;
    var store = {
        Dml_Indicator: "LS",
        hospital_id: $('#HdnHospital_id').val(),
        branch_id: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Billing/ServiceStore',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(store),
        success: function (data) {
            debugger;
            $('#SelStore').empty()
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">All</option>';
                    $.each(data1, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.Id + '">' + emp.Name + '</option>';
                    });
                    $('#SelStore').append(default_opt + SubDepartment);

                    if (store_id != null && store_id!='') {
                        $("#SelStore").val(store_id);
                    }
                    
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}


function LoadChargeType() {
    debugger;
    $('#SelChargeType').empty();
    var codeData = {
        Dml_Indicator: "LCT",
        hospital_id: $('#HospitalId').val(),
        //branch_id: 0
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Hospital_Automated_Charges',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(codeData),
        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, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.type_name + '">' + emp.type_name + '</option>';
                    });
                    if (data1.length == 1) {
                        $('#SelChargeType').append(SubDepartment);

                    }
                    else {
                        $('#SelChargeType').append(default_opt + SubDepartment);
                    }
                    if ($('#hiddenRole_id').val() == 1) {
                        $('#SelChargeType').val($('#HospitalBranchID').val());
                       // $('#SelChargeType').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}