(function($) {
    let rdgSportsPicksVs = $("body");

    rdgSportsPicksVs.on('change','#sport_picks_vs_sports_categories select',function(e) {
        let ajax_url = rdg_sports_picks_vs_var.ajaxurl;
        let sport = $(e.target).val();
        $('#sport_picks_vs_game_parts').find('option').remove();

        $.ajax({
            url: ajax_url,
            type: 'post',
            data: {
                action: 'load_sports_categories',
                sport: sport,
            },
            success: function( result ) {
                $('body').find('#sport_picks_vs_game_parts select').html(result);
            }
        });
    });

    rdgSportsPicksVs.on('click','.wp-block-acf-rdg-sports-picks-vs',function(e) {
        readyFn();
    });

    function readyFn($count = 0) {
        setTimeout(function() {
            let ajax_url = rdg_sports_picks_vs_var.ajaxurl;
            let sport = $('#sport_picks_vs_sports_categories select').val();
            let part = $('#sport_picks_vs_game_parts').attr('data-selected');

            if (typeof sport === "undefined") {
                $count++;

                if ($count < 5) {
                    readyFn($count);
                } 
            } else {
                if (typeof part === "undefined") {
                    part = null;
                }

                $.ajax({
                    url: ajax_url,
                    type: 'post',
                    data: {
                        action: 'load_sports_categories',
                        sport: sport,
                        part: part,
                    },
                    success: function( result ) {
                        $('body').find('#sport_picks_vs_game_parts select').html(result);
                    }
                });
            }
        }, 1000);
    }
}) (jQuery);
