(function($) {
    window.fpClientAdmin = {
        initStoreGroups: function(options) {
            var $inputs = $(options.inputSelector);
            if(!$inputs.length) return;

            var promise;

            if(!fpClientAdmin.stores) {
                var $loader = $('<span class="ajax-loader" data-role="ajax-loader"></span>')
                    .appendTo($(options.titleSelector));

                promise = $.ajax({
                        url: ajax_objectClient.rest_url + '/freshop/v1/content/stores',
                        dataType: 'json'
                    })
                    .done(function (resp) {
                        if (_.isArray(resp) && resp.length) {
                            var hashedStoreGroups = {},
                                storeGroups;
                            _.each(resp, function (item) {
                                _.each((item.group_id || '').split(','), function (groupId) {
                                    storeGroups = hashedStoreGroups[groupId];
                                    if(!storeGroups) storeGroups = hashedStoreGroups[groupId] = [];
                                    storeGroups.push(item);
                                });
                            });

                            fpClientAdmin.stores = resp;
                            fpClientAdmin.hashedStoreGroups = hashedStoreGroups;


                            _.each(hashedStoreGroups, function (value, key) {
                                hashedStoreGroups[key] = _.sortBy(value, function(item) {
                                    return item.post_title;
                                });
                            });
                        }
                    })
                    .always(function() {
                        $loader.remove();
                    });
            }

            $.when(promise)
                .done(function (resp) {
                    if(!_.size(fpClientAdmin.hashedStoreGroups)) return;

                    var html,
                        groupId;

                    $inputs
                        .each(function() {
                            $this = $(this);
                            groupId = $this.val();
                            if(groupId == '1000' || groupId == '2000') return;

                            html = '';
                            _.each(fpClientAdmin.hashedStoreGroups[groupId], function (item) {
                                html += '<div>' + item.post_title + '</div>';
                            });

                            if(!html) html = 'No stores found.';

                            $this.parent()
                                .append('<a href="javascript:;" class="toggle-stores" data-role="toggle-stores" data-visible-text="Hide Stores" data-hidden-text="Show Stores">Show Stores</a>')
                                .append('<div class="stores-from-group hidden" data-role="stores-from-group">' + html + '</div>');
                        });

                    $inputs.parent()
                        .off('click.storeGroup')
                        .on('click.storeGroup', '[data-role="stores-from-group"]', function(event) {
                            event.preventDefault();
                            event.stopImmediatePropagation();
                        })
                        .on('click.storeGroup', '[data-role="toggle-stores"]', function(event) {
                            event.preventDefault();
                            event.stopImmediatePropagation();

                            var $this = $(this),
                                $parent = $this.closest('.wpt-form-item, label'),
                                $storeContainer = $parent.find('[data-role="stores-from-group"]')
                                    .toggleClass('hidden');
                            $this.text($storeContainer.hasClass('hidden') ? $this.data('hidden-text') : $this.data('visible-text'));
                        });
                });
        }
    };

    $(function() {
        fpClientAdmin.initStoreGroups({
            titleSelector: '.wpt-form-item-checkboxes .title-checkboxes',
            inputSelector: '.wpt-form-item-checkboxes input[name^="wpcf[store-group]"]'
        });
    });
})(jQuery);