$(document).ready(function () {
    initFilters();
});

function initFilters() {
    $('.hcFilterForm').on('change', function (e) {
        e.preventDefault();
        sendAjaxFormRequest(this.id);
    });

    $('#btnNext').on('click', function (e) {
        $(this).off('click');
        if ($('#monthSelect')[0].selectedIndex < 11) {
            $('#monthSelect')[0].selectedIndex++;
        } else {
            if($('#yearSelect')[0].selectedIndex < 2) {
                $('#monthSelect')[0].selectedIndex = 0;
                $('#yearSelect')[0].selectedIndex++;
            }
        }
        sendAjaxFormRequest('hcFilterForm');
    });
    $('#btnPrev').on('click', function (e) {
        $(this).off('click');
        if ($('#monthSelect')[0].selectedIndex > 0) {
            $('#monthSelect')[0].selectedIndex--;
        } else {
            if($('#yearSelect')[0].selectedIndex > 0) {
                $('#monthSelect')[0].selectedIndex = 11;
                $('#yearSelect')[0].selectedIndex--;
            }
        }
        sendAjaxFormRequest('hcFilterForm');
    });
}

function sendAjaxFormRequest(formId) {
    if ($('#ajaxRequestUrl').length > 0) {
        var ajaxRequestUrl = $('#ajaxRequestUrl').data('url');
        var formData = $('#' + formId).serialize();
        ajaxRequest(ajaxRequestUrl, formData);
    }
}

//ajax request
function ajaxRequest(url, formData, successCallback) {
    jQuery.ajax({
        url: url,
        type: "POST",
        data: formData,
        dataType: "json",
        success: function (response) {
            try {
                if (successCallback !== undefined) {
                    successCallback(response);
                } else {
                    if (response.success == true) {
                        $('.tx-webx-holidaycal').html(response.data);
                        initFilters();
                    }
                }
            } catch (e) {
                console.log(1);
                console.log(e);
            }
        },
        error: function (error) {
            console.log(2);
            console.log(error);
        }
    });
}