<product-management-filters>
    <h3>Filters</h3>

    <strong>Preset searches</strong><br>
    <a href="#" onclick="{ get_new_styles }">New Styles</a><br>
    <a href="#" onclick="{ get_hidden_styles }">Hidden Styles</a><br>
    <!--<a href="#">Non-Hidden Styles</a><br>-->
    <!--<a href="#">Orphaned Styles</a><br>-->
    <br>

    <strong>Search</strong>
    <input name="style_search_filter" class="form-control" placeholder="keywords" onkeyup="{ style_keyword_changed }"><br>

    <strong>Results</strong><br>
    <i show="{ !search_results }">Select a preset or type keywords to search</i>
    <i show="{ search_results.length == 0 }">No results!</i>
    <ul>
        <li each="{ search_results }">
            <a href="#" onclick="{ select_style }">{ name }</a>
        </li>
    </ul>

    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.get_new_styles = function (e) {
            e.preventDefault;
            self.update_product_search_results({'new': 'True'})
        };

        self.get_hidden_styles = function (e) {
            e.preventDefault;
            self.update_product_search_results({only_hidden: 'true'})
        };

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

            delay(function () {
                self.update_product_search_results({
                    search: self.style_search_filter.value
                });
            }, 100);
        };

        self.update_product_search_results = function (filters) {
            var filters = filters || {};

            filters.page_size = 100;

            IFC.api.get_styles(filters)
                .success(function (data) {
                    self.update({search_results: data.results});
                })
                .error(function () {
                    toastr.error("Could not get product search results");
                });
        };

        self.select_style = function (event) {
            event.preventDefault();
            // _item here is the current item in the "each" loop
            IFC.events.trigger('style_selected', this._item);
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/

    </script>
    <style>

    </style>
</product-management-filters>

<product-management-form>
    <div show="{ !selected_style }">
        <i>Select a style using the filters on the left</i>
    </div>

    <div class="row" show="{ selected_style }">
        <div class="col-md-12">

            <ul class="nav nav-tabs">
                <li class="{ active: active_tab == 'general' }" onclick="{ switch_tab.bind(this, 'general') }">
                    <a href="#">General details</a>
                </li>
                <li class="{ active: active_tab == 'images' }" onclick="{ switch_tab.bind(this, 'images') }">
                    <a href="#">Images</a>
                </li>
                <li class="{ active: active_tab == 'add-ons' }" onclick="{ switch_tab.bind(this, 'add-ons') }">
                    <a href="#">Add On Exceptions</a>
                </li>
            </ul>

            <!-- Every tab is wrapped by our form! -->
            <form name="style_form" class="form-horizontal" onsubmit="{ submit_product_form }" autocomplete="on">
                <div class="alert alert-danger" show="{ errors }">
                    <!-- for every tab show errors in a very obvious way here -->
                    { errors.non_field_errors }

                    <ul>
                        <li each="{key, value in errors}"><strong>{ key }</strong> { value }</li>
                    </ul>
                </div>

                <div show="{ active_tab == 'general' }">
                    <!---------------------------------------------------------
                    Style
                    ---------------------------------------------------------->
                    <h4>Product style</h4>
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Style ID</label>
                        <div class="col-sm-10">
                            <span class="uneditable-text">{ selected_style.ecometry_style_id }</span>
                        </div>
                    </div>

                    <div class="form-group {has-error: errors.name}">
                        <label class="col-sm-2 control-label">Style name</label>
                        <div class="col-sm-10">
                            <input name="name" type="text" class="form-control">
                        </div>
                        <span class="help-block" show="{ errors.name }">{ errors.name }</span>
                    </div>

                    <hr>

                    <virtual show="{ selected_style.option_1 }">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">First option</label>
                            <div class="col-sm-10">
                                <select class="form-control option-select">
                                    <option each="{ selected_style.option_1.choices }" value="">{ label } ({value})</option>
                                </select>
                                <div class="color-radio">
                                    <input name="color_option_number" type="radio" value="1" onchange="{ color_option_number_changed }">
                                    Color option
                                </div>
                            </div>
                        </div>

                        <div class="form-group {has-error: errors.option_1_title }">
                            <label class="col-sm-2 control-label">First title</label>
                            <div class="col-sm-10">
                                <input name="option_1_title" type="text" class="form-control">
                            </div>
                            <span class="help-block" show="{ errors.option_1_title }">{ errors.option_1_title }</span>
                        </div>
                    </virtual>

                    <virtual show="{ selected_style.option_2 }">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Second option</label>
                            <div class="col-sm-10">
                                <select class="form-control option-select">
                                    <option each="{ selected_style.option_2.choices }" value="">{ label } ({value})</option>
                                </select>
                                <div class="color-radio">
                                    <input name="color_option_number" type="radio" value="2" onchange="{ color_option_number_changed }">
                                    Color option
                                </div>
                            </div>
                        </div>

                        <div class="form-group {has-error: errors.option_2_title }">
                            <label class="col-sm-2 control-label">Second title</label>
                            <div class="col-sm-10">
                                <input name="option_2_title" type="text" class="form-control">
                            </div>
                            <span class="help-block" show="{ errors.option_2_title }">{ errors.option_2_title }</span>
                        </div>
                    </virtual>

                    <virtual show="{ selected_style.option_3 }">
                        <div class="form-group">
                            <label class="col-sm-2 control-label">Third option</label>
                            <div class="col-sm-10">
                                <select class="form-control option-select">
                                    <option each="{ selected_style.option_3.choices }" value="">{ label } ({value})</option>
                                </select>
                                <div class="color-radio">
                                    <input name="color_option_number" type="radio" value="3" onchange="{ color_option_number_changed }">
                                    Color option
                                </div>
                            </div>
                        </div>

                        <div class="form-group {has-error: errors.option_3_title }">
                            <label class="col-sm-2 control-label">Third title</label>
                            <div class="col-sm-10">
                                <input name="option_3_title" type="text" class="form-control">
                            </div>
                            <span class="help-block" show="{ errors.option_3_title }">{ errors.option_3_title }</span>
                        </div>
                    </virtual>

                    <!-- Show explanation if no options are shown -->
                    <div class="form-group" show="{ !selected_style.option_1 && !selected_style.option_2 && !selected_style.option_3 }">
                        <label class="col-sm-2 control-label"></label>
                        <div class="col-sm-10">
                            <i>
                                No options for this style
                            </i>
                        </div>
                    </div>

                    <hr>

                    <div class="form-group">
                        <label class="col-sm-2 control-label">Price</label>
                        <div class="col-sm-10">
                            <span class="uneditable-text">
                                { selected_style.min_price } - { selected_style.max_price }
                            </span>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <div class="checkbox">
                                <label>
                                    <input name="hidden" type="checkbox"> Hide this style
                                </label>
                            </div>
                        </div>
                    </div>

                    <!--
                    <div class="form-group">
                        <label class="col-sm-2 control-label">Default color</label>
                        <div class="col-sm-10">
                            <select name="default_color" class="form-control">
                                <option each="{ color_options }" value="{ id }">{ label } ({ value })</option>
                            </select>
                        </div>
                    </div>
                    -->

                    <!--
                    <div class="form-group {has-error: errors.first_name }">
                        <label class="col-sm-2 control-label">Default color</label>
                        <div class="col-sm-10">
                            <select name="products_all" class="form-control">
                                <option>ASDFASDF</option>
                            </select>
                        </div>
                        <span class="help-block" show="{ errors.first_name }">{ errors.first_name }</span>
                    </div>
                    -->

                    <div class="form-group {has-error: errors.long_description }">
                        <label class="col-sm-2 control-label">Description</label>
                        <div class="col-sm-10">
                            <textarea id="long_description_textarea" name="long_description" class="form-control tinymce"></textarea>
                        </div>
                        <span class="help-block" show="{ errors.long_description }">{ errors.long_description }</span>
                    </div>

                    <div class="form-group {has-error: errors.specifications }">
                        <label class="col-sm-2 control-label">Specifications</label>
                        <div class="col-sm-10">
                            <textarea id="specifications_textarea" name="specifications" class="form-control tinymce"></textarea>
                        </div>
                        <span class="help-block" show="{ errors.specifications }">{ errors.specifications }</span>
                    </div>

                    <div class="form-group {has-error: errors.categories }">
                        <label class="col-sm-2 control-label">Categories</label>
                        <div class="col-sm-10">
                            <select name="categories" id="catagory" class="form-control" multiple="multiple">
                                <option each="{ categories }" value="{ id }">{ name }</option>
                            </select>
                        </div>

                        <span class="help-block" show="{ errors.categories }">{ errors.categories }</span>
                    </div>

                    <div class="form-group {has-error: errors.add_on_type}">
                        <label class="col-sm-2 control-label">Add on type</label>
                        <div class="col-sm-10">
                            <select name="add_on_type" class="form-control">
                                <option value="">-----</option>
                                <option each="{ customization_types }" value="{ name }">
                                    { name }
                                </option>
                            </select>
                            <span class="help-block" show="{ errors.add_on_type }">{ errors.add_on_type }</span>
                        </div>
                    </div>

                    <!---------------------------------------------------------
                    Customizations
                    ---------------------------------------------------------->
                    <h4>Product customizations</h4>

                    <product-customization-form-group each="{ selected_style.extra_customizations }" no-reorder></product-customization-form-group>

                    <button class="btn btn-default" type="button" onclick="{ add_empty_customization }">
                        <i class="glyphicon glyphicon-plus"></i> Add another customization
                    </button>

                    <!---------------------------------------------------------
                    Notes
                    ---------------------------------------------------------->
                    <h4>Notes & Reminders (NOT shown on web)</h4>

                    <div class="form-group {has-error: errors.notes}">
                        <label class="col-sm-2 control-label">Notes</label>
                        <div class="col-sm-10">
                            <textarea name="notes" class="form-control"></textarea>
                        </div>
                        <span class="help-block" show="{ errors.notes }">{ errors.notes }</span>
                    </div>
                </div>

                <div show="{ active_tab == 'images' }">
                    <product-image-upload each="{ selected_style.images }" colors="{ color_options }" no-reorder></product-image-upload>
                    <button class="btn btn-default" onclick="{ add_empty_image }">
                        <i class="glyphicon glyphicon-plus"></i> Add image
                    </button>
                </div>

                <div show="{ active_tab == 'add-ons' }">
                    <!---------------------------------------------------------
                    Add-On Exceptions
                    ---------------------------------------------------------->
                    <h4>Product add-on inclusions and exclusions</h4>
                    <p><br></p>
                    <div class="form-group {has-error: errors.add_on_exceptions}">
                        <div class="col-sm-6">
                            <button class="btn btn-default" type="button" onclick="{ add_new_add_on_exception.bind(this, 'inclusion') }">
                                <i class="glyphicon glyphicon-plus"></i> Add new add-on inclusion
                            </button>
                            <br><br>
                            <div class="panel panel-default col-sm-10">
                              <div class="panel-heading">Add_On Inclusions</div>
                              <table class="table table-responsive">
                                <thead>
                                  <tr>
                                    <th>Add On Type</th>
                                    <th>Company</th>
                                    <th>Office</th>
                                    <th><i class="glyphicon glyphicon-remove"></i> Delete</th>
                                  </tr>
                                </thead>
                                <tbody>
                                <tr each="{ add_on_inclusions }"
                                    class="{ }"
                                    onclick="{ }">
                                    <td>{ add_on_type.name }</td>
                                    <td>{ company.name }</td>
                                    <td>{ office.name }</td>
                                    <td><i class="glyphicon glyphicon-remove red-link"
                                           onclick="{ delete_exception.bind(this, id, 'inclusion') }"></i></td>
                                </tr>
                                </tbody>
                              </table>
                            </div>
                        </div>
                        <div class="col-sm-6">
                            <button class="btn btn-default" type="button" onclick="{ add_new_add_on_exception.bind(this, 'exclusion') }">
                                <i class="glyphicon glyphicon-plus"></i> Add new add-on exclusion
                            </button>
                            <br><br>
                            <div class="panel panel-default col-sm-10">
                              <div class="panel-heading">Add_On Exclusions</div>
                              <table class="table table-responsive">
                                <thead>
                                  <tr>
                                    <th>Add On Type</th>
                                    <th>Company</th>
                                    <th>Office</th>
                                    <th><i class="glyphicon glyphicon-remove"></i> Delete</th>
                                  </tr>
                                </thead>
                                <tbody>
                                <tr each="{ add_on_exclusions }"
                                    class="{ }"
                                    onclick="{ }">
                                    <td>{ add_on_type.name }</td>
                                    <td>{ company.name }</td>
                                    <td>{ office.name }</td>
                                    <td><i class="glyphicon glyphicon-remove red-link"
                                           onclick="{ delete_exception.bind(this, id, 'exclusion') }"></i></td>
                                </tr>
                                </tbody>
                              </table>
                            </div>
                        </div>
                        <span class="help-block" show="{ errors.add_on_exceptions }">{ errors.add_on_exceptions }</span>
                    </div>
                    <br><br>
                </div>

                <button type="submit" class="btn btn-success btn-lg pull-right"show="{ active_tab != 'add-ons' }">
                    <i class='glyphicon glyphicon-refresh glyphicon-spin' show="{ loading }"></i> Save style
                </button>
            </form>
        </div>
    </div>

    <div class="modal fade" id="add_on_exception_form_modal" role="dialog">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title">Add new add on { add_on_exception_type }</h4>
                </div>
                <form name="add_on_exception_form">
                    <div class="modal-body">
                        <div class="alert alert-danger" show="{ errors.non_field_errors }">
                            { errors.non_field_errors }
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group {has-error: errors.company}">
                                    <label class="control-label">Company</label>
                                    <select name="company" class="form-control" onchange="{ company_changed }">
                                        <option value="default">Select a company</option>
                                        <option each={ IFC.state.companies } value={ id }>{ name }</option>
                                    </select>
                                    <span class="help-block" show="{ errors.company }">{ errors.company }</span>
                                </div>
                            </div>

                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group {has-error: errors.office}">
                                    <label class="control-label">Office</label>
                                    <select name="office" class="form-control">
                                        <option value="default">Select an Office</option>
                                        <option each={ offices } value={ id }>{ name }</option>
                                    </select>
                                    <span class="help-block" show="{ errors.office }">{ errors.office }</span>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group {has-error: errors.add_on_type}">
                                    <label class="control-label">Add-On Type</label>
                                    <select name="add_on_type" class="form-control">
                                        <option value="default">Select an add-on type</option>
                                        <option each="{ customization_types }" value="{ id }">
                                            { name }
                                        </option>
                                    </select>
                                    <span class="help-block" show="{ errors.add_on_type }">{ errors.add_on_type }</span>
                                </div>
                            </div>
                        </div>

                        <input name="style" type="hidden" value="{ selected_style.id }">
                        <input name="add_on_exception_type" type="hidden" value="{ add_on_exception_type }">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Close</button>

                        <input type="submit" class="btn btn-success btn-lg" value="Add" onclick="{ submit_add_on_exception_form }" show="{ !editing }">
                        <input type="submit" class="btn btn-success btn-lg" value="Save" onclick="{ submit_add_on_exception_form }" show="{ editing }">
                    </div>
                </form>
            </div>
        </div>
    </div>


    <script>
    $(function() {
    $('#catagory').change(function(e) {
        var selected = $(e.target).val();
        console.log(selected);
        });
    });
        var self = this;

        /* ----------------------------------------------------------------------------
         Component properties
         ----------------------------------------------------------------------------*/
        self.active_tab = "general";


        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one("mount", function () {

            tinymce.init({
                selector: '.tinymce',
                plugins: ["lists"]
            });

            // Fill in categories
            IFC.api.get_categories()
                .success(function (categories) {
                    self.categories = flatten_categories(categories, true);
                })
                .error(function () {
                    toastr.error("Could not get category list");
                });

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

            // Setup select2
            $(self.style_form.categories).select2({width: '100%'});
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.switch_tab = function (tab_name) {
            self.update({active_tab: tab_name});
        };

        self.clear_form = function () {
            $(':input,textarea', self.style_form)
                .not(':button, :submit, :reset, :hidden, :radio')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
            $(self.style_form.categories).select2("val", "");
        };

        self.submit_product_form = function () {
            self.loading = true;
            self.update();

            // TinyMCE textareas need to be manually saved otherwise they'll be empty
            tinyMCE.triggerSave();

            // Serialize form
            var payload = $(self.style_form).serializeFormToObject();

            // Force multiple selections to be arrays
            if (payload.categories) {
                payload.categories = payload.categories instanceof Array ? payload.categories : [payload.categories];
            } else {
                payload.categories = [];
            }

            // For some reason checkboxes aren't serialized properly, add it here
            if (payload.hidden === undefined) {
                payload.hidden = false;
            }

            // Get images
            payload.images = [];
            self.selected_style.images.forEach(function (item) {
                if (item.zoomed_url !== undefined) {
                    // Images update their own `self._item` and we pull that here
                    payload.images.push(item);
                }
            });

            // Customizations
            payload.extra_customizations = [];
            self.selected_style.extra_customizations.forEach(function (item) {
                // Customizations update their own `self._item` and we pull that here
                if (item.title !== undefined) {
                    payload.extra_customizations.push(item);
                }
            });

            // Remove add on type if it's blank
            //if (payload.add_on_type == '') {
            //    delete payload.add_on_type;
            //}

            IFC.api.update_style(self.selected_style.id, JSON.stringify(payload))
                .success(function (data) {
                    // Remove errors
                    self.update({loading: false, errors: undefined});

                    // Update form with proper Ids (customizations, iamges)
                    self.process_selected_style(self.selected_style);

                    toastr.success("Saved style!")
                })
                .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'];
                        }

                        if (key == 'extra_customizations') {
                            // Instead of displaying `extra_customizations: [Object object]`
                            // display the contents of the error nicely
                            var flattened_errors = '';
                            data[key].forEach(function (item) {
                                for (var inside_key in item) {
                                    flattened_errors += inside_key + ' -> ' + item[inside_key];
                                }
                            });

                            data[key] = flattened_errors;
                        }
                    }
                    self.update({errors: data});
                    toastr.error("Error submitting form");
                });
        };

        self.add_empty_image = function () {
            self.selected_style.images.push({pointer: '#misc'});
        };
        self.add_empty_customization = function () {
            self.selected_style.extra_customizations.push({});
        };

        self.get_color_options = function (color_option_number) {
            // We need to get color options to pass to images selector, generate that here!
            // (color option can change, so we need to grab that specific selector)
            if (self.selected_style['option_' + color_option_number]) {
                return self.selected_style['option_' + color_option_number].choices;
            }
        };

        self.color_option_number_changed = function (event) {
            // If we're calling this directly without an event, set to a default, otherwise
            // use the event element to get the color option value
            if (event === undefined) {
                self.selected_style.color_option_number = self.selected_style.color_option_number || 1;
            } else {
                self.selected_style.color_option_number = event.target.value;
            }

            self.color_options = self.get_color_options(self.selected_style.color_option_number);
            self.update();
        };

        self.add_new_add_on_exception = function(exception_type){
            self.update({ add_on_exception_type: exception_type});
            $('#add_on_exception_form_modal').modal('show');
            self.clear_add_on_exception_form();
        };

        self.clear_add_on_exception_form = function () {
            Object.keys(self.add_on_exception_form).map(function (value, index) {
                var element = self.add_on_exception_form[index];
                if (element && element.type != "submit" && element.type != "button") {
                    self.add_on_exception_form[index].value = '';
                }
            });

            self.add_on_exception_form.company.value = 'default';
            self.add_on_exception_form.office.value = 'default';
            self.add_on_exception_form.add_on_type.value = 'default';
        };

        self.company_changed = function() {
            // alert('company changed');
             var selected_company = undefined;
             IFC.state.companies.forEach(function(item){
                if(item.id == self.add_on_exception_form.company.value) {
                    selected_company = item;
                }
             });
             self.update_office_list(selected_company);
        };

        self.update_office_list = function (selected_company) {
            var filters = {company: selected_company.id};

            // Return this so other events can do something AFTER it's finished
            return IFC.api.get_offices(filters)
                .success(function (data) {
                    // Update our local data
                    self.update({offices: data});
                    // Fire off selected office event
                    // IFC.events.trigger('offices_updated', data);
                })
                .error(function () {
                    toastr.error('Error getting office list');
                });
        };

        self.submit_add_on_exception_form = function () {
            var payload = $(self.add_on_exception_form).serializeFormToObject();
            payload = JSON.stringify(payload);

            IFC.api.create_add_on_exception(payload)
                .success(function (data) {
                    toastr.success("Style Exception created!");

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

                    // self.clear_form();
                    self.update({errors: undefined});

                    IFC.events.trigger('force_exception_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 add on exception form");
                });
        };

        self.populate_add_on_inclusions = function () {
            var filters = {style_id: self.selected_style.id};

            // Return this so other events can do something AFTER it's finished
            return IFC.api.get_add_on_inclusions(filters)
                .success(function (data) {
                    // Update our local data
                    self.update({add_on_inclusions: data});

                })
                .error(function () {
                    toastr.error("Could not get add_on inclusions for selected style");
                });
        };

        self.populate_add_on_exclusions = function () {
            var filters = {style_id: self.selected_style.id};
            // Return this so other events can do something AFTER it's finished
            return IFC.api.get_add_on_exclusions(filters)
                .success(function (data) {
                    // Update our local data
                    self.update({add_on_exclusions: data});

                })
                .error(function () {
                    toastr.error("Could not get add_on exclusions for selected style");
                });
        };

        self.delete_exception = function (id, exception_type) {
            if (confirm('Are you sure you want to delete this style add-on ' + exception_type + '?')) {
                var payload = {"add_on_exception_id": id, "add_on_exception_type": exception_type};
                // Return this so other events can do something AFTER it's finished
                return IFC.api.delete_add_on_exception(JSON.stringify(payload))
                        .success(function (data) {
                            toastr.success("Style Exception deleted!");
                            // Update our local data
                            IFC.events.trigger('force_exception_list_update');
                        })
                        .error(function (errors) {
                            var data = JSON.parse(errors.responseText);
                            toastr.error("Could not delete add on exception");
                        });
            }
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        self.process_selected_style = function (style) {
            self.clear_form();

            IFC.api.get_style_detail(style.id)
                .success(self.update_form_data)
                .error(function () {
                    toastr.error("Could not load style detail")
                });
        };

        self.update_form_data = function (style) {
            // Override images with empty definition if none already exist, so we have
            // at least one image
            style.images = style.images.length > 0 ? style.images : [{pointer: '#misc'}];

            // Make images be in the same order (sometimes it changes order for some reason?)
            style.images.sort(function (a, b) {
                return a.id > b.id;
            });

            // Same with customizations, we want at least 1 empty element for our form
            style.extra_customizations = style.extra_customizations.length > 0 ? style.extra_customizations : [{}];

            self.update({selected_style: style});
            self.selected_style = style;
            self.populate_add_on_inclusions();
            self.populate_add_on_exclusions();

            self.style_form.name.value = style.name || '';
            self.style_form.notes.value = style.notes || '';
            self.style_form.hidden.checked = style.hidden;
            self.style_form.color_option_number.value = style.color_option_number || 1;
            self.style_form.add_on_type.value = style.add_on_type ? style.add_on_type.name : '';

            self.style_form.option_1_title.value = style.option_1 ? style.option_1.label : undefined;
            self.style_form.option_2_title.value = style.option_2 ? style.option_2.label : undefined;
            self.style_form.option_3_title.value = style.option_3 ? style.option_3.label : undefined;

            // TinyMCE needs to be manually set
            tinyMCE.get('long_description_textarea').setContent(style.long_description || '')
            tinyMCE.get('specifications_textarea').setContent(style.specifications || '')

            // `trigger('change')` is the key to making select2 val updating work!
            $(self.style_form.categories).val(style.categories).trigger('change');

            // Set color options for image selection page
            self.color_option_number_changed();

            // Do this after color options have been assigned
            //self.style_form.default_color.value = style.default_color;
        };

        IFC.events.on("style_selected", self.process_selected_style);

        IFC.events.on('removed_customization', function (removed_id) {
            self.selected_style.extra_customizations = self.selected_style.extra_customizations.filter(function (customization) {
                return removed_id != customization.id && customization.remove_me !== true;
            });
            self.update();
        });

        IFC.events.on('removed_image', function (removed_id) {
            self.selected_style.images = self.selected_style.images.filter(function (image) {
                return removed_id !== image.id && image.remove_me !== true;
            });

            // If we have no images, put a blank one there
            if(self.selected_style.images.length == 0) {
                self.add_empty_image();
            }

            self.update();
        });

         IFC.events.on('force_exception_list_update', function (data) {
            self.populate_add_on_inclusions();
            self.populate_add_on_exclusions();
        });

    </script>

    <style scoped>
        .uneditable-text {
            margin-top: 7px;
            font-weight: bold;
            display: block;
            color: rgba(100, 100, 250, 1);
        }

        .form-horizontal h4 {
            background-color: rgba(100, 100, 250, 0.5);
            padding: 5px;
        }

        select {
            width: 100%;
        }

        .option-select {
            display: inline-block;
            margin-right: 10px;
            width: 50%;
        }

        .color-radio {
            display: inline-block;
        }

        .red-link{
            color: Red;
        }
    </style>
</product-management-form>

<product-customization-form-group>
    <div class="form-group">
        <label class="col-sm-2 control-label">Title</label>
        <div class="col-sm-10">
            <div class="input-group">
                <!--<input type="text" class="form-control" placeholder="Username" aria-describedby="sizing-addon1">-->
                <input name="title_element" type="text" class="form-control" onchange="{ title_changed }">
                <span class="input-group-addon remove-customization" onclick="{ customization_delete }">
                    <i class="glyphicon glyphicon-remove"></i>
                </span>
            </div>

        </div>
    </div>

    <div class="form-group">
        <label class="col-sm-2 control-label">Options</label>
        <div class="col-sm-10">
            <textarea name="content_element" class="form-control" onchange="{ content_changed }"></textarea>
        </div>
    </div>
    <hr>

    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("updated", function () {
            self.title_element.value = self._item.title || '';
            self.content_element.value = self._item.content || '';
        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.title_changed = function (event) {
            self._item.title = event.target.value;
        };
        self.content_changed = function (event) {
            self._item.content = event.target.value;
        };

        self.customization_delete = function (event) {
            event.stopPropagation();
            if (self._item.id === undefined) {
                // Hasn't even been saved yet, manually tell it to be removed
                self._item.remove_me = true;
                IFC.events.trigger('removed_customization', undefined);
                return;
            }

            if (confirm('Are you sure you want to delete this customization?')) {
                IFC.api.delete_customization(self._item.id)
                    .success(function () {
                        toastr.success("Customization deleted!");
                        IFC.events.trigger('removed_customization', self._item.id);
                    })
                    .error(function () {
                        toastr.error("Error deleting customization");
                    });
            }
        };
    </script>
    <style scoped>
        .remove-customization:hover {
            cursor: pointer;
            background-color: rgba(255, 0, 0, 0.35);
            color: rgba(255, 0, 0, 0.72);
            border-color: red;
            border-left: 1px solid red;
        }
    </style>
</product-customization-form-group>

<product-image-upload>
    <div class="media">
        <div class="media-left media-middle">
            <a href="#">
                <!-- If we don't have a thumbnail, just display the image as soon as it's uploaded compressed
                down to the right px width/height -->
                <img class="media-object" src="{ thumbnail_url || zoomed_url }" width="125" show="{ zoomed_url }">
                <img class="media-object" src=https://via.placeholder.com/125?text= " show="{ !zoomed_url }">
            </a>
        </div>
        <div class="media-body">
            <div class="row">
                <div class="col-md-6">
                    <select name="pointer_selector" class="form-control" onchange="{ image_type_changed }">
                        <option value="#misc">Misc Image</option>
                        <option value="#sizing">Size Chart</option>
                        <option each="{ opts.colors }" value="{ value }">{ label }</option>
                    </select>
                </div>
                <div class="col-md-6">
                    <div class="checkbox">
                        <label>
                            <input name="default_image" type="radio" onchange="{ image_default_changed }"> Default image
                        </label>
                    </div>
                </div>
            </div>

            <!-- This is hidden -->
            <input name="image" type="file" onchange="{ upload_file }" accept="image/*">

            <button type="button" class="btn btn-default" onclick="{ select_file }">
                <virtual show="{ zoomed_url }">
                    <i class="glyphicon glyphicon-pencil"></i> Replace image
                </virtual>
                <virtual show="{ !zoomed_url }">
                    <i class="glyphicon glyphicon-plus"></i> Upload new image
                </virtual>
            </button>

            <button type="button" class="btn btn-danger" onclick="{ image_delete }">
                <i class="glyphicon glyphicon-remove"></i> Remove image
            </button>

            <div class="progress" show="{ percent_complete > 0 }">
                <div class="progress-bar progress-bar-success progress-bar-striped" name="progress_bar">
                </div>
            </div>
            <br><br>
        </div>
    </div>
    <script>

        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("updated", function () {
            if (self._item) {
                self.pointer_selector.value = self._item.pointer;
                self.default_image.checked = self._item.is_default;

                // If the option isn't found, revert to default
                if (self.pointer_selector.selectedIndex === -1) {
                    self.pointer_selector.selectedIndex = 0;
                }
            }
        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.select_file = function () {
            //var input_element = $('input[name="product_' + self.id + '_image"]')[0];
            self.image.click();
        };

        self.upload_file = function () {
            //var input_element = $('input[name="product_' + self.id + '_image"]')[0];
            var file = self.image.files[0];

            IFC.api.upload(file, "product_images", function (data) {
                // Remove current image
                delete self.thumbnail_url;
                delete self._item.thumbnail_url;

                // Set new image
                self._item.zoomed_url = self.zoomed_url = data.image.url;
                self.percent_complete = 0;
                self.update();
            }, self.file_upload_progress_handler);
        };

        self.file_upload_progress_handler = function (percent_complete) {
            self.progress_bar.style.display = 'block';
            self.progress_bar.style.width = (percent_complete * 100) + '%';

            self.percent_complete = percent_complete;
            self.update();
        };

        self.image_type_changed = function () {
            // We need to set this, it also sets for the parent
            self._item.pointer = self.pointer_selector.value;
        };

        self.image_default_changed = function () {
            // We fire an event here so every image can unset their defaultness if they aren't
            // this image.
            IFC.events.trigger('image_default_selected', self._item);
        };

        self.image_delete = function (event) {
            event.stopPropagation();
            if (self._item.id === undefined) {
                // Hasn't even been saved yet, manually tell it to be removed
                self._item.remove_me = true;
                IFC.events.trigger('removed_image', undefined);
                return;
            }

            if (confirm('Are you sure you want to delete this image?')) {
                IFC.api.delete_image(self._item.id)
                    .success(function () {
                        toastr.success("Image deleted!");
                        IFC.events.trigger('removed_image', self._item.id);
                    })
                    .error(function () {
                        toastr.error("Error deleting image");
                    });
            }
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('image_default_selected', function (default_image) {
            // Image default selected, is it this image or another one??
            self._item.is_default = self._item.id == default_image.id;
        });
    </script>

    <style scoped>
        :scope {
            display: block;
            margin-bottom: 20px;
            background-color: rgba(100, 100, 250, 0.1);
            padding: 10px;
        }

        .form-control, .btn {
            margin-bottom: 20px;
        }

        input[type="file"] {
            display: none;
        }

        img {
            max-width: 500px;
            max-height: 300px;
        }
    </style>
</product-image-upload>
