(function()
{
    'use strict';

    var page = jQuery(document);

    var get_background_image_url = function( element )
    {
        if (!element.is('[data-has-background-image]'))
        {
            return null;
        }

        var data_attributes = [
            // look for layout-specific image first
            'background-' + page.data('layout'),

            // then look for general image
            'background-image',

            // and then fall back to full, if present
            // (e.g., separate full and compact images intended,
            // but only full version is uploaded)
            'background-full'
        ];

        var url;
        for (var i = 0; i < data_attributes.length; i++)
        {
            url = element.data( data_attributes[i] );
            if (url)
            {
                return url;
            }
        }

        return null;
    };

    page.on('contentloaded', function(event)
    {
        var block = jQuery(event.target);
        var blocks = block.find('[data-has-background-image]');

        blocks.on('background:reset', function()
        {
            var block = jQuery(this);

            block.attr('style', function(i, style)
            {
                if (style)
                {
                    return style.replace(/background-image[^;]+;?/g, '');
                }

                return null;
            });
        });

        blocks.on('background:update', function()
        {
            var block = jQuery(this);
            var url = get_background_image_url( block );
            var value = (url) ? 'url("' + url + '")' : 'none';

            block.trigger('background:reset');

            var external_value = block.css('background-image');
            if (external_value !== 'none')
            {
                value = external_value + ', ' + value;
            }

            block.css('background-image', value);

            if (url)
            {
                block.attr('data-background-image-set', 1);
            }
            else
            {
                block.removeAttr('data-background-image-set');
            }

            // workaround for ie11 to trigger multiple background block redraw
            if (external_value && jQuery('html').is('.ie'))
            {
                block.hide().show();
            }
        });

        blocks.on('background:load', function()
        {
            var block = jQuery(this);
            block.removeAttr('data-background-lazy').trigger('background:update');
        });

        page.on('resizeend', function()
        {
            blocks.not('[data-background-lazy]').trigger('background:update');
        });

        blocks.not('[data-background-lazy]').trigger('background:update');
    });

}());
