<script type="text/javascript">
    var customerCategories = {!! \Hilco\Models\CustomerCategory::orderBy('cust_category')->pluck('cust_category')->toJson() !!};
    var billingStates = {!! \Hilco\Models\CustomerShippingAddress::orderBy('state')->distinct()->pluck('state')->toJson() !!};
    var userPersonas = [
        @foreach(\Hilco\Models\WebUserPersona::orderBy('name')->get() as $userPersona)
            {"label":"{!! $userPersona->name !!}" , "value": "{!! $userPersona->slug !!}"},
        @endforeach
    ];
    var rewardsTiers = [
        {"label":"Not Qualified" , "value": "0"},
        {"label":"Member" , "value": "1"},
        {"label":"Silver" , "value": "2"},
        {"label":"Gold" , "value": "3"},
        {"label":"Platinum" , "value": "4"},
    ];
    var viewFunctionsInit = false;

    function initViewFunctions(body, postAddCallback, preDeleteCallback, postEditCallback) {
        if (viewFunctionsInit === false) {
            viewFunctionsInit = true;
            $(body).on('click', 'a.add-dynamic-view', function () {
                var viewContainer = $(this).closest('div.view-full-container');

                //Add a new Tab
                var tabContainer = viewContainer.find('ul.visibility-controls').first();
                var altViewTabs = tabContainer.find('.alt-view');
                if (altViewTabs.length > 0) {
                    lastAltViewTab = altViewTabs.last();
                    var newAltViewId = parseInt(lastAltViewTab.attr('data-view-id')) + 1;
                } else {
                    var newAltViewId = 1;
                }
                var newAltViewTab = '<li role="presentation"><a class="change-dynamic-view alt-view" title="@lang('hilco::app.target_customers_colon') None" href="#" data-view-id="' + newAltViewId + '">@lang('hilco::app.alternate') ' + newAltViewId + '</a></li>';
                var addListItem = tabContainer.find('li.add-dynamic-view-parent').first();
                //gotta remove the a tag's parent li and re-add it at the end to keep the options pretty
                addListItem.remove();
                tabContainer.append(newAltViewTab);
                tabContainer.append(addListItem);

                //Add a new view

                var templateView = viewContainer.find('div.view-container.default').first();

                var newView = templateView.clone();
                newView.attr('data-view-id', newAltViewId);
                newView.removeClass('default');
                newView.removeClass('visible');
                newView.addClass('alternate');
                newView.addClass('hidden');

                var deleteButton = newView.find('.delete-view-button').first();
                deleteButton.removeClass('delete-view-button');
                deleteButton.removeClass('hidden');
                deleteButton.addClass('delete-alternate-button');
                deleteButton.attr('title', "@lang('hilco::app.delete_alternate_description')");
                deleteButton.html("@lang('hilco::app.delete_alternate')");

                var visibilitySpan = newView.find('.visibility-options').first();
                visibilitySpan.attr('title', '@lang('hilco::app.target_customers_description')');
                visibilitySpan.html("@lang('hilco::app.target_customers_colon')");

                var visibilityAnchor = newView.find('.view-defaultvisibility').first();
                visibilityAnchor.removeClass('view-defaultvisibility');
                visibilityAnchor.addClass('view-targetcustomers');
                visibilityAnchor.html("None");

                viewContainer.append(newView);
                if (postAddCallback !== undefined){
                    postAddCallback(newView);
                }
            });

            $(body).on('click', 'a.change-dynamic-view', function () {
                var viewContainer = $(this).closest('div.view-full-container');

                //change active tab
                var tabContainer = viewContainer.find('ul.visibility-controls').first();
                var currentTab = tabContainer.find('li.active').first();
                var newTab = $(this).closest('li');
                currentTab.removeClass('active');
                newTab.addClass('active');

                //change visible view
                var currentView = viewContainer.find('div.visible').first();
                var newView = viewContainer.find('div.view-container[data-view-id="' + $(this).attr('data-view-id') + '"]').first();

                currentView.removeClass('visible');
                currentView.addClass('hidden');
                newView.removeClass('hidden');
                newView.addClass('visible');
            });

            $(body).on('click', 'a.delete-alternate-button', function () {
                var viewContainer = $(this).closest('div.view-full-container');

                //remove tab
                var tabContainer = viewContainer.find('ul.visibility-controls').first();
                tabContainer.find('li.active').first().remove();

                //change tab back to default
                tabContainer.find('a.default-view').first().closest('li').addClass('active');

                //remove view
                var view = $(this).closest('.view-container');
                if (preDeleteCallback !== undefined){
                    preDeleteCallback(view);
                }
                var viewId = parseInt(view.attr('data-view-id'));
                $(view).remove();

                //change view back to default
                var newView = viewContainer.find('div.view-container.default').first();
                newView.removeClass('hidden');
                newView.addClass('visible');

                //reduce the index of all subsequent alt-view views
                viewContainer.find('div.view-container.alternate').each(function () {
                    var altViewId = parseInt($(this).attr('data-view-id'));
                    if (altViewId > viewId) {
                        altViewId--;
                        $(this).attr('data-view-id', altViewId);
                    }
                });
                //reduce the index of all subsequent alt-view tabs
                tabContainer.find('a.alt-view').each(function () {
                    var altViewId = parseInt($(this).attr('data-view-id'));
                    if (altViewId > viewId) {
                        altViewId--;
                        $(this).html('@lang('hilco::app.alternate') ' + altViewId);
                        $(this).attr('data-view-id', altViewId);
                    }
                });
            });
            $(body).on('click', '.view-targetcustomers', function () {
                var view = $(this).closest('.view-container');

                var targetCustomers = {};
                try {
                    targetCustomers = JSON.parse($(view).attr('data-target-customers'));
                } catch (e) {
                    //not valid json, use the default empty arrays
                }
                if (!targetCustomers.hasOwnProperty('allUsers')){
                    targetCustomers.allUsers = 0;
                }
                if (!targetCustomers.hasOwnProperty('customerCategories')){
                    targetCustomers.customerCategories = [];
                }
                if (!targetCustomers.hasOwnProperty('billingState')){
                    targetCustomers.billingState = [];
                }
                if (!targetCustomers.hasOwnProperty('userPersonas')){
                    targetCustomers.userPersonas = [];
                }
                if (!targetCustomers.hasOwnProperty('rewardsTiers')){
                    targetCustomers.rewardsTiers = [];
                }
                if (!targetCustomers.hasOwnProperty('productsInCart')){
                    targetCustomers.productsInCart = [];
                }
                if (!targetCustomers.hasOwnProperty('productsInHistory')){
                    targetCustomers.productsInHistory = [];
                }

                var targetCustomersEditor = new $.fn.dataTable.Editor({
                    title: 'Target Customers',
                    fields: [
                        {
                            label: 'Users',
                            name: 'allUsers',
                            type: 'radio',
                            options: [
                                { label: "Any Logged In User", value: 1 },
                                { label: "Any of the Following", value: 0 }
                            ],
                            def: targetCustomers.allUsers
                        },
                        {
                            label: 'Customer Categories',
                            name: 'customerCategories',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            options: customerCategories,
                            def: targetCustomers.customerCategories,
                        },
                        {
                            label: 'Customer State',
                            name: 'billingState',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            options: billingStates,
                            def: targetCustomers.billingState,
                        },
                        {
                            label: 'Rewards Tiers',
                            name: 'rewardsTiers',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            options: rewardsTiers,
                            def: targetCustomers.rewardsTiers,
                        },
                        {
                            label: 'User Personas',
                            name: 'userPersonas',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            options: userPersonas,
                            def: targetCustomers.userPersonas,
                        },
                        {
                            label: 'Products in Cart',
                            name: 'productsInCart',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            opts: {
                                ajax: {
                                    url: '{{ route('promotion.productsearch') }}',
                                    height: 35,
                                    dataType: 'json',
                                    method: 'GET',
                                    delay: 250,
                                    cache: true,
                                    data: function (params) {
                                        return {
                                            _token: _csrf_token,
                                            query: params.term,
                                            page: params.page || 0,
                                        };
                                    },
                                    processResults: function (data) {
                                        var index = 0;
                                        for (index = 0; index < data.items.length; index++){
                                            data.items[index].id = JSON.stringify({
                                                id:data.items[index].id,
                                                name:data.items[index].name,
                                                slug:data.items[index].slug,
                                                table_type:data.items[index].table_type
                                            });
                                        };
                                        return {
                                            results:data.items,
                                            pagination: data.pagination,
                                        };
                                    }
                                },
                                minimumInputLength: 2,
                                escapeMarkup: function (markup) {
                                    return markup;
                                },
                                templateResult: function (item) {
                                    return formatProductSearchResult(item);
                                },
                                templateSelection: function (item) {
                                    return formatProductSearchResult(item);
                                },
                            },
                        },
                        {
                            label: 'Products in History',
                            name: 'productsInHistory',
                            type: 'select2',
                            multiple: true,
                            attr: {
                                multiple: 'multiple'
                            },
                            opts: {
                                ajax: {
                                    url: '{{ route('promotion.productsearch') }}',
                                    height: 35,
                                    dataType: 'json',
                                    method: 'GET',
                                    delay: 250,
                                    cache: true,
                                    data: function (params) {
                                        return {
                                            _token: _csrf_token,
                                            query: params.term,
                                            page: params.page || 0,
                                        };
                                    },
                                    processResults: function (data) {
                                        var index = 0;
                                        for (index = 0; index < data.items.length; index++){
                                            data.items[index].id = JSON.stringify({
                                                id:data.items[index].id,
                                                name:data.items[index].name,
                                                slug:data.items[index].slug,
                                                table_type:data.items[index].table_type
                                            });
                                        };
                                        return {
                                            results:data.items,
                                            pagination: data.pagination,
                                        };
                                    }
                                },
                                minimumInputLength: 2,
                                escapeMarkup: function (markup) {
                                    return markup;
                                },
                                templateResult: function (item) {
                                    return formatProductSearchResult(item);
                                },
                                templateSelection: function (item) {
                                    return formatProductSearchResult(item);
                                },
                            },
                        },
                    ]
                }).title('@lang('hilco::app.target_customers')').buttons({
                    label: "@lang('hilco::app.save')",
                    fn: function () {
                        this.submit(null, null, function (data) {
                            var targetCustomersFormatted = '';
                            var productsInCartFormatted = '';
                            var productsInHistoryFormatted = '';
                            var delim = '';
                            var delimInCart = 'Product In Cart: ';
                            var delimInHistory = 'Product In History: ';
                            var targetCustomers = {}
                            $.each(data.data.key, function (dataType, values) {
                                if ($.isArray(values)){
                                    targetCustomers[dataType] = [];
                                    $.each(values, function (index, value) {
                                        if (dataType === 'productsInCart'){
                                            var product = JSON.parse(value);

                                            if (product.hasOwnProperty('id') && product.hasOwnProperty('name') && product.hasOwnProperty('slug') && product.hasOwnProperty('table_type')){
                                                productsInCartFormatted += delimInCart + formatProductNameText(product.name, product.slug, product.table_type);
                                                delimInCart = ', ';
                                                targetCustomers[dataType].push(product);
                                            }
                                        } else if (dataType === 'productsInHistory'){
                                            var product = JSON.parse(value);

                                            if (product.hasOwnProperty('id') && product.hasOwnProperty('name') && product.hasOwnProperty('slug') && product.hasOwnProperty('table_type')){
                                                productsInHistoryFormatted += delimInHistory + formatProductNameText(product.name, product.slug, product.table_type);
                                                delimInHistory = ', ';
                                                targetCustomers[dataType].push(product);
                                            }
                                        } else if (dataType === 'userPersonas'){
                                            if (value !== '') {
                                                var labelValue = value;
                                                $.each(userPersonas, function (index, row){
                                                    if (row.value === value){
                                                        labelValue = row.label;
                                                    }
                                                })
                                                targetCustomersFormatted += delim + labelValue;
                                                delim = ', ';
                                                targetCustomers[dataType].push(value);
                                            }
                                        } else if (dataType === 'rewardsTiers'){
                                            if (value !== '') {
                                                var labelValue = value;
                                                $.each(rewardsTiers, function (index, row){
                                                    if (row.value === value){
                                                        labelValue = row.label;
                                                    }
                                                })
                                                targetCustomersFormatted += delim + labelValue;
                                                delim = ', ';
                                                targetCustomers[dataType].push(value);
                                            }
                                        }else{
                                            if (value !== '') {
                                                targetCustomersFormatted += delim + value;
                                                delim = ', ';
                                                targetCustomers[dataType].push(value);
                                            }
                                        }
                                    });
                                } else {
                                    targetCustomers[dataType] = values;
                                }
                            });

                            if (targetCustomersFormatted === '') {
                                if (productsInCartFormatted === '' && productsInHistoryFormatted === ''){
                                    targetCustomersFormatted = 'None';
                                }else{
                                    targetCustomersFormatted = 'Any customer with:';
                                }
                            }

                            if (productsInCartFormatted !== ''){
                                targetCustomersFormatted += ", " + productsInCartFormatted;
                            }
                            if (productsInHistoryFormatted !== ''){
                                targetCustomersFormatted += ", " + productsInHistoryFormatted;
                            }

                            if (targetCustomers['allUsers'] === 1){
                                targetCustomersFormatted = 'Any Logged In User';
                            }

                            var targetCustomersJson = JSON.stringify(targetCustomers);
                            $(view).attr('data-target-customers', targetCustomersJson);
                            $(view).find('.view-targetcustomers').first().text(targetCustomersFormatted);
                            $(view).closest('.view-full-container').find('.visibility-controls').first().find('a.change-dynamic-view[data-view-id="' + $(view).attr('data-view-id') + '"]').first().attr('title', "@lang('hilco::app.target_customers_colon') " + targetCustomersFormatted);

                            if (postEditCallback !== undefined){
                                postEditCallback(view);
                            }
                        });
                    }
                });

                //editor requires a key in the data.data object to notate what we're looking for, just using 'key' as a placeholder
                targetCustomersEditor.on( 'open', function ( e, type ) {
                    $.each(targetCustomers.productsInCart, function (index, product){
                        var newOption = new Option(formatProductSearchResult(product), JSON.stringify(product), true, true);
                        $('select#DTE_Field_productsInCart').append(newOption).trigger('change');
                    });
                    $.each(targetCustomers.productsInHistory, function (index, product){
                        var newOption = new Option(formatProductSearchResult(product), JSON.stringify(product), true, true);
                        $('select#DTE_Field_productsInHistory').append(newOption).trigger('change');
                    });
                } );
                targetCustomersEditor.edit('key');
            });
            $(body).on('click', '.view-defaultvisibility', function () {
                var view = $(this).closest('.view-container');

                defaultvisibility = $(view).attr('data-default-visibility').trim();
                if (defaultvisibility !== 'Hidden') {
                    defaultvisibility = 'Visible';
                }

                var defaultVisibilityEditor = new $.fn.dataTable.Editor({
                    title: 'Default Visibility',
                    fields: [
                        {
                            label: 'Default Visibility',
                            name: 'defaultVisibility',
                            type: 'select',
                            options: ['Visible', 'Hidden'],
                            def: defaultvisibility,
                        }
                    ]
                }).title('@lang('hilco::app.default_visibility')').buttons({
                    label: "@lang('hilco::app.save')",
                    fn: function () {
                        this.submit(null, null, function (data) {
                            var defaultVisibility = data.data.key.defaultVisibility;

                            $(view).attr('data-default-visibility', defaultVisibility);
                            $(view).find('.view-defaultvisibility').first().text(defaultVisibility);

                            if (postEditCallback !== undefined){
                                postEditCallback(view);
                            }
                        });
                    }
                });

                //editor requires a key in the data.data object to notate what we're looking for, just using 'key' as a placeholder
                defaultVisibilityEditor.edit('key');
            });
            $(body).on('click', '.view-visibledates', function () {
                var view = $(this).closest('.view-container');

                var visibleDates = {startDate: '', endDate: ''};
                try {
                    visibleDates = JSON.parse($(view).attr('data-visible-dates'));
                } catch (e) {
                    //not valid json, use the default empty arrays
                }

                var defaultVisibilityEditor = new $.fn.dataTable.Editor({
                    title: 'Default Visibility',
                    fields: [
                        {
                            label: 'Start Date',
                            name: 'startDate',
                            type: 'date',
                            def: visibleDates.startDate,
                        },
                        {
                            label: 'End Date',
                            name: 'endDate',
                            type: 'date',
                            def: visibleDates.endDate,
                        }
                    ]
                }).title('@lang('hilco::app.visible_dates')').buttons({
                    label: "@lang('hilco::app.save')",
                    fn: function () {
                        this.submit(null, null, function (data) {
                            var visibleDates = data.data.visibleDates;
                            var visibleDatesJson = JSON.stringify(visibleDates);
                            var visibleDatesFormatted = '';
                            if (visibleDates.startDate !== '' && visibleDates.endDate !== ''){
                                visibleDatesFormatted = 'From '+visibleDates.startDate+' until '+visibleDates.endDate;
                            } else if (visibleDates.startDate !== ''){
                                visibleDatesFormatted = 'From '+visibleDates.startDate;
                            } else if (visibleDates.endDate !== ''){
                                visibleDatesFormatted = 'Until '+visibleDates.endDate;
                            } else {
                                visibleDatesFormatted = 'All';
                            }

                            $(view).attr('data-visible-dates', visibleDatesJson);
                            $(view).find('.view-visibledates').first().text(visibleDatesFormatted);

                            if (postEditCallback !== undefined){
                                postEditCallback(view);
                            }
                        });
                    }
                });

                //editor requires a key in the data.data object to notate what we're looking for, just using 'key' as a placeholder
                defaultVisibilityEditor.edit('visibleDates');
            });
        }
    }

    function formatProductSearchResult(data, type = null) {
        if (data.name) {
            if (type) {
                return formatProductName(data.name, data.slug, type);
            } else {
                return formatProductName(data.name, data.slug, data.table_type);
            }
        }
        return data.text;
    }

    function formatProductNameText(name, slug, type) {
        switch (type) {
            case 'webGroup':
                return name + ' (' + slug + ') ' + ' (Group)';
            case 'webCategory':
                return name + ' (' + slug + ') ' + ' (Category)';
            case 'webCollection':
                return name + ' (' + slug + ') ' + ' (Collection)';
            case 'webFamily':
                return name + ' (' + slug + ') ' + ' (Family)';
            case 'webPart':
                return name + ' (' + slug + ') ' + ' (Part)';
            case 'webAttribute':
                return name + ' (Attribute)';
        }
    }

    function formatProductName(name, slug, type) {
        switch (type) {
            case 'webGroup':
                return '<span class="text-primary"><i class="fa fa-vs-group fa-fw"></i> ' + name + ' (' + slug + ') ' + ' <i>(Group)</i></span>';
            case 'webCategory':
                return '<span class="text-info"><i class="fa fa-vs-category fa-fw"></i> ' + name + ' (' + slug + ') ' + ' <i>(Category)</i></span>';
            case 'webCollection':
                return '<span class="text-success"><i class="fa fa-vs-collection fa-fw"></i> ' + name + ' (' + slug + ') ' + ' <i>(Collection)</i></span>';
            case 'webFamily':
                return '<span class="text-warning"><i class="fa fa-vs-family fa-fw"></i> ' + name + ' (' + slug + ') ' + ' <i>(Family)</i></span>';
            case 'webPart':
                return '<span class="text-danger"><i class="fa fa-vs-part fa-fw"></i> ' + name + ' (' + slug + ') ' + ' <i>(Part)</i></span>';
            case 'webAttribute':
                return '<span class="text"><i class="fa fa-vs-attribute fa-fw"></i> ' + name + ' <i>(Attribute)</i></span>';
        }
    }
</script>