(function ($) {
    $.fn.prepostsListen = function (options) {
        var $this = this;
        var settings = $.extend({
            message_div: $('.page-message'),
        }, options);

        $this.getApiPosts = function () {

            $.post(
                ctlppuQuery.ajaxurl,
                {
                    action: 'ctlppu_getapiposts',
                    ctlppu_nonce: ctlppuQuery.nonce

                }
            ).done(function (response) {
                if (typeof response.info !== 'undefined') {
                    jQuery(settings.message_div).showMessage('info', response.info);
                }
                if (typeof response.msg !== 'undefined') {
                 window.location.reload();
                }

                if (typeof response.error !== 'undefined') {
                    if (response.error == 'synced') {
                     window.location.reload();
                    } else {
                        jQuery(settings.message_div).showMessage('danger', response.error);
                    }
                }
            }, 'json').error(function () {
                jQuery(settings.message_div).showMessage('danger', "An error was occurred. Try again later.");
            });
        };
        return $this;
    };
})(jQuery);

jQuery(document).ready(function () {

    var progressInterval = 2000;
    jQuery('#ctlppu_preposts').prepostsListen().getApiPosts();
    setInterval(function () {
        jQuery('#ctlppu_preposts').prepostsListen().getApiPosts();
    }, progressInterval);
});
