@if($edit)
    <div class="mceNonEditable component-container" data-component-key="improvedPromoTiles">
        <a href="#" class="btn btn-danger pull-right delete-component">X</a>
        <h4>@lang('hilco::app.promo_tiles')</h4>
        <div class="view-full-container">
            @include('hilco::components.targetCustomer.viewSelector', ['alternateViews' => $alternateViews ?? []])
            @include('hilco::components.improvedPromoTilesView',
            [
                'viewId' => 0,
                'tiles' => $tiles,
                'selectedLayout' => $selectedLayout,
                'displayName' => $displayName,
                'defaultVisibility' => $defaultVisibility ?? 'Visible',
                'visibleDates' => $visibleDates ?? [],
                'visibleDatesFormatted' => $visibleDatesFormatted ?? 'All',
                'default' => true
            ])
            @foreach($alternateViews ?? [] as $altViewId => $altView)
                @include('hilco::components.improvedPromoTilesView',
                [
                'viewId' => $altViewId,
                    'tiles' => Arr::get($altView, 'tiles', []),
                    'selectedLayout' => Arr::get($altView, 'selectedLayout', ''),
                    'displayName' => Arr::get($altView, 'displayName', ''),
                    'targetCustomers' => Arr::get($altView, 'targetCustomers', []),
                    'targetCustomersFormatted' => Arr::get($altView, 'targetCustomersFormatted', 'None'),
                    'visibleDates' => Arr::get($altView, 'visibleDates', []),
                    'visibleDatesFormatted' => Arr::get($altView, 'visibleDatesFormatted', 'All'),
                    'default' => false
                ])
            @endforeach
        </div>
    </div>
@endif

@if($script)
<script type="text/javascript">
registerComponent('improvedPromoTiles', {
    menuText: '@lang('hilco::app.promo_tiles')',
    bladeTemplate: 'hilco::components.improvedPromoTiles',
    init: function (body) {
        initViewFunctions(body);
        var layouts = {
            full:{
                display_name : '100%',
                total_tiles : 1,
                tile_size_values :[12]
            },
            halves:{
                display_name : '50% | 50%',
                total_tiles : 2,
                tile_size_values :[6, 6]
            },
            thirds: {
                display_name : '33% | 33% | 33%',
                total_tiles : 3,
                tile_size_values: [4, 4, 4]
            },
            oneAndTwo: {
                display_name : '33% | 66%',
                total_tiles : 2,
                tile_size_values: [4, 8]
            },
            twoAndOne: {
                display_name : '66% | 33%',
                total_tiles : 2,
                tile_size_values: [8, 4]
            }
        };

        $(body).on('click', '.improved-tile-thumbnail', function () {
            var tile = $(this).closest('.tile-container');
            assets.finder({
                successFunction: function (data) {
                    $(tile).attr('data-web-asset-id', data.id).find('img').attr('src', data.url).attr('alt', alt);
                    var img = new Image();
                    img.addEventListener("load", function(){
                        $(tile).attr('data-web-asset-id', data.id).find('.image-size').attr('data-img-height', this.naturalHeight);
                        $(tile).attr('data-web-asset-id', data.id).find('.image-size').attr('data-img-width', this.naturalWidth);
                        $(tile).attr('data-web-asset-id', data.id).find('.image-size').html("Height: "+this.naturalHeight +"px Width: "+ this.naturalWidth +"px");
                    });
                    img.src = data.url;

                    var alt;
                    if(data.alttag != null && data.alttag != ""){
                        alt = data.alttag;
                    }else if(data.name != null && data.name != ""){
                        alt = data.name;
                    }else{
                        alt = 'None'
                    }

                    if(alt != 'None') {
                        $(tile).attr('data-img-alttag', alt);
                    }
                    $(tile).attr('data-web-asset-id', data.id).find('.improved-tile-alttag').text(alt);
                }
            });

        });
        $(body).on('click', '.improved-tile-link', function () {
            var tile = $(this).closest('.tile-container');
            assets.link({
                successFunction: function (data) {
                    $(tile).attr('data-link-type', data.link_type);
                    $(tile).attr('data-link-target', data.target);
                    $(tile).find('.improved-tile-link').text(data.description);
                }
            });
        }).on('click', '.improved-tile-alttag', function () {
            var tile = $(this).closest('.tile-container');
            assets.description({
                successFunction: function (data) {
                    if(data.alttag != null && data.alttag != ""){
                        $(tile).attr('data-img-alttag', data.alttag);
                        $(tile).find('.improved-tile-alttag').text(data.alttag);
                        $(tile).find('img').attr('alt', data.alttag);
                    }
                }
            });
        }).on('click', '#changeLayout', function () {
            var mainComponent = $(this).closest('.view-container');

            var message = "Choose a layout for the content.";
            var layout = $(mainComponent).find('h4.current-layout').attr('data-current-layout');

            swal({
                title: "Change Layout",
                type: "info",
                html: message,
                input: 'select',
                inputOptions: {
                    full: '100%',
                    halves: '50% | 50%',
                    thirds:'33% | 33% | 33%',
                    oneAndTwo: '33% | 66%',
                    twoAndOne:'66% | 33%'
                },
                inputPlaceholder: 'Select a layout',
                inputValue: layout,
                confirmButtonClass: "btn-primary",
                showCancelButton: true,
                allowOutsideClick: false,
            }).then(
                function(inputValue){
                    var current_layout = layouts[layout];
                    var chosen_layout = layouts[inputValue];
                    if(current_layout != chosen_layout){

                        $(mainComponent).find('h4.current-layout').attr('data-current-layout', inputValue);
                        $(mainComponent).find('h4.current-layout').attr('data-display-name', layouts[inputValue]['display_name']);
                        $(mainComponent).find('h4.current-layout').html('Current Layout: '+ layouts[inputValue]['display_name']);

                        //change the tiles and assign the size
                        if(current_layout['total_tiles'] > chosen_layout['total_tiles']){
                            var tilesToRemove = current_layout['total_tiles'] - chosen_layout['total_tiles'];
                            for (let step = 0; step < tilesToRemove; step++) {
                                var lastTile = $(mainComponent).find('div.tile-container').last();
                                $(lastTile).remove();
                            }
                        }else if(current_layout['total_tiles'] < chosen_layout['total_tiles']){
                            var tilesToAdd = chosen_layout['total_tiles'] - current_layout['total_tiles'];
                            for (let step = 0; step < tilesToAdd; step++) {
                                var lastTile = $(mainComponent).find('div.tile-container').last();
                                var newTileId = lastTile.data('tile-id') + 1;
                                var newTile = lastTile.clone().attr('data-tile-id', newTileId);
                                newTile.find('[data-tile-id]').each(function () {
                                    $(this).attr('data-tile-id', newTileId);
                                }).find('img').attr('src', '');
                                $(mainComponent).find('.tiles-container').append(newTile);
                            }
                        }

                        var loops = 0;

                        $(mainComponent).find('.tile-container').each(function () {

                            var tileSize = chosen_layout['tile_size_values'][loops];
                            $(this).attr('data-tile-size', tileSize);
                            loops++;
                        });
                    }
                });
        });
    },
    serialize: function (componentNode) {
        var viewDiv = $(componentNode).find('div.view-container.default');
        var alternateViews = {};
        viewDiv.closest('.view-full-container').find('.view-container.alternate').each(function () {
            var selectedLayout = $(this).find('h4.current-layout').data('current-layout');
            var displayName = $(this).find('h4.current-layout').data('display-name');
            var targetCustomers = {};
            try{
                targetCustomers = JSON.parse($(this).attr('data-target-customers'));
            }catch (e){
                //use the empty object
            }
            var visibleDates = {};
            try{
                visibleDates = JSON.parse($(this).attr('data-visible-dates'));
            }catch (e){
                //use the empty object
            }

            var altViewData = {
                selectedLayout: selectedLayout,
                displayName: displayName,
                targetCustomers: targetCustomers,
                targetCustomersFormatted: $(this).find('.view-targetcustomers').text(),
                visibleDates: visibleDates,
                visibleDatesFormatted: $(this).find('.view-visibledates').text(),
                tiles: {},
            };
            $(this).find('.tile-container').each(function () {
                var tileId = $(this).data('tile-id');

                altViewData.tiles[tileId] = {
                    webAssetId: $(this).data('web-asset-id'),
                    tileSize: $(this).data('tile-size'),
                    height: $(this).find('.image-size').data('img-height'),
                    width: $(this).find('.image-size').data('img-width'),
                    alttag: $(this).data('img-alttag'),
                    link: {
                        type: $(this).data('link-type'),
                        target: $(this).data('link-target'),
                    },
                };
            });
            alternateViews[$(this).attr('data-view-id')] = altViewData;
        });

        var selectedLayout = viewDiv.find('h4.current-layout').data('current-layout');
        var displayName = viewDiv.find('h4.current-layout').data('display-name');
        var visibleDates = {};
        try{
            visibleDates = JSON.parse(viewDiv.attr('data-visible-dates'));
        }catch (e){
            //use the empty object
        }

        var data = {
            selectedLayout: selectedLayout,
            displayName: displayName,
            tiles: {},
            defaultVisibility: viewDiv.attr('data-default-visibility').trim(),
            visibleDates: visibleDates,
            visibleDatesFormatted: viewDiv.find('.view-visibledates').text(),
            alternateViews: alternateViews
        };
        $(viewDiv).find('.tile-container').each(function () {
            var tileId = $(this).data('tile-id');

            data.tiles[tileId] = {
                webAssetId: $(this).data('web-asset-id'),
                tileSize: $(this).data('tile-size'),
                height: $(this).find('.image-size').data('img-height'),
                width: $(this).find('.image-size').data('img-width'),
                alttag: $(this).data('img-alttag'),
                link: {
                    type: $(this).data('link-type'),
                    target: $(this).data('link-target'),
                },
            };
        });
        return data;
    },
});
</script>
@endif

@if($view)
    @include('hilco::components.targetCustomer.viewRenderer',
['blade' => 'hilco::components.improvedPromoTilesView',
'bladeViewArgs' =>
    ['tiles' => $tiles,
    'selectedLayout' => $selectedLayout,
    'displayName' => $displayName,
    'defaultVisibility' => $defaultVisibility ?? 'Visible',
    'alternateViews' => $alternateViews?? []],
'mode' => 'view'])
@endif