$(document).ready(function () {
    debugger;
    LoadTPA();
    //LoadBranch();  //--One master concept--
});

// load table
//function LoadTPA(tpa_branch_id, tpa_status) {      //--One master concept--
function LoadTPA(tpa_status) {
    debugger;
    var branchid = '', values = ''
    //if (tpa_branch_id != '' || tpa_branch_id != 0 || tpa_branch_id == undefined) {
    //    branchid = tpa_branch_id      
    //}
    //else {
    //    branchid = $('#HospitalBranchID').val()
    //}
    if ($('#hiddenRole_id').val() == 2) {
        values = {

            Dml_Indicator: "LD",
            hospital_id: $('#HospitalId').val(),
            //branch_id: tpa_branch_id,        //--One master concept--
            status: tpa_status
            // name: tpa_pat_name,
            //mobile_number: tpa_phn_no
        }
    }
    else {
        values = {

            Dml_Indicator: "LD",
            hospital_id: $('#HospitalId').val(),
            // branch_id: $('#HospitalBranchID').val(),        //--One master concept--
            status: tpa_status
            //    name: tpa_pat_name,
            //  mobile_number: tpa_phn_no
        }
    }

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

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

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

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

                        //edit = '<a data-toggle="tooltip" title="Edit" class="btn btn-edit btn-xs" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=TPAedit(this,"' + emp.tpa_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        //del = ' <a  data-toggle="tooltip" title="Delete"  id="TPAdel_' + emp.tpa_id + '" class="btn deleteicon-btn btn-xs"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=TPAdel(this,"' + emp.tpa_id + '","D")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        edit = '<a title="Edit" class="edit_icon" data-id="SM_E1" data-type="role_rights_edit" data-nav="sp_div" data-name="c_details_form"  href="javascript:void(0);" onclick=TPAedit(this,"' + emp.tpa_id + '")><i class="fa fa-pencil" aria-hidden="true"></i></a>';
                        del = ' <a title="Delete"  id="TPAdel_' + emp.tpa_id + '" class="delete_icon"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form"  href="javascript:void(0);" onclick=TPAdel(this,"' + emp.tpa_id + '","D")><i class="fa fa-trash-o" aria-hidden="true"></i></a>';
                        if (emp.status == '1') {
                            //active_inactive = '<span class="label label-success">Active</span>';
                            //active = '<a  data-toggle="tooltip" title="Make In Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","INACT")><i class="fa fa-minus-square-o mr-5" aria-hidden="true"></i></a>';
                            //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + edit + ' ' + del + ' ' + active + '</div></div>';
                            active_inactive = '<span class="label label-success">Active</span>';
                            active = '<a title="Make In Active" class="inactive_icon" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","INACT")><i class="fa fa-minus-square-o" aria-hidden="true"></i></a>';
                            other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + edit + '</li><li>' + del + '</li><li>' + active + '</li></div></ul></div>';

                        }
                        else if (emp.status == '2') {
                            //active_inactive = '<span class="label label-warning">Inactive</span>';
                            //active = '<a  data-toggle="tooltip" title="Make Active" class="btn btn-xs btn-blue mr-10" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","ACT")><i class="fa fa-check-square-o mr-5" aria-hidden="true"></i></a>';
                            //other_info = '<div class="col-md-12 padding0"><div class="disp_if">' + del + ' ' + active + '</div></div>';
                            active_inactive = '<span class="label label-warning">Inactive</span>';
                            active = '<a title="Make Active" class="active_icon" href="javascript:void(0);"  data-id="SM_D1" data-type="role_rights_delete" data-nav="sp_delete" data-name="c_details_form" onclick= stsactive(this,"' + emp.tpa_id + '","ACT")><i class="fa fa-check-square-o" aria-hidden="true"></i></a>';
                            other_info = '<div class="dropdown"><i class="fa fa-ellipsis-h dropdown-toggle pull-right" data-toggle="dropdown" aria-expanded="true"></i> <ul class="dropdown-menu info-dropdown-new"><div class="disp_if mb-10"><li>' + del + '</li><li>' + active + '</li></div></ul></div>';
                        }
                        // tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.name + '</td><td>' + emp.branch_name + '</td><td>' + emp.mobile_number + '</td><td >' + emp.Address + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                     // one master concept
                        //tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.name + '</td><td>' + emp.branch_name + '</td><td>' + emp.mobile_number + '</td><td >' + emp.Address + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';
                        tr = tr + '<tr' + j + '"></td><td>' + j + '</td><td>' + emp.name + '</td><td>' + emp.mobile_number + '</td><td >' + emp.Address + '</td><td>' + active_inactive + '</td><td>' + other_info + '</td></tr>';

                    });
                    $('#tpa_body').html(tr);
                    datatable('TPA_table_list', 'TPA LIST', 'Legal');
                }
            }
            else {
                console.log(data);
            }
        }
    });
}

// active & inactive
function stsactive(event, tpa_id, indicatorid) {
    debugger;
    var status = "";

    if (indicatorid == 'INACT') {
        status = "Are you sure, Do you want to In-Activate?";
    }
    else if (indicatorid == 'ACT') {
        status = "Are you sure, you want to Activate?";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
          {
              closeButton: true,
              progressBar: true,
              allowHtml: true,
              timeOut: 20000000,

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

                      var status = {
                          Dml_Indicator: indicatorid,
                          tpa_id: tpa_id
                      }

                      $.ajax({
                          async: true,
                          type: 'POST',
                          url: '/TPA/insert_update_deleteTPA',
                          contentType: 'application/json; charset=UTF-8',
                          data: JSON.stringify(status),
                          success: function (data) {
                              debugger;
                              var data1 = JSON.parse(data);
                              console.log(data1)
                              if (indicatorid == 'INACT') {
                                  var data2 = data1.data
                                  if (data2.Table[0].Message == 'Mapped with Entity') {
                                      toastr.warning("The selected TPA Mapped with Entity. Unable to In-active.");
                                      return;
                                  }
                                  else {
                                      toastr.success('In-Activated Successfully');
                                  }
                              }
                              else if (indicatorid == 'ACT') {                                 
                                      toastr.success('Activated Successfully');                                  
                              }
                              LoadTPA()
                          }
                      });
                  });
              }
          })
};

// Edit
function TPAedit(event, Id) {
    debugger;
    $('#Htpaid').val(Id)

    $('#TPA_form').show();
    $('#add_new_TPA').hide();
    $('#tpa-table').hide();
    $('#TPAbacklist').hide();
    $('#TPAback').show();

    var Edit = {
        tpa_id: Id,
        Dml_Indicator: 'E'
    };

    $.ajax({
        async: true,
        type: 'POST',
        url: '/TPA/insert_update_deleteTPA',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(Edit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            var emp = data1.data.Table;
            // $("#SelBranch").val(emp[0].branch_id);       //--One master concept--
            $("#txtname").val(emp[0].name);
            $("#txtmobile").val(emp[0].mobile_number);
            $("#txtaddress").val(emp[0].address);
            $("#txtaddress_line2").val(emp[0].address_line_2);
            $("#txtarea").val(emp[0].area);
            $("#txtpin_code").val(emp[0].pin_code);
            var countryid = emp[0].country;
            var stateid = emp[0].state;
            var cityid = emp[0].city;
            loadcountry(countryid, stateid, cityid)
            $('#btnsubmit').html('Update');
        }
    })
}

// delete
function TPAdel(event, Id, indicatorid) {
    debugger;

    var status = "";
    if (indicatorid == 'D') {
        status = "Are you sure, Do you want to Delete?";
    }
    toastr.warning("<button type='button' id='confirmationRevertYes' class='btn btn-warning btn-xs mt20'>Yes</button><button type='button' id='confirmationRevertNo' class='btn btn-warning btn-xs mt20'>No</button>", status,
     {
         closeButton: true,
         progressBar: true,
         allowHtml: true,
         timeOut: 20000000,

         onShown: function (toast) {
             $("#confirmationRevertYes").click(function () {
                 var Delete = {
                     Dml_Indicator: indicatorid,
                     tpa_id: Id
                 }

                 $.ajax({
                     async: true,
                     type: 'POST',
                     url: '/TPA/insert_update_deleteTPA',
                     contentType: 'application/json; charset=UTF-8',
                     data: JSON.stringify(Delete),
                     success: function (data) {
                         debugger;
                         var data1 = JSON.parse(data);
                         if (data1.msg == "Success") {
                             if (data1.data.Table[0].Message == 'Mapped with Entity') {
                                 toastr.warning("The selected TPA Mapped with Entity. Unable to Delete.");
                                 return;
                             }
                            else if (data1.data.Table[0].msg == 'Deleted') {
                                 toastr.success("Deleted Successfully");
                                 LoadTPA()
                             }
                             else {
                                 toastr.warning("Somthing Went Wrong");
                                 return false;
                             }
                         }
                         else {
                             toastr.warning("Somthing Went Wrong");
                             return false;
                         }
                     }
                 });
             });
         }
     })
};

// load branch
function LoadBranch() {
    debugger;
    $('#SelBranch').empty();

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

    var subdepartment = {
        //Dml_Indicator: "LBRAN",
        Dml_Indicator: dml,
        name: $('#HiddenDoctorID').val()
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    debugger;
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    var fil_default_opt = '<option value="0">All</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.hospital_branch_id + '">' + emp.branch_name + '</option>';
                    });
                    if (data1.Table.length == 1) {
                        $('#SelBranch').append(SubDepartment);
                        $('#fbranch_id').append(SubDepartment);
                    }
                    else {
                        if ($('#hiddenRole_id').val() == 1) {
                            $('#fbranch_id').append(SubDepartment);
                        }
                        else {
                            $('#SelBranch').append(default_opt + SubDepartment);
                            $('#fbranch_id').append(fil_default_opt + SubDepartment);
                        }
                        
                    }

                    if ($('#hiddenRole_id').val() == 1) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#fbranch_id').val($('#HospitalBranchID').val());
                    }
                    else if ($('#hiddenRole_id').val() != 2) {
                        $('#SelBranch').val($('#HospitalBranchID').val());
                        $('#SelBranch').attr('disabled', true);
                        $('#fbranch_id').val($('#HospitalBranchID').val());
                        $('#fbranch_id').attr('disabled', true);
                    }
                }
            }
            else {
                console.log(data1);
            }

        }
    });
}

// load country
function loadcountry(countryid, stateid, cityid) {
    debugger;
    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) {
            debugger;
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    $('#txtCountry').empty();
                    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(Country);
                    $("#txtCountry").change();
                }
                else {
                    console.log(data);
                }

                if (countryid != 0 && countryid != undefined) {
                    $('#txtCountry').val(countryid)
                    var state_id = stateid
                    var city_id = cityid
                    load_state(countryid, state_id, city_id)
                }
            }
        }
    });
}

$("#txtCountry").change(function () {
    debugger
    var countryid = $("#txtCountry").val()
    load_state(countryid);
});

//load state and defaultly selected to tamil nadu
function load_state(countryid, state_id, city_id) {
    debugger
    var state = {
        country_id: countryid,
        Dml_Indicator: "S"
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/DoctorProfile/GetCountry',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(state),
        success: function (data) {
            debugger
            var data1 = JSON.parse(data);
            if (jQuery.isEmptyObject((data1.data))) {
            }
            else {
                if (data1.msg == "Success") {
                    var data1 = data1.data;
                    var state;
                    $('#txtState').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);
                    $("#txtState").change();
                }
                else {
                    console.log(data);
                }

                if (state_id != 0 && state_id != undefined) {
                    $('#txtState').val(state_id);
                    load_city(state_id, city_id)
                }
            }
        }
    });
}

$("#txtState").change(function () {
    debugger;
    var state_id = $('#txtState').val();
    load_city(state_id);
});

// load city
function load_city(state_id, city_id) {
    debugger
    var val = val;
    var state = {
        state_id: state_id,
        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);
                }
                else {
                    console.log(data);
                }

                if (city_id != 0 && city_id != undefined) {
                    $('#txtCity').val(city_id);
                }
            }
        }
    });
}

// insert
$('#btnsubmit').on("click", function () {
    debugger;
   //--One master concept--
    //if ($.trim($('#SelBranch').val()) == "" || ($('#SelBranch').val()) == '0') {
    //    $('#Pbranch').show();
    //    $('#Pbranch').fadeOut(8000);
    //    $('#Pbranch').html('Select the Branch');
    //    $('#SelBranch').focus();
    //    return false;
    //}

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

    if ($.trim($('#txtmobile').val()) == "" || $.trim($('#txtmobile').val())==0) {
        $('#Ptxtmobile').show();
        $('#Ptxtmobile').fadeOut(8000);
        $('#Ptxtmobile').html('Enter Mobile Number');
        $('#txtmobile').focus();
        $('#txtmobile').val('')
        return false;
    }

    if ($('#txtaddress').val() == "") {
        $('#Ptxtaddress').show();
        $('#Ptxtaddress').fadeOut(8000);
        $('#Ptxtaddress').html('Enter Address Line1');
        $('#txtaddress').focus();
        return false;
    }
    if ($('#txtCountry').val() == "" || $('#txtCountry').val() == '0') {
        $('#PtxtCountry').show();
        $('#PtxtCountry').fadeOut(8000);
        $('#PtxtCountry').html('Select the Country');
        $('#txtCountry').focus();
        return false;
    }
    if ($('#txtState').val() == "" || $('#txtState').val() == '0') {
        $('#PtxtState').show();
        $('#PtxtState').fadeOut(8000);
        $('#PtxtState').html('Select The State');
        $('#txtState').focus();
        return false;
    }

    if ($('#txtCity').val() == "" || $('#txtCity').val() == '0') {
        $('#Ptxtcity').show();
        $('#Ptxtcity').fadeOut(8000);
        $('#Ptxtcity').html('Select the City');
        $('#txtCity').focus();
        return false;
    }


    var indicator_id = '', msg = '', indicator_id = '', contry_val = '', state_val = '', city_val = '', tpaid = '';

    if ($('#btnsubmit').html() == 'Submit') {
        indicator_id = 'IS'
        msg = 'Saved Successfully';
    }
    else {
        indicator_id = 'UP'
        msg = 'Updated Successfully';
    }

    if ($('#txtCountry').val() == null) {
        contry_val = 0
    }
    else {
        contry_val = $('#txtCountry').val()
    }

    if ($('#txtState').val() == null) {
        state_val = 0
    }
    else {
        state_val = $('#txtState').val()
    }

    if ($('#txtCity').val() == null) {
        city_val = 0
    }
    else {
        city_val = $('#txtCity').val()
    }

    if ($('#Htpaid').val() == "") {
        tpaid = 0
    }
    else {
        tpaid = $('#Htpaid').val();
    }

    var submit = {
        tpa_id: tpaid,
        name: $('#txtname').val(),
        //branch_id: $('#SelBranch').val(),        //--One master concept--
        mobile_number: $('#txtmobile').val(),
        address: $('#txtaddress').val(),
        address_line2: $('#txtaddress_line2').val(),
        country: contry_val,
        state: state_val,
        city: city_val,
        area: $('#txtarea').val(),
        Pin_code: $('#txtpin_code').val(),
        created_by: $('#hiddenUser_id').val(),
        // Mrdid: $('#Hmrdid').val(),
        Dml_Indicator: indicator_id,
        //flag: 1
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/TPA/insert_update_deleteTPA',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(submit),
        success: function (data) {
            debugger;
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                debugger;
                var data2 = data1.data;
                if (data2.Table[0].Message == 'already')
                {
                    toastr.warning('Name Already Exists');
                    $('#txtname').val('');
                }
                else if (data2.Table[0].Message == 'Inserted')
                {
                    toastr.success('Inserted Successfully');
                    setTimeout(function () {
                        location.reload();
                    }, 1000)
                }
                else if (data2.Table[0].Message == 'Updated')
                {
                    toastr.success('Updated Successfully');
                    setTimeout(function () {
                        location.reload();
                    }, 1000)
                }
                else
                {
                    toastr.success('Somthing Went Wrong');
                }
                //clear()
               // clearRequest();
               // goback();
                //ShowWard();
            }
            else {
                toastr.success('Somthing Went Wrong');
            }
        },
    });
});

// filter
$('#btnfilter').on('click', function () {
    debugger;
    //if ($.trim($('#fbranch_id').val()) == "" || $('#fbranch_id').val() == "0") {
    //    $('#Pbranch_id').show();
    //    $('#Pbranch_id').fadeOut(8000);
    //    $('#Pbranch_id').html('Please Select the Branch');
    //    $('#Pbranch_id').focus();
    //    $('#Pbranch_id').val('');
    //    return false;
    //}
    //if ($.trim($('#ftname').val()) == "") {
    //    $('#Ptpaname').show();
    //    $('#Ptpaname').fadeOut(8000);
    //    $('#Ptpaname').html('Please Enter Name');
    //    $('#Ptpaname').focus();
    //    $('#Ptpaname').val('');
    //    return false;
    //}

    var tpa_branch_id = ''
    //if ($('#fbranch_id').val() != 0) {
    //    tpa_branch_id = $('#fbranch_id').val()
    //}
    //else {
    //    tpa_branch_id = $('#HospitalBranchID').val()
    //}

 // one master concept
    //if ($('#hiddenRole_id').val() == 2) {
    //    tpa_branch_id = $('#fbranch_id').val()
    //}
    //else {
    //    tpa_branch_id = $('#HospitalBranchID').val()
    //}

    var tpa_status = $('#status_filter').val();
    // var tpa_pat_name = $('#ftname').val();
    //var tpa_phn_no = $('#fphone').val();
    LoadTPA(tpa_status)
})

$('#btnclear').click(function () {
    debugger;
    // $('#fbranch_id').val(0),      //--One master concept--
    $('#status_filter ').val(0),
    $('#ftname').val(""),
    $('#fphone').val("")
    LoadTPA();
    //LoadBranch();
    //$('.pat-strip').hide();
});