<category-management>
    <div class="row">
        <div class="col-md-3">
            <category-selector></category-selector>
            <hr>
            <p><i>Select a category to edit the products in it.</i></p>
            <p>
                <i>To edit a category name or parent hover over the category then click the edit (<i class="glyphicon glyphicon-pencil"></i>)
                    button.</i>
            </p>
        </div>
        <div class="col-md-9">
            <category-product-form></category-product-form>
        </div>
    </div>
</category-management>

<category-selector>
    <!-- Do not show the category (ON CATALOG PAGE!) before we have an office because
    we need the category_office_properties hidden value -->
    <div class="category-container" show="{ opts.mode != 'catalog' || (IFC.state.office && IFC.state.office.id != '') }">
        <!-- Regular list of categories -->
        <category each="{ categories }" depth="0" mode="{ this.parent.opts.mode }"></category>

        <!-- Special category for collection -->
        <div class="category-wrapper {selected: on_collections_page }" show="{ opts.mode == 'catalog' }">
            <div class="category-name">
                <span class="title" onclick="{ go_to_collections }">Collections</span>
            </div>
        </div>
    </div>

    <hr class="visible-sm">

    <script>
        var self = this;

        self.has_loaded_categories = false;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("mount", function () {
            self.update_categories();

            if (get_url_params().collections == '1') {
                self.on_collections_page = true;
            }

        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.update_categories = function () {
            var filters = {};
            if (self.opts.mode == 'catalog') {
                filters.offer = IFC.state.office && IFC.state.office.offer ? IFC.state.office.offer : undefined;
            }

            IFC.api.get_categories(filters)
                .success(function (categories) {
                    var categories_expanded = [];
                    var selected_category = undefined;
                    var is_on_collections = get_url_params().collections == '1';
                    var category_id_from_url = get_url_params().category;

                    // First we save our CURRENT expanded tree views
                    map_categories(self.categories, function (category) {
                        if (category.expanded) {
                            categories_expanded.push(category.id);
                        }
                        if (category.selected) {
                            selected_category = category.id;
                        }
                    });

                    // Check if they have product
                    var check_has_product = function(category) {
                        if (!category.has_product) {
                            category.children.forEach(function (child_category) {
                                // ... also check children's children
                                check_has_product(child_category)
                                if (child_category.has_product) {
                                    category.has_product = true;
                                }
                            });
                        }
                    };
                    categories.forEach(check_has_product);

                    // Iterate over received categories, check if we need to preselect one
                    if (!selected_category && self.opts.auto_select && category_id_from_url && !self.has_loaded_categories && !is_on_collections) {
                        map_categories(categories, function (category) {
                            if (category.id == category_id_from_url) {
                                // We found category in URL, set all parents to be expanded
                                var set_parents_expanded = function(to_expand) {
                                    if(to_expand.parent) {
                                        map_categories(categories, function(category_to_check) {
                                            if(to_expand.parent == category_to_check.id) {
                                                categories_expanded.push(category_to_check.id);
                                                // Also go up the chain and set any other parents to be expanded
                                                set_parents_expanded(category_to_check);
                                            }
                                        })
                                    }
                                };

                                set_parents_expanded(category);

                                selected_category = category.id;
                                IFC.events.trigger('category_selected', category);
                            }
                        });
                    }

                    // If we're in autoselect mode and have nothing selected, auto select one
                    if (!selected_category && !is_on_collections && self.opts.auto_select && category_id_from_url == undefined && categories.length > 0) {
                        // Find one with has_product = True
                        for(var i=0; i<categories.length; i++) {
                            if(categories[i].has_product) {
                                selected_category = categories[i].id;
                                IFC.events.trigger('category_selected', categories[i]);
                                break;
                            }
                        }
                    }

                    // Then apply expands to new category list
                    map_categories(categories, function (category) {
                        // Modify our new list to be properly hidden/shown, otherwise
                        // we'll be reset to default unexpanded state
                        category.expanded = categories_expanded.indexOf(category.id) != -1;
                        category.selected = selected_category == category.id;

                        // Have to rename parent... it's a RiotJS keyword so we cant use it... ugh
                        category.parent_id = category.parent;
                        delete category.parent;
                    });

                    // Hide any categories without product, also check children
                    /*map_categories(categories, function(category) {
                     // Check our children and our children's children
                     var check_if_children_have_product = function(child_category) {
                     if(!child_category.has_product) {
                     // We don't have product in this immediate category, check children
                     child_category.children.forEach(function (child_category) {
                     if (child_category.has_product) {
                     child_category.has_product.has_product = true;
                     }
                     });
                     }

                     return child_category.has_product;
                     };
                     category.children.forEach(function(child_category) {
                     if(!child_category.has_product) {
                     category.has_product = check_if_children_have_product(child_category);
                     }
                     });
                     });*/

                    self.update({
                        has_loaded_categories: true,
                        categories: categories
                    });
                    IFC.events.trigger('categories_received', categories);
                })
                .error(function () {
                    toastr.error("Error fetching categories");
                });
        };

        self.go_to_collections = function () {
            if (self.opts.forward_on_select) {
                window.location.href = URL.pages.products + '?collections=1';
            } else {
                replace_state({collections: 1});
            }

            // Load collections and unselect current category
            IFC.events.trigger('go_to_collections');
            IFC.events.trigger('category_unselected');

            self.update({on_collections_page: true});
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('force_category_list_update', self.update_categories);
        IFC.events.on('office_selected', self.update_categories);
        IFC.events.on('category_selected', function (category) {
            self.selected_category = category;
            // go to thumbnails page with this category and office selected
            if (self.opts.forward_on_select) {
                var office_param = IFC.state.office && IFC.state.office.id != '' ? 'office=' + IFC.state.office.id + '&' : '';
                var category_param = 'category=' + category.id;
                window.location.href = URL.pages.products + '?' + office_param + category_param;
            }
            self.update({on_collections_page: false});
        });
        /*IFC.events.on('auto_select_category', function () {
            self.opts.auto_select = true;
            self.update_categories();
        });*/
    </script>
    <style scoped>

    </style>
</category-selector>

<!-- If the category is set to hidden then do not how unless admin then show it grayed -->
<category>
    <div class="category-super-wrapper" show="{ has_product || parent.opts.mode != 'catalog' }">
        <div class="category-wrapper { selected: selected }" show="{ !hidden || IFC.is_admin() }">
            <div class="category-name" show="{ !show_rename_form }">
                <virtual show="{ children.length > 0}">
                    <i class="glyphicon glyphicon-chevron-right" show="{ !expanded }" onclick="{ toggle_expand_view }"></i>
                    <i class="glyphicon glyphicon-chevron-down" show="{ expanded }" onclick="{ toggle_expand_view }"></i>
                </virtual>
                <!--<i class="glyphicon glyphicon-minus" show="{ children.length == 0 }"></i>-->
                <span class="left-side-spacer" show="{ children.length == 0 }"></span>

                <span class="title { ishidden : hidden }" onclick="{ select_category }">{ name }</span>

            <span class="buttons" show="{ IFC.is_admin() }">
                <!-- When in regular mode show regular edit button -->
                <i show="{ opts.mode != 'catalog' }" class="glyphicon glyphicon-pencil" onclick="{ select_category }"></i>
                <!-- In name editing mode, turn category into input box -->
                <i show="{ opts.mode == 'catalog' }" class="glyphicon glyphicon-pencil" onclick="{ show_rename_category_for_office }"></i>

                <!-- In name editing mode, show the show/hide, Show the eye glyphs which will submit a show/hide change when clicked -->
                <i show="{ opts.mode == 'catalog' && hidden }" class="glyphicon glyphicon-eye-open" onclick="{ submit_showhide_category }"></i>
                <i show="{ opts.mode == 'catalog' && !hidden }" class="glyphicon glyphicon-eye-close" onclick="{ submit_showhide_category }"></i>

                <virtual show="{ opts.mode != 'catalog' }">
                    <i class="glyphicon glyphicon-chevron-up move-up" onclick="{ category_move_up }"></i>
                    <i class="glyphicon glyphicon-chevron-down move-down" onclick="{ category_move_down }"></i>

                    <i class="glyphicon glyphicon-remove" onclick="{ category_delete }"></i>
                </virtual>
            </span>
            </div>
            <form name="rename_form" show="{ show_rename_form }" onsubmit="{ submit_rename_form }">
                <input type="text" name="new_name" class="form-control" onkeyup="{ new_name_input_key_up }" onblur="{ hide_rename_form }">
                { rename_form_error }
            </form>
        </div>
        <span show="{ children.length > 0 }">
            <category each="{ children }"
                      depth="{ this.parent.depth + 1 }"
                      show="{ this.parent.expanded || this.parent == undefined }"
                      mode="{ this.parent.opts.mode }"></category>
        </span>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Properties
         ----------------------------------------------------------------------------*/
        self.selected = false;
        self.expanded = false;
        self.depth = Number(self.opts.depth);
        self.root.style.marginLeft = (self.depth * 15) + "px";
        self.show_rename_form = false;


        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("update", function () {
            // If we have alternate namings for certain offices, check if we're one of
            // those offices
            if (self.category_office_properties) {
                self.category_office_properties.forEach(function (item) {
                    if (IFC.state.office && IFC.state.office.id == item.office) {
                        if (item.name != "") {
                            self.name = item.name;
                        }
                        self.hidden = item.hidden;
                    }
                });
            }

            // Check ourself and our children to see if we have product. if no product, hide!
            /*if (!self.has_product) {
                self.children.forEach(function (child_category) {
                    if (child_category.has_product) {
                        self.has_product = true;
                    }

                    // ... also check children's children
                    child_category.children.forEach(function (childs_child_category) {
                        if (childs_child_category.has_product) {
                            self.has_product = true;
                        }
                    })
                });
            }*/
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.toggle_expand_view = function (event) {
            // If we're in name editing mode ignore these clicks
            if (self.show_rename_form) {
                event.stopPropagation();
                return false;
            }
            // Save this info both to tag AND to our array element for this category!
            self.set_local_and_array('expanded', !self.expanded);
        };

        self.select_category = function (event) {
            event.stopPropagation();
            self.set_local_and_array('selected', true);
            IFC.events.trigger('category_selected', this._item);
        };

        self.get_new_name_element = function () {
            // For some reason in riot the children forms turn our form into an array,
            // first element -> ours if array
            if (self.rename_form instanceof Array) {
                return self.rename_form[0].new_name;
            } else {
                return self.rename_form.new_name;
            }
        };

        self.show_rename_category_for_office = function (event) {
            event.stopPropagation();
            self.show_rename_form = true;
            self.update();
            var field = self.get_new_name_element();
            field.focus();
            field.value = self.name;
        };

        self.submit_rename_form = function (event) {
            event.stopPropagation();
            if (IFC.state.office.id == undefined || IFC.state.office.id == "") {
                self.rename_form_error = "Select an office first before category rename!";
                return false;
            }

            var payload = JSON.stringify({name: self.get_new_name_element().value});

            IFC.api.category_rename(self._item.id, IFC.state.office.id, payload)
                .success(function () {
                    toastr.success("Category renamed!");
                    self.show_rename_form = false;
                    IFC.events.trigger('force_category_list_update');
                })
                .error(function () {
                    toastr.error("Category could not be renamed!");
                });
        };

        self.submit_showhide_category = function (event) {
            event.stopPropagation();
            if (IFC.state.office.id == undefined || IFC.state.office.id == "") {
                self.rename_form_error = "Select an office first before showing or hiding a category!";
                return false;
            }

            var payload = JSON.stringify({name: self.get_new_name_element().value});

            IFC.api.category_showhide(self._item.id, IFC.state.office.id)
                .success(function () {
                    toastr.success("Category show/hide changed!");
                    self.show_rename_form = false;
                    IFC.events.trigger('force_category_list_update');
                })
                .error(function () {
                    toastr.error("Category show/hide could not be changed!");
                });
        };

        self.new_name_input_key_up = function (event) {
            // On escape key hide rename form
            if (event.keyCode == 27) {
                self.show_rename_form = false;
            }
        };

        self.hide_rename_form = function (event) {
            self.show_rename_form = false;
        };

        self.category_move = function (direction) {
            IFC.api['category_move_' + direction](self._item.id)
                .success(function () {
                    toastr.success("Category moved!");
                    IFC.events.trigger('force_category_list_update');
                })
                .error(function () {
                    toastr.error("Error moving categories");
                });
        };

        self.category_move_up = function (event) {
            event.stopPropagation();
            self.category_move('up');
        };

        self.category_move_down = function (event) {
            event.stopPropagation();
            self.category_move('down');
        };

        self.category_delete = function (event) {
            event.stopPropagation();
            if (confirm('Are you sure you want to delete this category?')) {
                IFC.api.delete_category(self._item.id)
                    .success(function () {
                        toastr.success("Category deleted!");
                        // Let the parent know we removed an item, it should re-GET and update
                        IFC.events.trigger('force_category_list_update');
                    })
                    .error(function () {
                        toastr.error("Error deleting category");
                    });
            }
        };

        self.set_local_and_array = function (key, value) {
            // Also set array item value so we between updates we can keep the same item
            // selected/expanded/etc.
            //
            // (we're being used in an each={} loop, so we have self._item)
            self._item[key] = self[key] = value;
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('category_unselected', function () {
            self.set_local_and_array('selected', false);
            self.update();
        });
        IFC.events.on('category_selected', function (category) {
            // When another category is selected, make sure we mark ours as unselected
            self.set_local_and_array('selected', self._item.id == category.id);
            self.update();
        });
    </script>
    <style>
        category {
            display: block;
        }

        .category-super-wrapper {
            display: block;
            padding: 3px 0;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
        }

        .category-wrapper {
            position: relative;
            display: inline-block;
            width: 100%;
            padding: 0 2px;
        }

        category .buttons {
            opacity: 0;
            position: absolute;
            right: 2px;
        }

        .buttons .glyphicon:hover {
            color: #565656;
        }

        .category-name {
            font-size: 18px;
            font-weight: 100;
            letter-spacing: 1px;
            cursor: pointer;
            /*width: 100%;
            margin: 0 auto;
            position: absolute;
            left: 13px;*/
        }

        .category-name .title {
            display: inline-block;
            width: 100%;
        }

        .category-wrapper:hover, .category-wrapper.selected {
            background-color: rgba(150, 150, 250, 0.25);
        }

        .category-wrapper:hover .buttons {
            opacity: 1;
        }

        .category-name .glyphicon {
            font-size: 10px;
            top: -1px;
        }

        .category-name .glyphicon-minus {
            /*font-size: 10px;*/
            top: -5px;
            left: 3px;
            margin-right: 7px;
        }

        .left-side-spacer {
            margin-right: 17px;
        }

        .category-name:hover {
            color: rgba(150, 150, 250, 1);
        }

        .move-up {

        }

        .ishidden {
            opacity: 0.5;
        }
    </style>
</category>

<category-product-form>
    <div class="table-loader" show="{ loading }">
        <i class='glyphicon glyphicon-refresh glyphicon-spin'></i>
    </div>
    <form name="category_form" class="{ loading: loading }" onsubmit="{ submit_category_form }">
        <div class="alert alert-danger" show="{ errors.non_field_errors }">
            { errors.non_field_errors }
        </div>

        <div class="row">
            <div class="col-md-5">
                <div class="form-group {has-error: errors.name }">
                    <label class="control-label">Name</label>
                    <input name="name" type="text" class="form-control">
                    <span class="help-block" show="{ errors.name }">{ errors.name }</span>
                </div>

                <div class="form-group {has-error: errors.parent}">
                    <label class="control-label">Parent category</label>
                    <select name="parent" class="form-control">
                        <option value="">None (make a new Parent category)</option>
                        <!-- Hide the currently selected category so they don't accidentally try to set something
                        to be a parent of itself! -->
                        <option each="{ flat_categories }"
                                value="{ id }"
                                show="{ selected_category == undefined || id != selected_category.id }">
                            { name }
                        </option>
                    </select>
                    <span class="help-block" show="{ errors.parent }">{ errors.parent }</span>
                </div>

                <div class="form-group {has-error: errors.add_ons}">
                    <label class="control-label">Allowed addons</label>
                    <select name="add_ons" class="form-control" multiple="multiple">
                        <option each="{ customization_types }" value="{ name }">
                            { name }
                        </option>
                    </select>
                    <span class="help-block" show="{ errors.add_ons }">{ errors.add_ons }</span>
                </div>
            </div>
            <div class="col-md-1"></div>
            <div class="col-md-6">
                <b>To create a new category</b>
                <p>Fill in a name and select a parent category (if applicable). Then filters available products
                    and move them to the category product list and click Add Category.</p>

                <b>To edit an existing category</b>
                <p>Hover over it and click the pencil.</p>
            </div>
        </div>

        <div class="row">
            <div class="col-md-5 col-sm-12">
                <div class="form-group">
                    <div class="form-group {has-error: errors.styles}">
                        <label class="control-label">Category Product List</label>
                        <!-- Have to inline style 100% width here for some reason, says select2 :) -->
                        <select name="products_selected" class="form-control" multiple="multiple" style="width: 100%;">
                            <option each="{ selected_styles }" value="{ id }" no-reorder>{ name } ({ ecometry_style_id })</option>
                        </select>
                        <span class="help-block" show="{ errors.styles }">{ errors.styles }</span>
                    </div>
                </div>
            </div>
            <div class="col-md-1 ">
                <div class="switcher-button-container-lg hidden-sm">
                    <button type="button" onclick="{ add_products_to_category }">◄</button>
                    <button type="button" onclick="{ remove_products_from_category }">►</button>
                </div>
                <div class="switcher-button-container visible-sm">
                    <button type="button" class="btn-lg" onclick="{ add_products_to_category }">▲</button>
                    <button type="button" class="btn-lg" onclick="{ remove_products_from_category }">▼</button>
                </div>
            </div>
            <div class="col-md-6 col-sm-12">
                <div class="form-group">
                    <div class="form-group {has-error: errors.companies}">
                        <label class="control-label">Available Product List</label>
                        <input name="product_search_filter" placeholder="start typing to filter products" class="form-control" onkeyup="{ product_filter_changed }">
                        <!-- Have to inline style 100% width here for some reason, says select2 :) -->
                        <select name="products_all" class="form-control" multiple="multiple" style="width: 100%;">
                            <option each="{ available_styles }" value="{ id }" no-reorder>{ name } ({ ecometry_style_id })</option>
                        </select>
                        <span class="help-block" show="{ errors.companies }">{ errors.companies }</span>
                    </div>
                </div>
            </div>
        </div>

        <div class="pull-right">

        </div>
        <div class="row">
            <div class="col-md-6 text-left">
                <button type="button" class="btn btn-danger btn-lg" onclick="{ clear_form }">
                    <span show="{ !editing }">Clear form</span>
                    <span show="{ editing }">Clear form and unselect category</span>
                </button>
            </div>
            <div class="col-md-6 text-right">
                <input type="submit" class="btn btn-primary btn-lg" value="Add category" show="{ !editing }">
                <input type="submit" class="btn btn-success btn-lg" value="Save category" show="{ editing }">
            </div>
        </div>
    </form>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Component properties
         ----------------------------------------------------------------------------*/
        self.available_styles = [];
        self.selected_styles = [];


        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on('mount', function () {
            $(self.category_form.add_ons).select2({width: 'resolve'});

            IFC.api.get_customization_types()
                .success(function (types) {
                    self.customization_types = types;
                })
                .error(function () {
                    toastr.error("Could not get customization types list");
                });
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.clear_form = function () {
            Object.keys(self.category_form).map(function (value, index) {
                var element = self.category_form[index];
                if (element && element.type != "submit" && element.type != "button") {
                    self.category_form[index].value = '';
                }
            });
            self.category_form.parent.options[0].selected = true;
            $(self.category_form.add_ons).select2("val", "");
            self.editing = false;
            IFC.events.trigger('category_unselected');
            self.update({editing: false, selected_category: undefined, selected_styles: undefined});
        };

        self.get_form_endpoint = function (payload) {
            if (self.editing) {
                return IFC.api.update_category(JSON.stringify(payload), self.selected_category.id)
            } else {
                return IFC.api.create_category(JSON.stringify(payload));
            }
        };

        self.submit_category_form = function () {
            var payload = $(self.category_form).serializeFormToObject();

            // Remove our auto generated select results, we don't want "selected" options but
            // every single option in one field.
            delete payload.products_selected;
            delete payload.products_selected;

            // Put styles in our payload
            payload.styles = [];
            for (var i = 0; i < self.category_form.products_selected.length; i++) {
                payload.styles.push(self.category_form.products_selected.options[i].value);
            }

            // Make sure we pass allowed addons as array
            if (payload.add_ons) {
                payload.add_ons = payload.add_ons instanceof Array ? payload.add_ons : [payload.add_ons];
            }else{
                payload.add_ons = [];
            }

            self.get_form_endpoint(payload)
                .success(function (data) {
                    if (!self.editing) {
                        toastr.success("Category created!");
                    } else {
                        toastr.success("Category saved!");
                    }

                    $('#category_form_modal').modal('hide');

                    self.clear_form();
                    self.update({errors: undefined, editing: false});

                    IFC.events.trigger('force_category_list_update');
                })
                .error(function (errors) {
                    var data = JSON.parse(errors.responseText);
                    for (var key in data) {
                        // Some errors you get back come like this: ["This field is required!"]
                        // and some come back like this: {"non_field_errors": "This field should be a valid number!"}
                        if (!(data[key] instanceof Array)) {
                            data[key] = data[key]['non_field_errors'];
                        }
                    }
                    self.update({errors: data});
                    toastr.error("Error submitting category form");
                });
        };

        self.product_filter_changed = function (event) {
            if (self.product_search_filter.value.length < 3) {
                return;
            }

            delay(function () {
                var filters = {
                    search: self.product_search_filter.value,
                    page_size: 100
                };
                IFC.api.get_styles(filters)
                    .success(function (data) {
                        self.update({available_styles: data.results});
                    })
                    .error(function () {
                        toastr.error("Error searching for available products");
                    });
            }, 100);
        };

        self.add_products_to_category = function () {
            // Make sure our selected styles array exists, it may not if we haven't started
            // editing a category or something
            self.selected_styles = self.selected_styles || [];

            for (var i = 0; i < self.category_form.products_all.length; i++) {
                if (self.category_form.products_all.options[i].selected) {
                    var category = {
                        name: self.category_form.products_all.options[i].text,
                        id: self.category_form.products_all.options[i].value
                    };
                    self.selected_styles.push(category);
                    //self.category_form.products_all.remove(i);
                    self.available_styles = self.available_styles.filter(function (item) {
                        // Only include items that aren't this one (remove it)
                        return item.id != category.id;
                    });
                }
            }

            // For some reason items in select remain selected, unselect them
            $('option:selected', self.category_form.products_all).removeAttr('selected');
        };

        self.remove_products_from_category = function () {
            /*$('option:selected', self.category_form.products_selected)
             .remove()
             .appendTo(self.category_form.products_all);*/
            for (var i = 0; i < self.category_form.products_selected.length; i++) {
                if (self.category_form.products_selected.options[i].selected) {
                    var category = {
                        name: self.category_form.products_selected.options[i].text,
                        id: self.category_form.products_selected.options[i].value
                    };
                    self.available_styles.push(category);
                    //self.category_form.products_selected.remove(i);
                    self.selected_styles = self.selected_styles.filter(function (item) {
                        // Only include items that aren't this one (remove it)
                        return item.id != category.id;
                    });
                }
            }

            // For some reason items in select remain selected, unselect them
            $('option:selected', self.category_form.products_selected).removeAttr('selected');
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('categories_received', function (categories) {
            // Flatten categories so all children and parents are just a simple array
            self.update({flat_categories: flatten_categories(categories)});
        });

        IFC.events.on('category_selected', function (category) {
            self.update({loading: true});

            // let's load all the styles and such for this category
            var filters = {categories: category.id};
            IFC.api.get_styles(filters)
                .success(function (filtered_styles) {
                    self.update({
                        errors: {},
                        loading: false,
                        editing: true,
                        selected_styles: filtered_styles.results,
                        selected_category: category
                    });

                    // Fill in the form with selected category values
                    self.category_form.name.value = category.name;

                    // Set parent category, if it exists
                    if (category.parent_id) {
                        self.category_form.parent.value = category.parent_id;
                    } else {
                        // No parent so choose "None" option, the first one
                        self.category_form.parent.options[0].selected = true;
                    }

                    // Set addons
                    var addon_names = [];
                    category.add_ons.forEach(function (i) {
                        addon_names.push(i.name)
                    });
                    $(self.category_form.add_ons).val(addon_names).trigger('change');
                })
                .error(function () {
                    toastr.error("Error getting category styles list...");
                });
        });
    </script>
    <style scoped>
        .loading {
            opacity: 0.5;
        }

        .switcher-button-container-lg {
            margin-top: 75px;
        }

        select[name="add_ons"] {
            margin-bottom: 40px;
        }

        select {
            resize: vertical;
        }

        select[name="products_selected"] {
            height: 285px;
        }

        select[name="products_all"] {
            height: 250px;
        }
    </style>
</category-product-form>