function validation() {
    debugger
    if ($.trim($('#pkg_department').val()).length == "" || $.trim($('#pkg_department').val()) == "0") {
        $('#Ppkg_department').show();
        $('#Ppkg_department').fadeOut(8000);
        $('#Ppkg_department').html('Select a Department');
        $('#Ppkg_department').focus();
        $('#pkg_department').val('0');
        return false;
    }

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

    if ($.trim($('#educationtitle').val()).length == "" || $.trim($('#educationtitle').val()) == "0") {
        $('#Peducationtitle').show();
        $('#Peducationtitle').fadeOut(8000);
        $('#Peducationtitle').html('Please enter a title');
        $('#Peducationtitle').focus();
        return false;
    }

    if ($('#pe_date').val() == "" || $('#pe_date').val() == null) {
        $('#Pdate').show();
        $('#Pdate').fadeOut(8000);
        $('#Pdate').html('Please Select From Date');
        return false;
    }

    if ($('#pe_dateto').val() == "" || $('#pe_dateto').val() == null) {
        $('#Ppe_dateto').show();
        $('#Ppe_dateto').fadeOut(8000);
        $('#Ppe_dateto').html('Please Select To Date');
        return false;
    }

    submit();
}


$(document).ready(function () {
    debugger;
    LoadFilterDepartment();
    loadpatienteducationTable();
});

function loadpatienteducationTable() {

    var tabreq = {
        Dml_Indicator: 'S',
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/PatientEducation/insert_update_deletePatientEducation',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(tabreq),
        success: function (data) {
            var data2 = JSON.parse(data);

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

                var data1 = data2.data;

                function populateTable(data1) {
                    var tableBody = $("#patienteducationcontent");


                    $.each(data1, function (index, item) {
                        var row = $("<tr>");
                        row.append($("<td>").text(index + 1));
                        row.append($("<td>").text(item.Title));
                        row.append($("<td>").text(item.name));
                        row.append($("<td>").text(item.sub_cd_name));

                        var isJournalText = item.IsJournal === 1 ? "Yes" : "No";
                        row.append($("<td>").text(isJournalText));

                        var IsAlwaysText = item.IsAlways === 1 ? "Yes" : "No";
                        row.append($("<td>").text(IsAlwaysText));

                        var statusBadgeClass = item.Status === 1 ? 'label label-success' : 'label label-danger';
                        var statusText = item.Status === 1 ? 'Active' : 'Inactive';
                        row.append($("<td>").html('<span class="' + statusBadgeClass + '">' + statusText + '</span>'));


                        row.append($("<td>").html('<td class="disp_if"><button class="btn btn-edit btn-xs" onclick="pededitdata(' + item.Id + ')"><i class="fa fa-pencil"></i></button><button class="btn btn-delete btn-xs" onclick="pedeletedata(' + item.Id + ')"><i class="fa fa-trash-o"></i></button></td>'));
                        tableBody.append(row);
                    });
                }

                populateTable(data1.Table);

                $(document).ready(function () {
                    $('#pedtable').DataTable();
                });

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

function pededitdata(val) {


    addnew();


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


    var tabreq1 = {
        Dml_Indicator: 'ED',
        Id: val
    }

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

            var data2 = JSON.parse(data);

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

                var data = data2.data;

                $('#Hdneducation_id').val(data.Table[0].Id);

                var dispid = $('#Hdneducation_id').val();

                loadsubcontenttable(dispid);

                $('#pkg_department').val(data.Table[0].DepartmentId);

                subdepartmentload(data.Table[0].DepartmentId, data.Table[0].SubDepartmentId)

                $('#educationtitle').val(data.Table[0].Title);

                $("#pe_date").val(data.Table[0].MobileFrom);

                $("#pe_dateto").val(data.Table[0].MobileTo);

                if (data.Table[0].IsJournal == 1) {
                    $('#yes').addClass('active');
                    $('#yes').removeClass('not-active');
                    $('#no').removeClass('active');
                    $('#no').addClass('not-active');
                }
                else if (data.Table[0].IsJournal == 0) {
                    $('#yes').removeClass('active');
                    $('#yes').addClass('not-active');
                    $('#no').addClass('active');
                    $('#no').removeClass('not-active');
                }

                if (data.Table[0].IsAlways == 1) {
                    $('#ChkID').prop('checked', true);
                }
                else {
                    $('#ChkID').prop('checked', false);
                }


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

function loadsubcontenttable(val)
{

    var tabreq1 = {
        Dml_Indicator: 'ED',
        Id: val
    }

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

            var data2 = JSON.parse(data);

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

                var data = data2.data;

                var i = 0; tableArray = '';

                var tableArray = data.Table1;

                var serialNumber = 1;

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

                    var id = emp.Id;
                    var title = emp.Title;
                    var filePath = emp.FilePath;
                    var content = emp.Content;

                    var newRow =
                        '<tr id="row' + serialNumber + '">' +
                        '<td>' + serialNumber + '</td>' +
                        '<td>' + title + '</td>' +
                        '<td>' + filePath + '</td>' +
                        '<td>' + content + '</td>' +
                        '<td class="hide">' + id + '</td>' +
                        '<td class="disp_if"><button class="btn btn-edit btn-xs" onclick="editRow(' + id + ',' + serialNumber + ')"><i class="fa fa-pencil"></i></button> <button class="btn btn-delete btn-xs" onclick="deleteRow(' + id + ',' + serialNumber + ')"><i class="fa fa-trash-o"></i></button></td>' +
                        '</tr>';

                    $('#addsubtitlebody').append(newRow);

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

function pedeletedata(val) {

    var pedelete = {
        Dml_Indicator: 'D',
        Id: val
    }

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

            if (data1.msg == "Success") {
                alert('deleted successfully');
                location.reload();
            }
            else {
                console.log(data1);
            }
        },
    });
}

function LoadFilterDepartment() {

    var department = {
        Dml_Indicator: "DP",
        //branch_id: "0",
        //name: $('#DoctorUser_Id').val()
    }

    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(department),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1)
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var Department;
                    $('#pkg_department').empty();
                    document.getElementById("pkg_sub_department").innerHTML = null;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        Department = Department + '<option value="' + emp.master_category_department_id + '">' + emp.name + '</option>';
                    });
                    $('#pkg_department').append(default_opt + Department);
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

$('#pkg_department').change(function () {
    subdepartmentload($('#pkg_department').val(), 0);
});

function subdepartmentload(deptid, subdeptid) {
    document.getElementById("pkg_sub_department").innerHTML = null;

    var subdepartment = {
        Dml_Indicator: "SDP",
        Master_cd_id: deptid
    }
    $.ajax({
        async: true,
        type: 'POST',
        url: '/Hospitalsetup/Category_Department_Ins_Upd_sel',
        contentType: 'application/json; charset=UTF-8',
        data: JSON.stringify(subdepartment),
        success: function (data) {
            var data1 = JSON.parse(data);
            if (data1.msg == "Success") {
                var data1 = data1.data;
                console.log(data1);
                if (jQuery.isEmptyObject((data1))) {
                }
                else {
                    var SubDepartment;
                    var default_opt = '<option value="0">--Select--</option>';
                    $.each(data1.Table, function (i, emp) {
                        SubDepartment = SubDepartment + '<option value="' + emp.sub_category_department_id + '">' + emp.sub_cd_name + '</option>';
                    });
                    $('#pkg_sub_department').append(default_opt + SubDepartment);

                    if (subdeptid != 0 && subdeptid != null) {
                        $('#pkg_sub_department').val(subdeptid);
                    }
                }
            }
            else {
                console.log(data1);
            }
        }
    });
}

function pedata() {

    var ActiveForm = $("#pe_date").val();
    var ActiveFormsplit = ActiveForm.split('/');
    var mobfrom = ActiveFormsplit[2] + '-' + ActiveFormsplit[1] + '-' + ActiveFormsplit[0];

    var ActiveTo = $("#pe_dateto").val();
    var ActiveTosplit = ActiveTo.split('/');
    var mobto = ActiveTosplit[2] + '-' + ActiveTosplit[1] + '-' + ActiveTosplit[0];

    var journalval = $("#radioBtn .btn.active").data("title");

    var isChecked = document.getElementById("ChkID").checked;
    var checkboxValue = isChecked ? 1 : 0;
    debugger;
    var dml_value = '';


    if ($('#Hdnpeducation_id').val() != null && $('#Hdnpeducation_id').val() != '') {
        dml_value = "UP";
    }
    else {
        dml_value = "IS";
        $('#Hdnpeducation_id').val(0);
    }


    var peddata = {
        Dml_Indicator: dml_value,
        Id: $('#Hdnpeducation_id').val(),
        BranchId: 0,
        DepartmentId: $('#pkg_department').val(),
        SubDepartmentId: $('#pkg_sub_department').val(),
        Title: $('#educationtitle').val(),
        MobileFrom: mobfrom,
        MobileTo: mobto,
        IsJournal: journalval,
        IsAlways: checkboxValue,
        Status: 0,
        Createdby: $('#hiddenUser_id').val(),
        HospitalId: $('#HospitalId').val(),
        PatientEducationId: 0
    }


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

            if (data1.msg == "Success") {
                var pedid = data1.data.Table[0].LastId;
                collectTableData(pedid);
            }
            else {
                console.log(data1);
            }
        },
    });


}

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

function AllMultifileimageupload(id) {

    var UploadFileid = "ImagesUploaded";

    //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: '/PatientEducation/uploadImg',
                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() + "PatientEducationContent/" + 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: '/PatientEducation/uploadImg',
                        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() + "PatientEducationContent/" + emp + '" target="_blank">' + UploadFileid + '</a>');
                            });
                        }
                    });
                }
                else {
                    $('#Hos_UploadFile').val('');
                    //  $('#HospitalFavicon').val('');
                    //$('#' + photo).empty();
                }
            });
        }
    }
}

var serialNumber = 1;

function addimagesandcontent()
{
    var subtitle = $('#subcontenttitle').val();
    var hosfilepath = $('#Hos_UploadFile_pathvalue').val();
    var subtitlecontent = $('#content').val();
    var Id = $('#HEducontent_id').val();

    if ($('#subcontenttitle').val() == '') {
        $('#Psubcontenttitle').show();
        $('#Psubcontenttitle').fadeOut(8000);
        $('#Psubcontenttitle').html('Fill the Sub Title field');
        $('#subcontenttitle').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;
    }

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


    if (Id == 0)
    {
        alert('idis0');

        var existingRow = $('#addsubtitlebody').find('td.hide').closest('tr');

        var serialNumber = 1; // Set a default serialNumber if no existing row is found

        if (existingRow.length > 0) {
            serialNumber = parseInt(existingRow.find('td:eq(0)').text()) + 1;
        }

        var newRow =
            '<tr id="row' + serialNumber + '">' +
            '<td>' + serialNumber + '</td>' +
            '<td>' + subtitle + '</td>' +
            '<td>' + hosfilepath + '</td>' +
            '<td>' + subtitlecontent + '</td>' +
            '<td class="hide">' + Id + '</td>' +
            '<td class="disp_if"><button class="btn btn-edit btn-xs" onclick="editRow(' + Id + ',' + serialNumber + ')"><i class="fa fa-pencil"></i></button> <button class="btn btn-delete btn-xs" onclick="deleteRow(' + Id + ',' + serialNumber + ')"><i class="fa fa-trash-o"></i></button></td>' +
            '</tr>';

        $('#addsubtitlebody').append(newRow);
    }

    else {

        var existingRow = $('#addsubtitlebody').find('td.hide:contains(' + Id + ')').closest('tr');

        if (existingRow.length > 0)
        {
            existingRow.find('td:eq(1)').text(subtitle);
            existingRow.find('td:eq(2)').text(hosfilepath);
            existingRow.find('td:eq(3)').text(subtitlecontent);
        }
        else
        {
           alert('Error: Attempted to update a non-existent row with Id ' + Id);
        }
    }


    // Clear input fields
    $('#subcontenttitle').val('');
    $('#Hos_UploadFile_pathvalue').val('');
    $('#Hos_UploadFile_photo').empty();
    $('#Hos_UploadFile').val('');
    $('#content').val('');

}

// Edit the row
function editRow(rowId, serialNumber)
{
    $('#HEducontent_id').val(rowId);

    var tabreq1 = {
        Dml_Indicator: 'EST',
        Id: rowId
    }

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

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

                var subtitle = data.Table[0].Title;
                var hosfilepath = data.Table[0].FilePath;
                var subtitlecontent = data.Table[0].Content;

                $('#subcontenttitle').val(subtitle);
                $('#Hos_UploadFile_pathvalue').val(hosfilepath);
                $('#content').val(subtitlecontent);
                $('#Hos_UploadFile_photo').append('<a href="' + $('#hdnHospitalfilepath').val() + "PatientEducationContent/" + hosfilepath + '" target="_blank">ImagesUploaded</a>');

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

// Delete the row
function deleteRow(rowId, serialnumber) {

    var pedelete = {
        Dml_Indicator: 'DEC',
        Id: rowId
    }

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

            if (data1.msg == "Success") {
                toastr.warning('deleted successfully');
                //addimagesandcontent()
                $('#row' + serialnumber).remove();
            }
            else {
                console.log(data1);
            }
        },
    });
}


function collectTableData(PatientEducationId)
{
    var dataArray = [];

    $('#addsubtitlebody tr').each(function () {
        debugger;

        var row = $(this);
        var rowData = {
            Dml_Indicator: "TPI",
            Title: row.find('td:eq(1)').text(),
            Createdby: $('#hiddenUser_id').val(),
            HospitalId: $('#HospitalId').val(),
            FilePath: row.find('td:eq(2)').text(),
            Content: row.find('td:eq(3)').text(),
            PatientEducationId: PatientEducationId,
            Id: row.find('td:eq(4)').text()
        };

        dataArray.push(rowData);
    });



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

            var data1 = JSON.parse(data);

            if (data1.msg == "Success") {
                toastr.success('Inserted successfully');
                var pedid = data1.data.Table[0].LastId;
            }
            else {
                console.log(data1);
            }
        },
    });

    loadsubcontenttable(pedid);

}


function submit() {
    pedata();
}

$('#ChkID').change(function () {
    if ($('#ChkID').prop("checked") == true) {
        $('#pe_date').val('');
        $("#pe_date").prop("disabled", true);
        $('#pe_dateto').val('');
        $("#pe_dateto").prop("disabled", true);
    }
    else {
        $("#pe_date").prop("disabled", false);
        $("#pe_dateto").prop("disabled", false);
    }
})