(function ($) {
    "use strict";

    var schedule_data = $('#schedule_script');

    fsCode.modalWidth(schedule_data.data('mn'), '800px');

    $(document).ready(function () {
        $("#schedule_popup").on('click', '.custom-messages-sn > [data-sn-id]', function () {
            if ($(this).hasClass('active-sn'))
                return;

            $("#schedule_popup .custom-messages-sn > .active-sn").removeClass('active-sn');
            $(this).addClass('active-sn');

            var sn = $(this).data('sn-id');

            $("#schedule_popup .social_network_custom_texts > textarea").hide();
            $("#schedule_popup .social_network_custom_texts > [data-sn-id='" + sn + "']").fadeIn(200);
        }).on('click', '.schedule-mdl-tabs > div', function () {
            if ($(this).hasClass('active-tab'))
                return;

            $("#schedule_popup .schedule-mdl-tabs > .active-tab").removeClass('active-tab');
            $(this).addClass('active-tab');

            var activeTabId = $(this).data('tab-id');

            $("#schedule_popup [data-oppen-tab-id]:not([data-oppen-tab-id='\" + activeTabId + \"'])").slideUp(200);
            $("#schedule_popup [data-oppen-tab-id='" + activeTabId + "']").slideDown(200);

        }).on('click', '.schedule_save_btn', function () {
            var title = $("#schedule_popup .schedule_input_title").val(),
                startDate = $("#schedule_popup .schedule_input_start_date").val(),
                startTime = $("#schedule_popup .schedule_input_start_time").val(),
                interval = $("#schedule_popup .interval").val(),
                intervalType = $("#schedule_popup .interval_type").val(),
                share_time = $("#schedule_popup .share_time").val(),
                post_type_filter = $("#schedule_popup .schedule_input_post_type_filter").val(),
                dont_post_out_of_stock_products = $("#schedule_popup .schedule_dont_post_out_of_stock_products").is(':checked') ? 1 : 0,
                category_filter = $("#schedule_popup .schedule_input_category_filter").val(),
                post_ids = $("#schedule_popup .schedule_input_post_ids").val(),
                post_sort = $("#schedule_popup .post_sort").val(),
                post_date_filter = $("#schedule_popup .schedule_input_post_date_filter").val(),
                set_sleep_time = $("#schedule_popup .schedule_set_sleep_time").is(':checked') ? 1 : 0,
                sleep_time_start = set_sleep_time ? $("#schedule_popup .schedule_input_sleep_time_start").val() : '',
                sleep_time_end = set_sleep_time ? $("#schedule_popup .schedule_input_sleep_time_end").val() : '',
                custom_messages = {},
                accounts_list = [];

            if ($('#schedule_popup .schedule_matches_count').text().trim() === '0') {
                fsCode.toast($('fslang[data-id="no_posts_matched_your_filters"]').text(), 'danger');
                return false;
            }

            $("#schedule_popup .social_network_custom_texts > textarea").each(function () {
                custom_messages[$(this).data('sn-id')] = $(this).val();
            });

            $("#schedule_popup #share_box1 > .fs_share_box_node").each(function () {
                accounts_list.push($(this).find('input[name="share_on_nodes[]"]').val());
            });

            if (!schedule_data.data('keep-logs') && post_sort == 'random2') {
                fsCode.alert('You can not select "Random (no duplicates)" option. Because in your General settings "Keep shared posts log" is disabled. Please activate it firstly.');
                return false;
            }

            fsCode.ajax('schedule_save', {
                'id': schedule_data.data('id'),
                'title': title,
                'start_date': startDate,
                'start_time': startTime,
                'interval': (parseInt(interval) * parseInt(intervalType)),
                'share_time': share_time,
                'post_type_filter': post_type_filter,
                'dont_post_out_of_stock_products': dont_post_out_of_stock_products,
                'category_filter': category_filter,
                'post_ids': post_ids,
                'post_sort': post_sort,
                'post_date_filter': post_date_filter,
                'sleep_time_start': sleep_time_start,
                'sleep_time_end': sleep_time_end,
                'custom_messages': JSON.stringify(custom_messages),
                'accounts_list': JSON.stringify(accounts_list)
            }, function (result) {
                fsCode.loading(1);
                location.href = 'admin.php?page=fs-poster-schedule&view=list';
            });
        }).on('click', '.wp_native_schedule_save_btn', function () {
            var info = $(this).data('info'),
                custom_messages = {},
                accounts_list = [];

            if ($('#schedule_popup .schedule_matches_count').text().trim() === '0') {
                fsCode.toast($('fslang[data-id="no_posts_matched_your_filters"]').text(), 'danger');
                return false;
            }

            $("#schedule_popup .social_network_custom_texts > textarea").each(function () {
                custom_messages[$(this).data('sn-id')] = $(this).val();
            });

            $("#schedule_popup #share_box1 > .fs_share_box_node").each(function () {
                accounts_list.push($(this).find('input[name="share_on_nodes[]"]').val());
            });

            if (!schedule_data.data('keep-logs') && post_sort === 'random2') {
                fsCode.alert('You can not select "Random (no duplicates)" option. Because in your General settings "Keep shared posts log" is disabled. Please activate it firstly.');
                return false;
            }

            fsCode.ajax('wp_native_schedule_save', {
                'info': JSON.stringify(info),
                'custom_messages': JSON.stringify(custom_messages),
                'accounts_list': JSON.stringify(accounts_list)
            }, function (result) {});
        }).on('click', '#share_box1 .node_remove_btn', function () {
            $(this).closest('.fs_share_box_node').slideUp(200, function () {
                $(this).remove();
            });
        }).on('click', '.add_to_list_btn', function () {
            var excepts = [];
            $("#schedule_popup #share_box1 input[name='share_on_nodes[]']").each(function () {
                excepts.push($(this).val());
            });
            fsCode.loadModal('add_node_to_list', {'dont_show': excepts, 'fn_prefix': '2'});
        }).on('click', '.remove_all_from_list', function () {
            $("#schedule_popup #share_box1 > .fs_share_box_node").remove();
        }).on('click', '.sn_tabs > [data-tab-id]', function () {
            $("#schedule_popup .sn_tabs > .active-sn").removeClass('active-sn');
            $(this).addClass('active-sn');

            var tab = $(this).attr('data-tab-id');

            $("#schedule_popup #share_box1 > :not([data-tab='\"+tab+\"'])").slideUp(200);
            $("#schedule_popup #share_box1 > [data-tab='" + tab + "']").slideDown(200);
        }).on('click', '.append_to_text', function () {
            var tag = $(this).text().trim(),
                activeTab = $("#schedule_popup .custom-messages-sn > .active-sn").data('sn-id');

            $("#schedule_popup .social_network_custom_texts > textarea[data-sn-id='" + activeTab + "']").append(tag);
        }).on('change', '.schedule_set_sleep_time', function () {
            if ($(this).is(':checked')) {
                $('#schedule_popup .schedule_sleep_time_section').slideDown(200);
            } else {
                $('#schedule_popup .schedule_sleep_time_section').slideUp(200);
            }
        }).on('blur', '.schedule_input_post_ids', function () {
            if ($(this).val() == '' && !$(this).data('old-value'))
                return;

            if ($(this).val() == $(this).data('old-value'))
                return;


            $(this).data('old-value', $(this).val());

            fsRecalculatePostCount();
        }).on('change', '.schedule_input_post_type_filter', function () {
            var post_type = $(this).val();

            if (post_type == 'product') {
                $('#schedule_popup .fs_stock_option_area').slideDown(200);
            } else {
                $('#schedule_popup .fs_stock_option_area').slideUp(200);
            }
        });

        $('#schedule_popup .schedule_input_post_ids').data('old-value', $('#schedule_popup .schedule_input_post_ids').val());
        $('#schedule_popup').on('change', '.schedule_input_post_date_filter, .schedule_input_post_type_filter, .schedule_input_category_filter, .schedule_dont_post_out_of_stock_products', fsRecalculatePostCount);
        $("#schedule_popup .schedule_set_sleep_time").trigger('change');
        $('#schedule_popup .sn_tabs > [data-tab-id]:eq(0)').trigger('click');
        $('#schedule_popup .schedule_input_post_type_filter').trigger('change');

        function datePickerBoot() {
            if ('datepicker' in $.fn) {
                $("#schedule_popup .schedule_input_start_date").datepicker({
                    dateFormat: "yy-mm-dd"
                });
            } else {
                setTimeout(datePickerBoot, 1000);
            }
        }

        function fsRecalculatePostCount() {
            var post_date_filter = $('#schedule_popup .schedule_input_post_date_filter').val(),
                post_type_filter = $('#schedule_popup .schedule_input_post_type_filter').val(),
                dont_post_out_of_stock_products = $("#schedule_popup .schedule_dont_post_out_of_stock_products").is(':checked') ? 1 : 0,
                category_filter = $('#schedule_popup .schedule_input_category_filter').val(),
                post_ids = $('#schedule_popup .schedule_input_post_ids').val();

            fsCode.ajax('calcualte_post_count', {
                post_date_filter: post_date_filter,
                post_type_filter: post_type_filter,
                dont_post_out_of_stock_products: dont_post_out_of_stock_products,
                category_filter: category_filter,
                post_ids: post_ids
            }, function (result) {
                $('#schedule_popup .schedule_matches_count').text(result['count']);
            });
        }

        fsRecalculatePostCount();
        datePickerBoot();
    });

})(jQuery);

function addNodeToList2(dataId, cover, name) {
    dataId = dataId.split(':');
    var tab = dataId[0],
        nodeType = dataId[1],
        id = dataId[2];

    jQuery(".fs_share_box_items").append(
        '<div class="fs_share_box_node" data-tab="' + tab + '">' +
        '<input type="hidden" name="share_on_nodes[]" value="' + (nodeType + ':' + id) + '">' +
        '<div class="node_img"><img src="' + cover + '"></div>' +
        '<div class="node_label">' +
        '<div>' + name + '</div>' +
        '<div class="node_label_help">' + nodeType + '</div>' +
        '</div>' +
        '<div class="node_remove"><div class="node_remove_btn" type="button"><i class="fa fa-times"></i></div></div>' +
        '</div>');

    jQuery(".sn_tabs > .active-sn").click();
}
