$(document).ready(function () {
    document.documentElement.addEventListener('click', function (event) {
        if (event.ctrlKey) {
            event.preventDefault()
        }
    });

    document.documentElement.addEventListener('contextmenu', function (event) {
        event.preventDefault()
    });

    document.documentElement.addEventListener('mouseup', function (event) {
        if (event.button === 1) {
            event.preventDefault()
        }
    });

    $('#col1CheckAll').on('ifToggled', function () {
        var is_checked = ($('#col1CheckAll').is(':checked'));
        $(this).parents('table').find('tr:nth-of-type(n+1)').each(function () {
            if (is_checked) {
                $(this).find('td:nth-of-type(1) input[type="checkbox"]').iCheck('check');
            } else {
                $(this).find('td:nth-of-type(1) input[type="checkbox"]').iCheck('uncheck');
            }
        });
    });
    $('#col2CheckAll').on('ifToggled', function () {
        var is_checked = ($('#col2CheckAll').is(':checked'));
        $(this).parents('table').find('tr:nth-of-type(n+1)').each(function () {
            if (is_checked) {
                $(this).find('td:nth-of-type(2) input[type="checkbox"]').iCheck('check');
            } else {
                $(this).find('td:nth-of-type(2) input[type="checkbox"]').iCheck('uncheck');
            }
        });
    });
});

function initiateFullCalendar() {
    if ($(document).find('[data-container="table"] #calendar').length == 1) {
        calendarInit();
    }
}

function showError(msg, timeout) {

    var showtime = timeout ? timeout : 2500;

    $('.content').prepend('<div id="errorMessage" class="alert alert-danger animated fadeInDown" style="width:50%; margin: 0 auto; margin-bottom: 20px; text-align: center">\n' +
        '    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>\n' +
        '    <strong>' + msg + '</strong>\n' +
        '</div>');
    setTimeout(function () {
        $('.alert').remove();
    }, showtime);
}

function showSuccess(msg, timeout) {

    var showtime = timeout ? timeout : 2500;

    $('.content').prepend('<div id="successMessage" class="alert alert-success animated fadeInDown" style="width:50%; margin: 0 auto; margin-bottom: 20px; text-align: center">\n' +
        '    <a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>\n' +
        '    <strong>' + msg + '</strong>\n' +
        '</div>');
    setTimeout(function () {
        $('.alert').remove();
    }, showtime);
}

function hideMessages() {
    $('#successMessage').remove();
    $('#errorMessage').remove();
}

function initEditor() {
    tinymce.init({
        selector: '.tinymce',
        language: 'pl',
        toolbar: 'undo redo | styleselect | bold underline italic | alignleft aligncenter alignright'
    });
}

$(document).ready(function () {
    initEditor();
});

//active menu item
function setActiveNav() {
    var currentHref = window.location.pathname;
    var currentLink = $('.sidebar-menu').find('a[href="' + currentHref + '"]');

    if (typeof currentLink == "undefined" || currentLink.length <= 0) {
        var kadry =
            ['/umowy_o_prace', '/nieobecnosci', '/przebiegi_pracy',
                '/wyksztalcenia', '/badania', '/szkolenia',
                '/kary', '/jezyki', '/kwalifikacje', '/rodzina',
                '/ocena_pracownika', '/plan_urlopu', '/akceptacja_planu_urlopu', '/dokumenty', '/zawiesia'];
        if (kadry.indexOf(currentHref) > -1) {
            currentLink = $('.sidebar-menu a#kadry');
        }
    }

    var zastepstwa = [
        '/dodaj_zastepstwo'
    ];
    if (zastepstwa.indexOf(currentHref) > -1) {
        currentLink = $('.sidebar-menu a#zastepstwa');
    }

    var treeview_menu = currentLink.parents('.treeview-menu');
    if (typeof treeview_menu !== "undefined" && treeview_menu.length > 0) {
        treeview_menu.parent('.treeview').addClass('active');
        treeview_menu.addClass('menu-open');
        treeview_menu.children().each(function () {
            $(this).removeClass('active');
        });
    }
    currentLink.parent('li').addClass('active');
}

//initiate checkboxes
function checkboxesInit(parentClass) {
    var selector;
    if (typeof parentClass === "undefined") {
        selector = 'input[type="checkbox"]';
    } else {
        selector = parentClass + ' input[type="checkbox"]';
    }
    if ($(selector).length > 0) {
        $(selector).iCheck({
            checkboxClass: 'icheckbox_minimal-red icheck',
        });

        if ($(selector).parents('.modal').data('single') == 1) {
            $(selector).on('ifChanged', function (event) {
                if ($(this).is(':checked')) {
                    $(selector).prop('checked', false);
                    var t = $(this);
                    $(selector).each(function () {
                        if ($(this) != t) {
                            $(this).iCheck('uncheck');
                            $(this).iCheck('update');
                        }
                    });
                }
            });
        }
    }
}

function datepickerInit() {
    $(document).find('.datepicker').datetimepicker({
        format: "YYYY-MM-DD",
        locale: 'pl',
        keepOpen: false,
        showClose: true,
        useCurrent: false
    }).on('dp.change', function (ev) {
        $('.datepicker').trigger('blur');

        $('#SprawdzWniosekResponse').html('');
    });
}

function datepickerFromToInit() {
    $(document).find('.datepicker-from').datetimepicker({
        format: "YYYY-MM-DD",
        locale: 'pl',
        keepOpen: false,
        showClose: true,
        useCurrent: false
    }).on('dp.change', function (ev) {
        $('.datepicker-from').trigger('blur');
        $('.datepicker-to').trigger('blur');

        $('#SprawdzWniosekResponse').html('');

        var minDate = $(this).val();

        var currentDate = $(document).find('.datepicker-to').val();

        $(document).find('.datepicker-to').datetimepicker('destroy').datetimepicker({
            format: "YYYY-MM-DD",
            locale: 'pl',
            keepOpen: false,
            showClose: true,
            minDate: minDate
        }).on('dp.change', function (ev) {
            $('.datepicker-from').trigger('blur');
            $('.datepicker-to').trigger('blur');
        }).on('dp.show', function () {
        });

        $(document).find('.datepicker-to').val(currentDate);
    });

    var first_open_date_from = true;

    $(document).find('.datepicker-to').datetimepicker({
        format: "YYYY-MM-DD",
        locale: 'pl',
        keepOpen: false,
        showClose: true
    }).on('dp.change', function (ev) {
        $('.datepicker-from').trigger('blur');
        $('.datepicker-to').trigger('blur');
    }).on('dp.show', function () {
        // console.log($(this).val());
        // if(first_open_date_from) {
        //     first_open_date_from = false;
        //     $(this).data('DateTimePicker').date($('.datepicker-from').val());
        //     $(this).datetimepicker('show');
        // }
    });
}

function datetimepickerInit() {
    $(document).find('.datetimepicker').datetimepicker({
        format: "YYYY-MM-DD HH:mm",
        locale: 'pl',
        keepOpen: false,
        showClose: true
    }).on('dp.change', function (ev) {
        $('.datepicker').trigger('blur');
    });
}

function timepickerInit() {

    $(document).find('.timepicker').datetimepicker({
        format: 'HH:mm',
        locale: 'pl',
        keepOpen: false,
        showClose: true,
        date: null
    }).on('dp.change', function (ev) {
        $('.timepicker').trigger('blur');
    });
}

function timepickerValid() {

    $('.timepicker').focusout(function () {

        var str = this.value;
        var re;

        if (str.length >= 5) {
            re = new RegExp('^([01]\\d|2[0-3]):?([0-5]\\d)$');
            if (re.test(this.value) === false) {
                this.value = '00:00';
            }
        } else if (str.length >= 4) {
            re = new RegExp('^([0-9]{1}|1[0-9]|2[0-3]):?([0-5]\\d)$');
            if (re.test(this.value) === false) {
                this.value = '00:00';
            } else {
                this.value = '0' + str;
            }
        } else {
            re = new RegExp('^[0-9]{1,}$');
            if (re.test(this.value) === false) {
                this.value = '00:00';
            } else {
                this.value = str + ':00';
            }
        }
    });
}

//get calendar events
function getCalendarEvents(url) {
    var events;
    $.ajax({
        url: url,
        type: 'GET',
        data: null,
        dataType: 'JSON',
        async: false,
        beforeSend: function () {

        },
        success: function (response) {
            events = response;
        },
        error: function (response) {
            console.log(response);
        }
    });
    return events;
}

function addInput() {
    if ($('#datepicker').length == 0) {
        $('.fc-right').prepend('<input type="text" name="datepicker" data-events-url="calendar_feed_ajax" class="chooseMonthDatepicker" placeholder="Wybierz miesiąc" id="datepicker" autocomplete="off"/>');
        $(document).find('#datepicker').datepicker({
            format: "YYYY-MM",
            locale: 'pl',
            changeMonth: true,
            changeYear: true,
            showButtonPanel: true,

            onClose: function (dateText, inst) {
                var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
                var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
                $(this).val($.datepicker.formatDate('MM yy', new Date(year, month, 1)));
                month = parseInt(month) + 1;
                if (month < 10) {
                    $('#calendar').fullCalendar("gotoDate", year + "-0" + month + "-01");
                } else {
                    $('#calendar').fullCalendar("gotoDate", year + "-" + month + "-01");
                }
            }
        });

        $("#datepicker").focus(function () {
            $(".ui-datepicker-calendar").hide();
            $("#ui-datepicker-div").position({
                my: "center top",
                at: "center bottom",
                of: $(this)
            });
        });
    }
}

//initiate calendar
//#calendar element needs data-events-url to fetch.
function calendarInit() {
    var calendar = $('#calendar');
    if (calendar.length > 0) {
        var eventSource = calendar.data('events-url');
        var events = getCalendarEvents(eventSource);
        calendar.fullCalendar({
            locale: 'pl',
            // events: events,
            // eventSources: [
            //
            //     // your event source
            //     {
            //         url: calendar.data('events-url'),
            //         type: 'POST',
            //         data: {
            //             custom_param1: 'cp1',
            //             custom_param2: 'cp2'
            //         },
            //         error: function() {
            //             console.log('there was an error while fetching events!');
            //         },
            //         color: '#dd4b39',   // a non-ajax option
            //         textColor: 'white' // a non-ajax option
            //     }
            //
            //     // any other sources...
            //
            // ],

            eventOrder: 'index',
            header: {
                left: 'title',
                center: '',
                right: 'today prev,next'
            },
            titleFormat: 'MMMM YYYY',
            buttonText: {
                today: 'Aktualny miesiąc',
            },
            eventColor: '#dd4b39',
            height: 'parent',
            events: {
                url: calendar.data('events-url'),
                type: 'POST',
                error: function () {
                },
                beforeSend: function () {
                    // $(document).find('.custom-loader').css('display', 'block');
                    $('.loader-holder').css('visibility', 'visible').css('opacity', 1);
                },
                success: function (data) {
                    $(document).find('.holiday-day').removeClass('holiday-day');
                    $(document).find('.grey-day').removeClass('grey-day');
                    var event
                    for (var _event in data) {
                        event = data[_event];
                        if (event['czySwieto'] != undefined && event['czySwieto'] == true) {
                            $(document).find('.fc-day-top[data-date="' + event.start + '"]').addClass('holiday-day')
                        }
                        if (event['czyUmowa'] == false || event['czyUmowa'] == 'false') {
                            $(document).find('.fc-day[data-date="' + event.start + '"]').addClass('grey-day')
                        }
                    }
                    if (event !== undefined && event.print) {
                        $('#print_report').show();
                    }
                    if (event !== undefined && event['informacjaDodatkowa']) {
                        $('#informacjaDodatkowa').html(event['informacjaDodatkowa']);
                    }
                    // $(document).find('.custom-loader').css('display', 'none');
                    $('.loader-holder').css('visibility', 'hidden').css('opacity', 0);
                }
            },
            viewRender: function (view, element) {
                var title = $('.clickable-row.active td:nth-of-type(2)').html();
                if (title !== undefined) $('#calendar .fc-center').html('<h4>' + title + '</h4>');
                // $(document).find('.custom-loader').css('display', 'none');
            },
            complete: function () {
                // $(document).find('.fc-scroller').attr('style', 'height: calc(100vh - 150px)!important');
            },
            eventAfterAllRender: function (view) {
                // $(document).find('.fc-scroller').attr('style', 'height: calc(100vh - 150px)!important');
            }
        });

        addInput();
    }

    function get_calendar_height() {
        var height = $('#calendar').parents('.box-body').height();
        if ($('#calendar').parents('.box-body').attr('id') == 'GrafikBoxBody') {
            height -= 50;
        }
        return height;
    }

//attacht resize event to window and set fullcalendar height property
    $(document).ready(function () {
        $(window).resize(function () {
            $('#calendar').fullCalendar('option', 'height', get_calendar_height());
        });
    });

}

//show loader
function showLoader(loader) {
    $(loader).addClass('active');
}

//hide loader
function hideLoader(loader) {
    $(loader).removeClass('active');
}

//toggle loader
function toggleLoader(loader) {
    $(loader).toggleClass('active');
}

//remove element with control and jquery animation parameter
function getRidOf(element, control, animate, time) {
    if (typeof time === 'undefined') {
        time = 200;
    }
    if (control == 'parent') {
        if (animate == 'slideUp') {
            $(element).parent().slideUp(time);
            return;
        }
        if (animate == 'fadeOut') {
            $(element).parent().fadeOut(time);
            return;
        }
        $(element).parent().remove();
        return;
    }
    if (control == 'children') {
        if (animate == 'slideUp') {
            $(element).children().each(function () {
                $(this).slideUp(time);
            });
            return;
        }
        if (animate == 'fadeOut') {
            $(element).children().each(function () {
                $(this).fadeOut(time);
            });
            return;
        }
        $(element).children().remove();
        return;
    }
    if (animate == 'slideUp') {
        $(element).slideUp(time);
        return;
    }
    if (animate == 'fadeOut') {
        $(element).fadeOut(time);
        return;
    }
}

//More info click event
$(document).on('click', '.more-info-append', function (e) {
    e.preventDefault();
    e.stopPropagation();
    var appendTarget = $(this).data('append-to');
    var moreInfo = $(this).data('more-info');
    if (typeof appendTarget !== 'undefined' && typeof moreInfo !== 'undefined') {
        $(appendTarget).html('<p>' + moreInfo + '</p>');
        if (moreInfo.length > 0) $('.more-info-container').show('fast');
    }
});

// filter by application status
$(document).on('change', '#application_status_filter', function () {
    var targetTable = $($(this).data('table'));
    var selectedFilter = $(this).val();
    var rows = $(targetTable).children('tbody').children('tr');
    if (selectedFilter == 'Wszystkie') {
        rows.show();
    } else {
        $.each(rows, function () {
            if ($(this).data('status') == selectedFilter) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
});

/**
 * runDataTable function
 * @param action
 */
function runDataTable(action) {
    $.fn.dataTable.ext.order.intl('pl');
    if (action != 'daj_profil' && action != 'daj_zdarzenia') {

        $('[data-container="table"] .custom-table').each(function () {
            var dataTableOptions = {
                "paging": false,
                "language": {
                    "url": local_url + "js/datatable-pl.json"
                }
            };

            if ($(this).data('start-sort') != undefined) {
                dataTableOptions['order'] = [[$(this).data('start-sort'), $(this).data('start-sort-direction')]];
            }
            if ($(this).data('start-height') != undefined) {
                dataTableOptions['scrollY'] = $(this).data('start-height');
                dataTableOptions['scrollCollapse'] = true;
            }

            if ($(this).attr('id') == 'UsersTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'UsersRoleTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'RolesTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'SciezkiAkceptacjiTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'ZastepstwaTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).data('messages-homepage') == true || $(this).attr('id') == 'WnioskiHomepageTable') {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 320)) + "px";
                if ($(this).attr('id') == 'WnioskiHomepageTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 220)) + "px";
                }
            }
            if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250)) + "px";
                if ($(this).hasClass('OtherPracownicyTable')) {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 300)) + "px";
                }
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350)) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegPracyTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310)) + "px";
                }
            }
            if (window.innerWidth < 1585) {
                if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250 - 60)) + "px";
                    if ($(this).attr('id') == 'NieobecnosciTable') {
                        dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350 - 40)) + "px";
                    }
                    if ($(this).attr('id') == 'PrzebiegPracyTable') {
                        dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310 - 40)) + "px";
                    }
                }
            }

            if ($(this).attr('id') == 'PracownicyTable') {
                if (parseFloat(dataTableOptions['scrollY'].replace('px', '')) < 25) dataTableOptions['scrollY'] = "90px";
            }

            if ($(this).hasClass('FullTable')) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 380) + "px";
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegiPracy') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 420) + "px";
                }
                if ($(this).attr('id') == 'WyksztalceniaTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
                }
                if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 330) + "px";
                }
                if ($(this).attr('id') == 'PlanUrlopuTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 370) + "px";
                }
                if (window.innerWidth < 1585) {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 380 - 90) + "px";
                    if ($(this).attr('id') == 'NieobecnosciTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'PrzebiegiPracy') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 420 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'WyksztalceniaTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 330 - 100) + "px";
                    }
                    if ($(this).attr('id') == 'PlanUrlopuTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 370 - 90) + "px";
                    }
                }
            }

            if ($(this).attr('id') == 'MessagesTable' && $(this).data('messages-homepage') == false) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 380) + "px";
            }

            if ($(this).attr('id') == 'MessagesTable' && $(this).parents('.home-messages-container').length == 1 && $('#WnioskiHomepageTable').length == 1) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() / 2 - 240) + "px";
            }

            if ($(this).data('start-filter') != undefined) {
                var tId = $(this).attr('id');
                dataTableOptions['initComplete'] = function () {
                    this.api().columns().every(function () {
                        var column = this;
                        if (column[0][0] == 0) {
                            var select = $('<select class="form-control" id="FilterSelectTable"><option value=""></option></select>')
                                // .appendTo( $(column.footer()).empty() )
                                .appendTo($('#' + tId + '_length'))
                                // .appendTo( $('#'+$(this).attr('id')+'_0_length') )
                                .on('change', function () {
                                    var val = $.fn.dataTable.util.escapeRegex(
                                        $(this).val()
                                    );

                                    column
                                        .search(val ? '^' + val + '$' : '', true, false)
                                        .draw();
                                });

                            column.data().unique().sort().each(function (d, j) {
                                select.append('<option value="' + d + '">' + d + '</option>')
                            });
                        }
                    });
                }
            }

            if ($(this).attr('id') == 'UsersTable') {
                dataTableOptions['stateSave'] = true;
            }

            if ($(this).hasClass('dokument-class-table')) {
                dataTableOptions['rowGroup'] = {
                    dataSrc: 2
                };
            }

            $(this).dataTable(dataTableOptions);
            datatableHeaders();

            if (typeof action !== 'undefined' && action == 'wiadomosci') {
                setTimeout(function () {
                    var selectInput = $('#ChangeMessagePriorContainer').clone();
                    selectInput.find('select').attr('id', 'ChangeMessagePrior');
                    selectInput.removeClass('hidden');
                    $('#MessagesTable_filter').append(selectInput);
                }, 500);
            }
        })
    }

    initiateFullCalendar();
}

function initialTableContent() {
    if ($('[data-active="1"]').length == 1) {
        var initialTable = $('[data-active="1"]');
        var single = initialTable.data('single');
        var isSingle = typeof initialTable.data('single') !== 'undefined';
        if (isSingle) {
            var action = initialTable.data('action');
            var param = initialTable.data('value');
            load_table_content(action, param);
        }
    }
}

function fileInput(input, removeButtonId) {
    var fileNames = '';
    if ($(input)[0].files.length < 1) {
        $(input).siblings('span').html("Wybierz pliki");
        $(removeButtonId).fadeOut('fast');
    } else {
        $.each($(input)[0].files, function (index, value) {
            if (index > 0) {
                fileNames += ', ' + value.name;
            } else {
                fileNames += value.name;
            }
        });
        $(input).siblings('span').html(fileNames);
        $(removeButtonId).fadeIn('fast');
    }
}

function clearFileInput(input, button) {
    $(button).fadeOut('fast');
    $(input).val('').siblings('span').html("Wybierz pliki");
}

var counterFiles = 0;

function initMultipleFiles() {
    counterFiles++;
    var f = $(document).find('[data-file-multiple]:first-of-type').clone();
    $(document).find('[data-file-multiple]:last-of-type').after(f);
    $(document).find('[data-file-multiple]:last-of-type').addClass('col-md-offset-2 mb10');
    $(document).find('[data-file-multiple]:last-of-type').show();
    $(document).find('[data-file-multiple]:last-of-type #file-selector').attr('id', 'file-selector-' + counterFiles);
    $(document).find('[data-file-multiple]:last-of-type label').attr('for', 'file-selector-' + counterFiles);
    $(document).find('[data-file-multiple]:last-of-type #remove-attachments').attr('onclick', 'clearFileInputSingle("#file-selector-' + counterFiles + '", this)');
}

$(document).on('click', '[data-usun-zalacznik]', function () {
    $(this).parents('[data-file-multiple]').remove();
});

$(document).ready(function () {
    initMultipleFiles();
});

function fileInputMultiple(input, removeButtonId) {
    var fileNames = '';
    if ($(input)[0].files.length < 1) {
        $(input).siblings('span').html("Wybierz pliki");
        $(removeButtonId).fadeOut('fast');
    } else {
        $.each($(input)[0].files, function (index, value) {
            if (index > 0) {
                fileNames += ', ' + value.name;
            } else {
                fileNames += value.name;
            }
        });
        $(input).siblings('span').html(fileNames);
        $(removeButtonId).show();
        initMultipleFiles();
    }
}

function clearFileInputSingle(input, button) {
    $(button).parents('[data-file-multiple]').remove();
}

function passwordRepeat() {
    if ($('.password-repeat').length > 0) {
        $('.password-repeat').each(function (index) {
            var $this = $(this);
            $this.blur(function () {
                var repeatValue = $this.val(),
                    $repeatFormGroup = $this.parents('.form-group'),
                    compareInputId = $this.data('compare-target'),
                    $compareInput = $(compareInputId),
                    compareValue = $compareInput.val(),
                    $compareFormGroup = $compareInput.parents('.form-group');
                if (repeatValue != compareValue) {
                    $('input[type="submit"]').attr('disabled', 'disabled');
                    if (!$repeatFormGroup.hasClass('has-error')) {
                        $repeatFormGroup.addClass('has-error');
                    }
                    if (!$compareFormGroup.hasClass('has-error')) {
                        $compareFormGroup.addClass('has-error');
                    }
                } else {
                    $('input[type="submit"]').removeAttr('disabled');
                    if ($repeatFormGroup.hasClass('has-error')) {
                        $repeatFormGroup.removeClass('has-error');
                    }
                    if ($compareFormGroup.hasClass('has-error')) {
                        $compareFormGroup.removeClass('has-error');
                    }
                }
            });
        });
    }
}

function initiateDataTable(rowGroupCol) {
    $(document).find('.custom-table').each(function () {
        var dataTableOptions = {
            "paging": false,
            "language": {
                "url": local_url + "js/datatable-pl.json"
            }
        };

        if ($(this).data('start-sort') != undefined) {
            dataTableOptions['order'] = [[$(this).data('start-sort'), $(this).data('start-sort-direction')]];
        }
        if ($(this).data('start-height') != undefined) {
            dataTableOptions['scrollY'] = $(this).data('start-height');
            dataTableOptions['scrollCollapse'] = true;
        }

        if ($(this).attr('id') == 'UsersTable') {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
        }
        if ($(this).attr('id') == 'UsersRoleTable') {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
        }
        if ($(this).attr('id') == 'RolesTable') {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
        }
        if ($(this).attr('id') == 'SciezkiAkceptacjiTable') {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
        }
        if ($(this).attr('id') == 'ZastepstwaTable') {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
        }
        if ($(this).data('messages-homepage') == true || $(this).attr('id') == 'WnioskiHomepageTable') {
            dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 320)) + "px";
            if ($(this).attr('id') == 'WnioskiHomepageTable') {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 220)) + "px";
            }
        }
        if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
            dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250)) + "px";
            if ($(this).hasClass('OtherPracownicyTable')) {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 300)) + "px";
            }
            if ($(this).attr('id') == 'NieobecnosciTable') {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350)) + "px";
            }
            if ($(this).attr('id') == 'PrzebiegPracyTable') {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310)) + "px";
            }
        }
        if (window.innerWidth < 1585) {
            console.log('lower');
            if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250 - 60)) + "px";
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350 - 40)) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegPracyTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310 - 40)) + "px";
                }
            }
        }

        if ($(this).attr('id') == 'PracownicyTable') {
            if (parseFloat(dataTableOptions['scrollY'].replace('px', '')) < 25) dataTableOptions['scrollY'] = "90px";
        }

        if ($(this).hasClass('FullTable')) {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 380) + "px";
            if ($(this).attr('id') == 'NieobecnosciTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
            }
            if ($(this).attr('id') == 'PrzebiegiPracy') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 420) + "px";
            }
            if ($(this).attr('id') == 'WyksztalceniaTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
            }
            if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 330) + "px";
            }
            if ($(this).attr('id') == 'PlanUrlopuTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 370) + "px";
            }
            if (window.innerWidth < 1585) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 380 - 90) + "px";
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegiPracy') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 420 - 90) + "px";
                }
                if ($(this).attr('id') == 'WyksztalceniaTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                }
                if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 330 - 100) + "px";
                }
                if ($(this).attr('id') == 'PlanUrlopuTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 370 - 90) + "px";
                }
            }
        }

        if ($(this).attr('id') == 'MessagesTable' && $(this).data('messages-homepage') == false) {
            dataTableOptions['scrollY'] = ($(window).innerHeight() - 350) + "px";
        }

        if ($(this).attr('id') == 'MessagesTable' && $(this).parents('.home-messages-container').length == 1 && $('#WnioskiHomepageTable').length == 1) {
            dataTableOptions['scrollY'] = ($(window).innerHeight() / 2 - 240) + "px";
        }

        if ($(this).attr('id') == 'PracownicyTable') {
            if (parseFloat(dataTableOptions['scrollY'].replace('px', '')) < 25) dataTableOptions['scrollY'] = "90px";
        }

        if ($(this).data('start-filter') != undefined) {
            var tId = $(this).attr('id');
            dataTableOptions['initComplete'] = function () {
                this.api().columns().every(function () {
                    var column = this;
                    if (column[0][0] == 0) {
                        var select = $('<select class="form-control" id="FilterSelectTable"><option value=""></option></select>')
                            // .appendTo( $(column)footer()).empty() )
                            .appendTo($('#' + tId + '_length'))
                            // .appendTo( $('#'+$(this).attr('id')+'_0_length') )
                            .on('change', function () {
                                var val = $.fn.dataTable.util.escapeRegex(
                                    $(this).val()
                                );

                                column
                                    .search(val ? '^' + val + '$' : '', true, false)
                                    .draw();
                            });

                        column.data().unique().sort().each(function (d, j) {
                            select.append('<option value="' + d + '">' + d + '</option>')
                        });
                    }
                });
            }
        }

        if ($(this).attr('id') == 'UsersTable') {
            dataTableOptions['stateSave'] = true;
        }

        // Add row grouping for DokumentyTable based on the specified column or default to the 3rd column (Kategoria dokumentu)
        if ($(this).attr('id') == 'DokumentyTable') {
            dataTableOptions['rowGroup'] = {
                dataSrc: (rowGroupCol !== undefined) ? rowGroupCol : 2 // Use provided column index or default to 3rd column (0-based index)
            };
        }

        $(this).dataTable(dataTableOptions);
        datatableHeaders();

        if (typeof action !== 'undefined' && action == 'wiadomosci') {
            setTimeout(function () {
                var selectInput = $('#ChangeMessagePriorContainer').clone();
                selectInput.find('select').attr('id', 'ChangeMessagePrior');
                selectInput.removeClass('hidden');
                $('#MessagesTable_filter').append(selectInput);
            }, 500);
        }
    });
}

//document ready
$(document).ready(function () {
    setActiveNav();
    checkboxesInit();
    datepickerInit();
    datepickerFromToInit();
    datetimepickerInit();
    calendarInit();
    initialTableContent();
    runDataTable();
    passwordRepeat();

    initiateDataTable();
});

$(document).on('click', '[data-active]', function (e) {
    e.preventDefault();
    e.stopPropagation();
    $('[data-active]').attr('data-active', 0);
    $(this).attr('data-active', 1);
    var action = $(this).data('action');
    if ($(document).find('.clickable-row.active').length == 1) {
        var element = $(document).find('.clickable-row.active');
        if (element.data('pre-key') !== undefined) {
            //console.log(element.data('pre-key'));
            var prefix = $(document).find('.btn-tile[data-active="1"]').data('value');
            load_table_content(action, prefix + "/" + element.data('pre-key'));
        } else {
            load_table_content(action, element.data('key'));
        }
    } else {
        var single = $(this).data('single');
        if (single == 1) {
            localStorage.setItem('typ_wniosku', $(this).data('value'));
            if ($('[data-filter-active="1"]').length >= 1) {
                var subkey = $('[data-filter-active="1"]').data('filter-value');
                load_table_content(action, $(this).data('value'), subkey);
            } else {
                load_table_content(action, $(this).data('value'));
            }
        }
    }
});

$(document).on('click', '[data-filter-active]', function (e) {
    e.preventDefault();
    e.stopPropagation();
    $('[data-filter-active]').attr('data-filter-active', 0);
    $(this).attr('data-filter-active', 1);
    var action = $(this).data('filter-action');
    var single = $(this).data('single');
    if (single == 1) {
        // $('[data-filter-active]').attr('data-filter-active', 0);
        // $('[data-filter-active]:first-of-type').attr('data-filter-active', 1);
        localStorage.setItem('typ_wniosku_filter', $(this).data('filter-value'));
        load_table_content(action, $('[data-active="1"]').data('value'), $(this).data('filter-value'));
    }
});


$(document).ready(function () {
    $(document).on('ifClicked', '.switch-current-year input', function (event) {
        var activeInput = !$(this).is(":checked");

        if ($(this).attr('data-action-url') != undefined) {

        } else {
            var href = window.location.origin + window.location.pathname;
            if (activeInput) {
                href += "?tylko-ten-rok";
            }
            window.location.href = href;
        }
    });
});

$(document).ready(function () {
    $(document).on('ifClicked', '.switch-accept input', function (event) {
        var activeInput = !$(this).is(":checked");

        if ($(this).attr('data-action-url') != undefined) {

        } else {
            var href = window.location.origin + window.location.pathname;
            if (activeInput) {
                href += "?tylko-akceptacja";
            }
            window.location.href = href;
        }
    });
});

$(document).on('click', '.clickable-row td', function (e) {
    e.preventDefault();
    e.stopPropagation();
    //console.log('cicked row');
    $(this).parents('table').find('tr').removeClass('active');
    $(this).parents('tr').addClass('active');

    var action = $('[data-active="1"]').data('action');
    var key = $(this).parents('tr').data('key');

    if ($(this).parents('tr').data('pre-key') !== undefined) {
        var prefix = $(document).find('.btn-tile[data-active="1"]').data('value');
        load_table_content(action, prefix + "/" + $(this).parents('tr').data('pre-key'));
    } else {
        load_table_content(action, key);
    }
    // load_table_content(action, key);
});
var tableRequest;
var tableRequestRunning = false;

/**
 * load_table_content method
 * @param action
 * @param key
 */
function load_table_content(action, key, subkey) {
    if (tableRequestRunning) {
        tableRequest.abort();
        tableRequestRunning = false;
    }
    tableRequest = $.ajax({
        type: "GET",
        url: local_url + "ajax" + (action.charAt(0) == '/' ? action : '/api/' + action) + "/" + key + (subkey != undefined ? ("/" + subkey) : "") + "?no_cache=" + ((new Date()).getTime()),
        dataType: "html",
        beforeSend: function (a, b) {
            showLoader($('#table-loading'));
            tableRequestRunning = true;
        }
    }).done(function (response) {
        if (trim(response) == 'login') {
            window.location = local_url + 'login';
        } else {
            tableRequestRunning = false;
            $('[data-container="table"]').html(response);
            $('.more-info-container').hide('fast');
            hideLoader($('#table-loading'));
            setTimeout(function () {
                runDataTable(action);
            });
        }
    }).error(function (err) {
        console.log(err);
        if (err.status == 403) {
            window.location = local_url + 'login';
        }
    });
}

/**
 * methods for open/download files
 */
$(document).on('click', '[data-document-download]', function () {
});
$(document).on('click', '[data-document-view]', function () {
    console.log($(this).data('gid'));
    $.ajax({
        url: local_url + 'ajax_daj_dokument/' + $(this).data('gid')
    }).done(function (response) {
        console.log(response);
    });
});

$(document).on('click', '[data-open-tab]', function () {
    window.open($(this).data('href'), '_blank');
});

$(document).on('click', '[data-inner-tab]', function () {
    window.location.href = $(this).attr('href');
});

/**
 * methods for edit/remove "wnioski"
 */
$(document).on('click', '[data-entry]', function () {
    if (confirm('Czy na pewno chcesz usunąć?')) {
        var action = $(this).data('entry');
        var gid = $(this).data('gid');

        $.ajax({
            method: 'POST',
            url: local_url + 'ajax_wniosek_' + action + '/' + gid
        }).done(function (response) {
            //console.log(response);
            if (trim(response) == 'login') window.location = local_url + 'login';

            $('[data-action="daj_wnioski"][data-active="1"]').click();
        });
    }
});

/**
 * tooltip section
 */
$(document).on('mouseenter', '[rel=tooltip]', function () {
    $(this).tooltip('show');
});

$(document).on('mouseleave', '[rel=tooltip]', function () {
    $(this).tooltip('hide');
});

$(window).bind('resize', function () {
    $.fn.dataTable
        .tables({visible: true, api: true})
        .columns.adjust();
});

$(document).ready(function () {
    $(document).on('click', '#PokazWspolpracownikowBtn', function () {
        $('#WspolpracownicyLista').html('');
        /*$.ajax({
            type: "POST",
            url: "/ajax_lista_wspolpracownikow",
            dataType: "json",
            data: {}
        }).done(function(json) {
            console.log(json);
            if(json['wspolpracownicy']['bPracownicy']['bPracownik'] != undefined && json['wspolpracownicy']['bPracownicy']['bPracownik'].length > 0) {
                var workers = json['wspolpracownicy']['bPracownicy']['bPracownik'];
                for(var i=0; i<workers.length; i++) {
                    $('#WspolpracownicyLista').append('<li class="wspolpracownik-kalendarz" data-nrewid="'+workers[i]['bNumerEwidencyjny']+'"><a>'+workers[i]['bNazwiskoImie']+'</a></li>');
                }
            }
        });*/
        $('#modal-show-people').modal('show');
    });

    var wspolpracownicy = [];

    $('#full-calendar').fullCalendar({
        buttonText: {
            today: 'Aktualny miesiąc',
        },
        events: {
            url: local_url + 'calendar_feed_ajax',
            type: 'POST',
            error: function () {
            },
            beforeSend: function () {
                // $(document).find('.custom-loader').css('display', 'block');
                $('.loader-holder').css('visibility', 'visible').css('opacity', 1);
            },
            success: function (data) {
                $(document).find('.holiday-day').removeClass('holiday-day');
                $(document).find('.grey-day').removeClass('grey-day');
                for (var _event in data) {
                    var event = data[_event];

                    if (event['czySwieto'] != undefined && event['czySwieto'] == true) {
                        $(document).find('.fc-day-top[data-date="' + event.start + '"]').addClass('holiday-day')
                    }
                    if (event['czyUmowa'] == false || event['czyUmowa'] == 'false') {
                        $(document).find('.fc-day[data-date="' + event.start + '"]').addClass('grey-day')
                    }
                }
                // $(document).find('.custom-loader').css('display', 'none');
                $('.loader-holder').css('visibility', 'hidden').css('opacity', 0);

                addInput();
            }
        },
        eventRender: function (event, element) {
        }
    });

    $(document).on('click', '[data-nrewid]', function () {
        $('.loader-holder').css('visibility', 'visible').css('opacity', 1);
        $('[data-nrEwid]').removeClass('active');
        $(this).addClass('active');
        var nrEwid = $(this).data('nrewid');
        $('#full-calendar').fullCalendar('removeEvents');
        $('#full-calendar').fullCalendar('removeEventSources');
        $('#full-calendar').fullCalendar('addEventSource', {
            url: local_url + 'calendar_feed_ajax/' + nrEwid + "/true",
            type: 'POST',
            error: function () {
            },
            beforeSend: function () {
                $('.loader-holder').css('visibility', 'visible').css('opacity', 1);
            },
            success: function (data) {
                $(document).find('.holiday-day').removeClass('holiday-day');
                $(document).find('.grey-day').removeClass('grey-day');
                for (var _event in data) {
                    var event = data[_event];

                    if (event['czySwieto'] != undefined && event['czySwieto'] == true) {
                        $(document).find('.fc-day-top[data-date="' + event.start + '"]').addClass('holiday-day')
                    }
                    if (event['czyUmowa'] == false || event['czyUmowa'] == 'false') {
                        $(document).find('.fc-day[data-date="' + event.start + '"]').addClass('grey-day')
                    }
                }

                $('.loader-holder').css('visibility', 'hidden').css('opacity', 0);

                addInput();
            }
        });
    });

    $(document).on('shown.bs.modal', '#modal-show-people', function () {
        var getCalendar = (function () {
            $(document).find('.custom-loader').css('display', 'block');
            var full_url = local_url + 'calendar_feed_ajax_employee';
            if (undefined !== $('#nr_ew_id_pod').val()) {
                full_url = local_url + 'calendar_feed_ajax_employee/' + $('#nr_ew_id_pod').val();
            }
            $.ajax({
                url: full_url,
                method: 'POST',
                dataType: 'html'
            }).done(function (response) {
                if (trim(response) == 'login') window.location = local_url + 'login';

                $('#ModalContentWithNewCallendar').html(response);
                $(document).find('.custom-loader').css('display', 'none');
            }).error(function (err) {
                if (err.status == 403) {
                    window.location = local_url + 'login';
                }
            });
        });

        window.setTimeout(getCalendar, 0);
    });
});

$(document).ready(function () {
    $(window).resize(function () {
        $('.custom-table').each(function () {
            var dataTableOptions = {
                "paging": false,
                "language": {
                    "url": local_url + "js/datatable-pl.json"
                }
            };

            if ($(this).data('start-sort') != undefined) {
                dataTableOptions['order'] = [[$(this).data('start-sort'), $(this).data('start-sort-direction')]];
            }
            if ($(this).data('start-height') != undefined) {
                dataTableOptions['scrollY'] = $(this).data('start-height');
                dataTableOptions['scrollCollapse'] = true;
            }

            if ($(this).attr('id') == 'UsersTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'UsersRoleTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'RolesTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'SciezkiAkceptacjiTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).attr('id') == 'ZastepstwaTable') {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 300) + "px";
            }
            if ($(this).data('messages-homepage') == true || $(this).attr('id') == 'WnioskiHomepageTable') {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 320)) + "px";
                if ($(this).attr('id') == 'WnioskiHomepageTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 220)) + "px";
                }
            }
            if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
                dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250)) + "px";
                if ($(this).hasClass('OtherPracownicyTable')) {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 300)) + "px";
                }
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350)) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegPracyTable') {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310)) + "px";
                }
            }
            if (window.innerWidth < 1585) {
                if ($(this).attr('id') == 'PracownicyTable' || $(this).hasClass('HalfTable')) {
                    dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 250 - 60)) + "px";
                    if ($(this).attr('id') == 'NieobecnosciTable') {
                        dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 350 - 40)) + "px";
                    }
                    if ($(this).attr('id') == 'PrzebiegPracyTable') {
                        dataTableOptions['scrollY'] = ((($(window).innerHeight() / 2) - 310 - 40)) + "px";
                    }
                }
            }

            if ($(this).attr('id') == 'PracownicyTable') {
                if (parseFloat(dataTableOptions['scrollY'].replace('px', '')) < 25) dataTableOptions['scrollY'] = "90px";
            }

            if ($(this).hasClass('FullTable')) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 380) + "px";
                if ($(this).attr('id') == 'NieobecnosciTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
                }
                if ($(this).attr('id') == 'PrzebiegiPracy') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 420) + "px";
                }
                if ($(this).attr('id') == 'WyksztalceniaTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 400) + "px";
                }
                if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 330) + "px";
                }
                if ($(this).attr('id') == 'PlanUrlopuTable') {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 370) + "px";
                }
                if (window.innerWidth < 1585) {
                    dataTableOptions['scrollY'] = ($(window).innerHeight() - 380 - 90) + "px";
                    if ($(this).attr('id') == 'NieobecnosciTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'PrzebiegiPracy') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 420 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'WyksztalceniaTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 400 - 90) + "px";
                    }
                    if ($(this).attr('id') == 'JezykiTable' || $(this).attr('id') == 'DokumentyTable' || $(this).attr('id') == 'OcenaTable' || $(this).attr('id') == 'RodzinaTable' || $(this).attr('id') == 'KaryTable' || $(this).attr('id') == 'KwalifikacjeTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 330 - 100) + "px";
                    }
                    if ($(this).attr('id') == 'PlanUrlopuTable') {
                        dataTableOptions['scrollY'] = ($(window).innerHeight() - 370 - 90) + "px";
                    }
                }
            }

            if ($(this).attr('id') == 'MessagesTable' && $(this).data('messages-homepage') == false) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() - 380) + "px";
            }

            if ($(this).attr('id') == 'MessagesTable' && $(this).parents('.home-messages-container').length == 1 && $('#WnioskiHomepageTable').length == 1) {
                dataTableOptions['scrollY'] = ($(window).innerHeight() / 2 - 240) + "px";
            }

            $(this).parents('.dataTables_scrollBody').attr('style', 'position: relative;overflow: auto;max-height: ' + dataTableOptions['scrollY'] + '!important;width: 100%;');
        });
    });
});

$(function () {
    $(document).on('click', '#DodajOcenePracownikaButton', function () {
        var eId = $(document).find('.clickable-row.active').data('key');
        loadAjaxView("/dodaj_ocene/" + eId);
    });

    setTimeout(function () {
        if (/a=daj_oceny/.test(window.location.search)) {
            $('[data-action="daj_oceny"]').trigger('click');
        }
    });
});

$(document).ready(function () {
    $(document).on('click', '#submitForm-EdytujRole', function (e) {
        e.preventDefault();

        var form = $(this).parents('form');

        var formData = $(form).serializeArray();
        var formAction = $(form).attr('action');

        $.ajax({
            type: 'POST',
            url: formAction,
            data: formData
        }).done(function (response) {
            var r = response;
            response = JSON.parse(response);
            //console.log(response);
            if (trim(r) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response['error'] != undefined) {
                    showError(response['error']);
                } else {
                    hideMessages();
                    showSuccess(response['message']);
                    loadAjaxView('/administracja_role');
                }
            }
        });
    });
});

$(document).ready(function () {
    $(document).on('click', '#submitForm-UprawnieniaRoli', function (e) {
        e.preventDefault();

        var form = $(this).parents('form');

        var formData = $(form).serializeArray();
        var formAction = $(form).attr('action');
        var loader = $('#table-loading2[data-main-loader]');
        loader
            .css('visibility', 'visible')
            .css('opacity', '1')
            .css('display', 'block');

        $.ajax({
            type: 'POST',
            url: formAction,
            data: {
                content: JSON.stringify(formData)
            }
        }).done(function (response) {
            loader
                .css('visibility', 'hidden')
                .css('opacity', '0')
                .css('display', 'none');
            var r = response;
            response = JSON.parse(response);
            //console.log(response);
            if (trim(r) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response['error'] != undefined) {
                    showError(response['error']);
                } else {
                    hideMessages();
                    showSuccess(response['message']);
                    loadAjaxView('/administracja_role');
                }
            }
        });
    });
});

$(document).ready(function () {
    $(document).on('click', '#submitForm-UzytkownicyRoli', function (e) {
        e.preventDefault();

        var form = $(this).parents('form');

        // var formData = $(form).serializeArray();
        var formData = $(form).serializeArray();
        var formAction = $(form).attr('action');

        $.ajax({
            type: 'POST',
            url: local_url + formAction,
            data: {
                content: JSON.stringify(formData)
            }
        }).done(function (response) {
            var r = response;
            response = JSON.parse(response);
            if (trim(r) == 'login') {
                window.location = local_url + 'login';
            } else {
                //console.log(response);
                if (response['error'] != undefined) {
                    showError(response['error']);
                } else {
                    hideMessages();
                    showSuccess(response['message']);
                    loadAjaxView('/administracja_role');
                }
            }
        });
    });
});

$(document).on('click', '[data-remove-entry]', function (e) {
    e.preventDefault();
    var t = $(this);
    if (confirm(t.data('title'))) {
        $.ajax({
            type: 'POST',
            url: local_url + t.data('url') + "/" + t.data('gid')
        }).done(function (response) {
            var r = response;
            response = JSON.parse(response);
            //console.log(response);
            if ((response['login'] != undefined && response['login'] == true) || trim(r) == 'login') {
                window.location = local_url + 'login';
            } else {
                if (response['error'] != undefined) {
                    showError(response['error']);
                } else {
                    hideMessages();
                    showSuccess(response['message']);
                    // loadAjaxView(localStorage.getItem('menu_action'));
                    t.parents('tr').remove();
                }
            }
        }).error(function (err) {
            if (err.status == 403) {
                window.location = local_url + 'login';
            }
        });
    }
});

$(document).on('click', '[data-method="make-action"]', function (e) {
    e.preventDefault();
    var t = $(this);
    $.ajax({
        type: 'GET',
        url: t.data('url')
    }).done(function (response) {
        var r = response;
        response = JSON.parse(response);
        if (trim(r) == 'login') {
            window.location = local_url + 'login';
        } else {
            if (response['error'] != undefined) {
                showError(response['error']);
            } else {
                hideMessages();
                showSuccess(response['message']);
                loadAjaxView(localStorage.getItem('menu_action'));
            }
        }
    }).error(function (err) {
        if (err.status == 403) {
            window.location = local_url + 'login';
        }
    });
});

function datatableHeaders() {
    setTimeout(function () {
        if ($('#MessagesTable').length > 0) {
            $('#MessagesTable_wrapper .row .col-sm-6:first-of-type').html('<h3>Wiadomości</h3>');
        }
        if ($('#WnioskiHomepageTable').length > 0) {
            $('#WnioskiHomepageTable_wrapper .row .col-sm-6:first-of-type').html('<h3>Wnioski</h3>');
        }
    }, 100);
}

function showTop() {
    var body = $("html, body");
    body.stop().animate({scrollTop: 0}, 300, 'swing', function () {
    });
}

$(document).on('change', '#UsersRoleTable_wrapper #showAllChecked input', function () {
    if ($(this).is(':checked')) {
        $('#UsersRoleTable [type="checkbox"]').each(function () {
            if (!$(this).is(':checked')) {
                $(this).parents('tr').hide();
            }
        });
    } else {
        $('#UsersRoleTable [type="checkbox"]').each(function () {
            $(this).parents('tr').show();
        });
    }
});

//KodyNieobecnosciGodzinowych
function hasKnG(kody, val, obj) {
    try {
        if (kody != null && obj != null) {
            obj.hide();
            var valDec = JSON.parse(atob(val));
            wniosek_powod(valDec['dat2:CzyPotrzebnyPowod']);
            kody.forEach(function (entry) {
                if (entry == valDec['dat2:Symbol']) {
                    obj.show();
                    return;
                }
            });
        }
    } catch (e) {
        console.error(e);
    }
}

function wniosek_powod(czyPotrzebnyPowod) {
    var powod = $('#wniosek_powod');
    if (powod && powod.length > 0) {
        if (czyPotrzebnyPowod == 'false') {
            powod.hide();
        } else {
            powod.show();
        }
    }
}

function wniosek_zdalna(czyPracaZdalna) {
    var zdalna = $('#wniosek_zdalna');
    var zastepca = $('#wniosekZastepca');
    var pieChart = $('#CounterFreeDaysHolder');
    var saldoWniosku = $('#saldoWniosku');
    if (zdalna && zdalna.length > 0) {
        if (czyPracaZdalna === false) {
            zdalna.hide();
            zastepca.show();
            pieChart.show();
            saldoWniosku.show();
        } else {
            zdalna.show();
            zastepca.hide();
            pieChart.hide();
            saldoWniosku.hide();
        }
    } else {
        zdalna.hide();
        zastepca.show();
        pieChart.show();
        saldoWniosku.hide();
    }
}

function wniosek_dodatkowe(czyPolaDodatkowe) {
    var codeSelected = $('#codeList option:selected').val();
    var pola_dodatkowe = $('#pola_dodatkowe');
    if (pola_dodatkowe && pola_dodatkowe.length > 0) {
        if (czyPolaDodatkowe === false) {
            pola_dodatkowe.hide();
            $('#pola_dodatkowe div[data-text]').hide();
        } else {
            pola_dodatkowe.show();
            $('#pola_dodatkowe div[data-text]').hide();
            $('#pola_dodatkowe div[data-text="' + codeSelected + '"]').show();
            var postfix = $('#pola_dodatkowe div[data-text="' + codeSelected + '"] input').attr("name");
            var extractedValue = "";

            if (postfix) {
                var match = postfix.match(/_([^_]+)$/);
                if (match && match[1]) {
                    extractedValue = match[1].slice(0, -1);
                }
            }

            $('#wniosek-code').val(extractedValue);
        }
    } else {
        pola_dodatkowe.hide();
        $('#pola_dodatkowe div[data-text]').hide();
    }
}

function wniosek_zdalna_saldo(czyPracaZdalnaSaldo) {
    var wniosek_zdalana_saldo = $('#wniosek_zdalana_saldo');
    if (wniosek_zdalana_saldo && wniosek_zdalana_saldo.length > 0) {
        if (czyPracaZdalnaSaldo === false) {
            wniosek_zdalana_saldo.hide();
        } else {
            wniosek_zdalana_saldo.show();
        }
    } else {
        wniosek_zdalana_saldo.hide();
    }
}

function checkFormAgain() {
    $('#SprawdzWniosek').removeClass('hidden');
    $('form input[type="submit"]').attr("disabled", "disabled").addClass('hidden');
}

function createCalendar() {
    const dates = $('#datepicker').multiDatesPicker('value');

    let dateOd = new Date();
    let dateDo = new Date();
    if ($('[name="pWniosek[dat:DataOd]"]').val().length != 0) {
        dateOd = new Date($('[name="pWniosek[dat:DataOd]"]').val());
    }
    const newDateOd = dateOd.getDate() + '.' + (dateOd.getMonth() + 1) + '.' + dateOd.getFullYear();
    if ($('[name="pWniosek[dat:DataDo]"]').val().length != 0) {
        dateDo = new Date($('[name="pWniosek[dat:DataDo]"]').val());
    }
    const newDateDo = dateDo.getDate() + '.' + (dateDo.getMonth() + 1) + '.' + dateDo.getFullYear();
    $('#datepicker').multiDatesPicker('destroy');
    $('#datepicker').multiDatesPicker({
        minDate: newDateOd,
        maxDate: newDateDo,
        onSelect: () => checkFormAgain()
    });
    $('#datepicker').multiDatesPicker('value', dates);
}
