
var hospitalid = $('#HospitalId').val();
function datatable(tableid, title, size) {

    //if($('#' + tableid +' tbody').length < 10){
    //    ('#' + tableid +' tbody').addClass('tableheight');
    //}
    debugger;
    $('.groupscolumn').prop('checked', false);
    var table = $('#' + tableid + '').DataTable({
        "fnInitComplete": function () {
            // Disable TBODY scoll bars


            // Enable TFOOT scoll bars
            $('.dataTables_scrollFoot').css('overflow', 'hidden');

            $('.dataTables_scrollHead').css('overflow', 'auto');

            // Sync TFOOT scrolling with TBODY
            $('.dataTables_scrollFoot').on('scroll', function () {
                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
            });

            $('.dataTables_scrollHead').on('scroll', function () {
                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
            });
        },
        "scrollX": true,
        "scrolly": true,
        responsive: true,
        "scrollCollapse": true,
        "sScrollY": "500px",
        "fixedHeader": {
            header: true,
            footer: true
        },
        "fixedColumns":{
            leftColumns: 2
        },
        "colResize": {
            "tableWidthFixed": false,
            "resizeCallback": function (column) {
            }
        },

        "deferRender": true,

        dom: 'lBfrtip',
        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
        buttons: [
        ]
    });

    //if (tableid != 'patientsearchtable') {


        var d = new Date();
        var month = d.getMonth() + 1;
        var day = d.getDate();
        var output = (day < 10 ? '0' : '') + day + '/' + (month < 10 ? '0' : '') + month + '/' + d.getFullYear();
        var downloadfilename = "";
        if (title == "Patient List") {
            downloadfilename = "PatientList" + output;
        }
        else {
            downloadfilename = title;
        }

        var table = $('#' + tableid + '').DataTable();
        var buttons = new $.fn.dataTable.Buttons(table, {
            buttons: [
      {
          extend: 'copyHtml5', footer: true, title: title, text: '<i class="fa fa-files-o" aria-hidden="true"></i> Download as Copy', titleAttr: 'Download as Copy',
          footer: true,
          stripHtml: false,
          decodeEntities: true,
          filename: downloadfilename,
          pageSize: size,
          paging: true,
          exportOptions: {
              columns: ':not(:last-child)'
          }
      },
      {
          extend: 'excelHtml5', footer: true, title: title, text: '<i class="fa fa-file-excel-o" aria-hidden="true"></i> Download as Excel', titleAttr: 'Download as Excel', footer: true,
          stripHtml: false,
          decodeEntities: true,
          filename: downloadfilename,
          pageSize: size,
          paging: true,
          exportOptions: {
              columns: ':not(:last-child)'
          }
      },
      {
          extend: 'csvHtml5', footer: true, title: title, text: '<i class="fa fa-file-text-o" aria-hidden="true"></i> Download as CSV', titleAttr: 'Download as CSV',
          footer: true,
          stripHtml: false,
          decodeEntities: true,
          filename: downloadfilename,
          pageSize: size,
          paging: true,
          exportOptions: {
              columns: ':not(:last-child)'
          }
      },
      {
          extend: 'pdfHtml5', footer: true, title: title, text: '<i class="fa fa-file-pdf-o" aria-hidden="true"></i> Download as PDF', titleAttr: 'Download as PDF',
          footer: true,
          stripHtml: false,
          decodeEntities: true,
          filename: downloadfilename,
          orientation: 'landscape',
          pageSize: size,
          paging: true,
          exportOptions: {
              columns: ':not(:last-child)'
          }
      }
            ]
        }).container().appendTo($('#buttons'));
        chkttablecolumnstatus(tableid);
        // fixed header - 
        new $.fn.dataTable.FixedHeader(table);
   // }
}


$(document).ready(function () {

    var th = '', thd = '', i = 0, j = 0;
    getformid();
    function getformid() {
        var formdata = {
            Stringtype: window.location.pathname,
            Dml_Indicator: 'GFID',
        }

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

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

                    }
                    else {
                        var form_id = data1.Table[0].form_id
                        if (form_id == '') {
                            toastr.warning('You do not have rights this page');
                            return;
                        }
                        else {
                            $('#formid').val(form_id);
                        }
                    }
                }
            }
        });
    }



    $(function () {
        debugger;

        $(".table").each(function () {
            debugger;
            var th = '', thd = '', i = 0, j = 0;
            // alert($(this).attr("id"));
            var datatable = $(this).attr("id")
            var tabletitle = $(this).attr("data-title")
            var tablesize = $(this).attr("data-size")
            var datatable = $(this).attr("id")

            var columnshowhide = datatable + 'colshow';
            var columnsgroupdropdown = datatable + 'dropdown';
            $("#" + datatable + " thead tr th").each(function () {
                //alert(this.innerHTML); //This executes once per column showing your column names!
                var tdname = this.innerHTML;
                i = i + 1;
                //if (tdname != 'Actions') {
                //    var tdnameid = tdname.replace(/ +/g, "")
                //    th = th + '<input type="checkbox" class="chkthcolumnhhideshow" data-column1="' + datatable + '" data-column2="' + datatable + tdnameid + '"  id="' + datatable + tdnameid + '"  value="' + tdname + '" checked data-column="' + i + '"><label>' + tdname + '</label><br>';
                //}
                if (tdname != 'Actions' && tdname != 'View More') {
                    var tdnameid = tdname.replace(/ +/g, "")
                    th = th + ' <div class=""><label class="control-sidebar-subheading">' + tdname + '<input type="checkbox" class="pull-right chkthcolumnhhideshow formscheck_field" data-title="' + tabletitle + '" data-size="' + tablesize + '" data-column1="' + datatable + '" data-column2="' + datatable + tdnameid + '"  id="' + datatable + tdnameid + '"  value="' + tdname + '" checked data-column="' + j + '"></label></div>';
                }

                //if (tdname != 'Actions') {
                //    thd = thd + '  <option value="' + j + '" data-id="' + datatable + '">' + tdname + '</option>';
                //}
                if (tdname != 'Actions' && tdname != 'View More') {
                    var tdnameid = tdname.replace(/ +/g, "")
                    thd = thd + ' <div class=""><label class="control-sidebar-subheading">' + tdname + '<input type="checkbox" class="pull-right groupscolumn formscheck_field" data-title="' + tabletitle + '" data-size="' + tablesize + '"  id="' + datatable + '_' + j + '"  data-id="' + datatable + '" value="' + j + '" ></label></div>';
                }
                j++;
            });

            var sub_btn = '<button type="button"  data-column1="' + datatable + '" class="btn btn btn_submit btn-sm pull-right mt20 phsallorderdisplaycolumn" id="phsallorderdisplaycolumn">Save</button>';

            //var dfoption = '<option value="" disabled selected hidden>Please Choose...</option>'
            $('#' + columnshowhide + '').html(th + sub_btn);
            $('#' + columnsgroupdropdown + '').html(thd);




        });

        $('.chkthcolumnhhideshow').on('change', function () {
            debugger;
            var colno = $(this).attr('data-column');
            var dttable = $(this).attr('data-column1');
            var table = $('#' + dttable + '').DataTable();
            if (colno != 0) {
                if (!$(this).is(':checked')) {
                    //$('#' + dttable + ' tbody tr th').eq(colno).hide();
                    //$('#' + dttable + ' td:nth-child(' + colno + ')').hide();
                    //$('#' + dttable + ' th:nth-child(' + colno + ')').hide();
                    // $('table tbody tr td').eq(colno).hide();
                    //dttable.find('tr :nth-child(' + (colno) + ')').toggle();

                    var column = table.column(colno);
                    column.visible(false);
                }
                else {
                    //$('#' + dttable + ' td:nth-child(' + colno + ')').show();
                    //$('#' + dttable + ' th:nth-child(' + colno + ')').show();
                    var column = table.column(colno);
                    column.visible(true);
                }
            }
            else {
                //$('.chkthcolumnhhideshow').prop('checked', false);
                //$('#' + dttable + ' td').show();
                //$('#' + dttable + ' th').show();
                //$(this).prop('checked', true);
            }

        })

        var dttable1 = '';
        $('.groupscolumn').change(function () {
            debugger;
            var dttable = $(this).attr("data-id");
            var tabletitle = $(this).attr("data-title")
            var tablesize = $(this).attr("data-size")
            var colno = $(this).val();
            if (dttable != undefined) {
                dttable1 = dttable;
            }
            var dname = dttable + '_' + colno;
            // colno = colno.join(',')
            //var colno = [3, 1];
            var selected_value = []; // initialize empty array 
            $(".groupscolumn:checked").each(function () {
                selected_value.push($(this).val());
            });
            //alert(colno);
            var currentselection = $(this).val();
            // var len = $('.groupscolumn :selected').length
            var len = selected_value.length;

            if (len > 3) {
                toastr.warning('only three columns allowed');
                $('#' + dname + '').prop('checked', false);
                return;
            }
            else {
                if (len != 0) {
                    $('#' + dttable + '').dataTable().fnDraw();
                    $('#' + dttable + '').dataTable().fnDestroy();
                    $('#' + dttable + '').DataTable({
                        rowGroup: {
                            dataSrc: selected_value
                        },
                        columnDefs: [{
                            targets: selected_value,
                            visible: false
                        }],
                        "fnInitComplete": function () {
                            // Disable TBODY scoll bars


                            // Enable TFOOT scoll bars
                            $('.dataTables_scrollFoot').css('overflow', 'hidden');

                            $('.dataTables_scrollHead').css('overflow', 'auto');

                            // Sync TFOOT scrolling with TBODY
                            $('.dataTables_scrollFoot').on('scroll', function () {
                                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                            });

                            $('.dataTables_scrollHead').on('scroll', function () {
                                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                            });
                        },
                        "scrollX": true,
                        "scrolly": true,
                        responsive: true,
                        "scrollCollapse": true,
                        "sScrollY": "500px",
                        "fixedHeader": {
                            header: true,
                            footer: true
                        },
                        "fixedColumns": {
                            leftColumns: 2
                        },
                        "colResize": {
                            "tableWidthFixed": false,
                            "resizeCallback": function (column) {

                            }
                        },

                        "deferRender": true,

                        dom: 'lBfrtip',
                        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                        buttons: [
                        ]
      
                    });
                        var d = new Date();
                        var month = d.getMonth() + 1;
                        var day = d.getDate();
                        var output = (day < 10 ? '0' : '') + day + '/' + (month < 10 ? '0' : '') + month + '/' + d.getFullYear();
                        var downloadfilename = "";
                        if (tabletitle == "Patient List") {
                            downloadfilename = "PatientList" + output;
                        }
                        else {
                            downloadfilename = tabletitle;
                        }

                        var table = $('#' + dttable + '').DataTable();
                        var buttons = new $.fn.dataTable.Buttons(table, {
                            buttons: [
                      {
                          extend: 'copyHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-files-o" aria-hidden="true"></i> Download as Copy', titleAttr: 'Download as Copy',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'excelHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-excel-o" aria-hidden="true"></i> Download as Excel', titleAttr: 'Download as Excel', footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'csvHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-text-o" aria-hidden="true"></i> Download as CSV', titleAttr: 'Download as CSV',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'pdfHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-pdf-o" aria-hidden="true"></i> Download as PDF', titleAttr: 'Download as PDF',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          orientation: 'landscape',
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      }
                            ]
                        }).container().appendTo($('#buttons'));
                       
                        // fixed header - 
                        new $.fn.dataTable.FixedHeader(table);
                    

                }
                else {
                   $('#' + dttable1 + '').dataTable().fnDestroy();
                    $('#' + dttable1 + '').DataTable({


                       "fnInitComplete": function () {
                            // Disable TBODY scoll bars


                            // Enable TFOOT scoll bars
                            $('.dataTables_scrollFoot').css('overflow', 'hidden');

                            $('.dataTables_scrollHead').css('overflow', 'auto');

                            // Sync TFOOT scrolling with TBODY
                            $('.dataTables_scrollFoot').on('scroll', function () {
                                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                            });

                            $('.dataTables_scrollHead').on('scroll', function () {
                                $('.dataTables_scrollBody').scrollLeft($(this).scrollLeft());
                            });
                        },
                        "scrollX": true,
                        "scrolly": true,
                        responsive: true,
                        "scrollCollapse": true,
                        "sScrollY": "500px",
                        "fixedHeader": {
                            header: true,
                            footer: true
                        },
                        "colResize": {
                            "tableWidthFixed": false,
                            "resizeCallback": function (column) {

                            }
                        },

                        "deferRender": true,

                        dom: 'lBfrtip',
                        "lengthMenu": [[10, 25, 50, -1], [10, 25, 50, "All"]],
                        buttons: [
                        ]
      
                    });
                        var d = new Date();
                        var month = d.getMonth() + 1;
                        var day = d.getDate();
                        var output = (day < 10 ? '0' : '') + day + '/' + (month < 10 ? '0' : '') + month + '/' + d.getFullYear();
                        var downloadfilename = "";
                        if (tabletitle == "Patient List") {
                            downloadfilename = "PatientList" + output;
                        }
                        else {
                            downloadfilename = tabletitle;
                        }

                        var table = $('#' + dttable + '').DataTable();
                        var buttons = new $.fn.dataTable.Buttons(table, {
                            buttons: [
                      {
                          extend: 'copyHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-files-o" aria-hidden="true"></i> Download as Copy', titleAttr: 'Download as Copy',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'excelHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-excel-o" aria-hidden="true"></i> Download as Excel', titleAttr: 'Download as Excel', footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'csvHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-text-o" aria-hidden="true"></i> Download as CSV', titleAttr: 'Download as CSV',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      },
                      {
                          extend: 'pdfHtml5', footer: true, title: tabletitle, text: '<i class="fa fa-file-pdf-o" aria-hidden="true"></i> Download as PDF', titleAttr: 'Download as PDF',
                          footer: true,
                          stripHtml: false,
                          decodeEntities: true,
                          filename: downloadfilename,
                          orientation: 'landscape',
                          pageSize: tablesize,
                          paging: true,
                          exportOptions: {
                              columns: ':not(:last-child)'
                          }
                      }
                            ]
                        }).container().appendTo($('#buttons'));
                       
                        // fixed header - 
                        new $.fn.dataTable.FixedHeader(table);

                }
            }
        })

        $('.phsallorderdisplaycolumn').click(function () {

            debugger;
            var dttable = $(this).attr('data-column1');
            var tharry = new Array();
            //$("#" + dttable + " thead tr th").each(function () {
            var table = $("#" + dttable + "").DataTable();

            //iterate through every column in the table.
            table.columns().every(function (index) {
                //var visible = this.visible();
                //if (!visible)
                //alert(this.header().innerHTML);


                var thobject = {};
                var tdname = this.header().innerHTML;
                var tdindex = index;
                if (tdname != 'Actions' && tdname != 'S.No' && tdname !='View More') {
                    var tdd = {}
                    var tdnameid = tdname.replace(/ +/g, "")
                    tdd.Dml_Indicator = 'HTCV';
                    tdd.id = 0;
                    tdd.columnindex = tdindex;
                    tdd.tableid = dttable;
                    tdd.hospitalid = hospitalid;
                    tdd.branchid = 0;
                    tdd.columnnames = dttable + tdnameid;
                    //  tdd.status = $("#" + dttable + tdnameid + "").is(':checked') ? 1 : 0;
                    // $("#" + $.escapeSelector("[metachar]"))
                    tdd.status = $("#" + $.escapeSelector("" + dttable + tdnameid + "")).is(':checked') ? 1 : 0;
                    tdd.formid = $('#formid').val();
                    tdd.userid = $('#HiddenUserCreatedBy').val();
                    tharry.push(tdd);
                }
            })

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

                    }
                    else {
                        toastr.success('Successfully Submitted');

                    }
                }
            });
            //alert(tharry);
        });
    });

    function chkttablecolumnstatus(columnsgroupdropdown) {
        debugger;

        var formdata = {
            formid: $('#formid').val(),
            tableid: columnsgroupdropdown,
            userid: $('#HiddenUserCreatedBy').val(),
            Dml_Indicator: 'CHKCV'
        }

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

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

                    }
                    else {
                        $.each(data1.Table, function (i, emp) {
                            debugger;
                            var columnnames = emp.columnnames
                            var status = emp.status
                            var cellindex = emp.columnindex
                            var table = $("#" + emp.tableid + "").DataTable();
                            if (status == 0) {
                                //  $('#' + columnnames + '').prop('checked', false);
                                $('#' + $.escapeSelector("" + columnnames + "")).prop('checked', false);


                                //$('#' + emp.tableid + ' td:nth-child(' + cellindex + ')').hide();
                                //$('#' + emp.tableid + ' td:nth-child(' + cellindex + ')').hide();
                                //$('#' + emp.tableid + ' th:nth-child(' + cellindex + ')').hide();

                                var column = table.column(cellindex);
                                column.visible(false);
                            }
                        });
                    }
                }
            }
        });
    }

    $(function () {
        //Initialize Select2 Elements
        $('.select2').select2()
    });

    $('#lhschedate').datepicker({
        autoclose: true,
        todayHighlight: true,
        //endDate: new Date()
    });
    $('.visiteddate').datepicker({
        autoclose: true,
        todayHighlight: true,
        endDate: new Date()
    });
    $('#lhschFTime').timepicker({
        showInputs: false
    });
    $('#lhschdFTime').timepicker({
        showInputs: false
    });





});

function chkttablecolumnstatus(columnsgroupdropdown) {
    debugger;

    var formdata = {
        formid: $('#formid').val(),
        tableid: columnsgroupdropdown,
        userid: $('#HiddenUserCreatedBy').val(),
        Dml_Indicator: 'CHKCV'
    }

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

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

                }
                else {
                    $.each(data1.Table, function (i, emp) {
                        debugger;
                        var columnnames = emp.columnnames
                        var status = emp.status
                        var cellindex = emp.columnindex
                        var table = $("#" + emp.tableid + "").DataTable();
                        if (status == 0) {
                            // $('#' + columnnames + '').prop('checked', false);
                            $('#' + $.escapeSelector("" + columnnames + "")).prop('checked', false);

                            //$('#' + emp.tableid + ' td:nth-child(' + cellindex + ')').hide();
                            //$('#' + emp.tableid + ' td:nth-child(' + cellindex + ')').hide();
                            //$('#' + emp.tableid + ' th:nth-child(' + cellindex + ')').hide();

                            var column = table.column(cellindex);
                            column.visible(false);
                        }
                    });
                }
            }
        }
    });
}