<user-account-management>
    <div class="row">
        <div class="col-lg-6 col-md-12">
            <user-table></user-table>
        </div>
        <div class="col-lg-6 col-md-12">
            <user-form></user-form>
        </div>
    </div>
</user-account-management>

<user-table>
    <div class="table-responsive">
        <table name="user_table" class="table { loading: loading }">
            <thead>
            <tr onclick="{ table_header_clicked }">
                <th width="30"></th>
                <th width="32"></th>
                <!--
                data-ordering is the column in database to sort when clicked (in the api call, i.e.
                http://something.com/users/?orderby=-last_name

                also note "sort-down" class on Last Name gives us our default first sort otherwise
                initial click appears to do nothing
                -->
                <th data-ordering="last_name">Last Name</th>
                <th data-ordering="first_name">First Name</th>
                <th data-ordering="username">Username</th>
                <th data-ordering="role">Type</th>
            </tr>
            </thead>
            <tbody>
            <tr each="{ users }" class="{ highlight: selected_user.email == email }" onclick="{ select_user }">
                <td>
                    <button class="btn btn-primary btn-sm" onclick="{ select_user }">
                        <i class="glyphicon glyphicon-edit"></i>
                    </button>
                </td>
                <td>
                    <button class="btn btn-danger btn-sm" onclick="{ delete_user }">
                        <i class="glyphicon glyphicon-remove"></i>
                    </button>
                </td>
                <td>{ last_name }</td>
                <td>{ first_name }</td>
                <td>{ username ? username : 'N/A' }</td>
                <td>{ role.name }</td>
            </tr>
            </tbody>
        </table>
        <div class="table-loader" show="{ loading }">
            <i class='glyphicon glyphicon-refresh glyphicon-spin'></i>
        </div>
    </div>

    <nav>
        <ul class="pagination">
            <li onclick="{ change_page.bind(this, page.prev) }">
                <a href="#" class="{ disabled: !page.prev }" aria-label="Previous">
                    <span aria-hidden="true">&laquo;</span>
                </a>
            </li>
            <li each="{ page.page_numbers }" onclick="{ change_page.bind(this, number) }" class="{active: number == page.current_page }">
                <a href="#">{ number }</a></li>
            <li onclick="{ change_page.bind(this, page.next) }">
                <a href="#" class="{ disabled: !page.next }" aria-label="Next">
                    <span aria-hidden="true">&raquo;</span>
                </a>
            </li>
        </ul>
    </nav>

    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("mount", function () {
            // Init table
            self.user_table_sorter = Tablesort(self.user_table);
        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.update_users = function (filters) {
            self.update({loading: true});
            filters = filters || {};
            filters.companies = IFC.state.user.company.id;
            if (IFC.state.office && IFC.state.office.id !== '') {
                filters.offices = IFC.state.office.id;
            }

            var selected_header_element = $(".sort-down, .sort-up", self.user_table);
            var sort_name = selected_header_element.attr('data-ordering');
            var sort_direction = selected_header_element.hasClass("sort-down") ? "" : "-";  // default is last_name
            filters.ordering = sort_direction + sort_name;  // -first_name, for example

            IFC.api.get_users(filters)
                .success(function (data) {
                    /*
                     For reference:
                     data = {
                     "count": 62,
                     "next": "http://localhost:8000/api/users/?page=3",
                     "previous": "http://localhost:8000/api/users/",
                     "results": [ ... ]
                     }
                     */
                    var page_numbers = [];
                    var page_size = 15;
                    var current_page = filters && filters.page ? filters.page : 1;
                    var page_count = 0;

                    for (var count = 0; count < data.count; count += page_size) {
                        page_numbers.push({number: (count + page_size) / page_size});
                        page_count++;
                    }

                    self.update({
                        page: {
                            prev: current_page > 1 ? current_page - 1 : 0,
                            next: current_page != page_count ? current_page + 1 : 0,
                            count: data.count,
                            page_numbers: page_numbers,
                            // Save our current page if we're selecting a page (if we have a filter), otherwise
                            // we can assume we're on page 1
                            current_page: current_page
                        },
                        users: data.results
                    });

                    // Update table sorting
                    self.user_table_sorter.refresh();
                })
                .error(function () {
                    toastr.error("Error fetching users");
                })
                .always(function () {
                    self.update({loading: false});
                });
        };

        self.table_header_clicked = function (event) {
            self.update_users();
        };

        self.change_page = function (page_number) {
            // We check page number here and if prev/next are set to 0 because we're on the first/last page,
            // this won't fire!
            if (page_number) {
                self.update_users({page: page_number})
            }
        };

        self.select_user = function () {
            // _item here is the current item in the "each" loop (our user data!)
            self.update({selected_user: this._item});
            IFC.events.trigger('user_selected', self.selected_user);
        };

        self.update_user_list_in_place = function () {
            // Force an update request using the current page
            self.update_users({page: self.page.current_page});
        };

        self.delete_user = function (event) {
            event.cancelBubble = true;
            if (confirm('Are you sure you want to delete this user?')) {
                IFC.api.delete_user(this._item.id)
                    .success(function () {
                        toastr.success("User deleted!");
                        self.update_user_list_in_place();
                    })
                    .error(function (response) {
                        if (response.status == 403) {
                            toastr.error("Can't delete a user with permissions greater than yours.");
                        } else {
                            toastr.error("Error deleting user");
                        }
                    });
            }
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('office_selected', function (data) {
            self.update_users();
        });

        IFC.events.on('force_user_management_list_update', self.update_user_list_in_place);

        IFC.events.on('user_unselected', function () {
            self.update({selected_user: undefined});
        });
    </script>
    <style scoped>
        nav {
            text-align: right;
        }

        .table {
            table-layout: fixed;
        }

        .table > tbody > tr > td,
        .table > tbody > tr > th,
        .table > tfoot > tr > td,
        .table > tfoot > tr > th,
        .table > thead > tr > td,
        .table > thead > tr > th {
            padding: 3px;
            vertical-align: middle;
        }

        .table td {
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
        }

        .highlight,
        tr.highlight > td {
            background-color: rgba(221, 237, 237, 1) !important;
        }

        .btn-sm {
            padding: 2px 5px;
            margin: 1px;
            opacity: 0.5;
        }

        .btn-sm:hover,
        .highlight .btn-primary.btn-sm {
            opacity: 1;
        }
    </style>
</user-table>

<user-form>
    <div class="well">
        <fieldset>
            <legend>User Account Info</legend>
        </fieldset>
        <form name="user_form" onsubmit="{ submit_user_form }">
            <div class="alert alert-danger" show="{ errors.non_field_errors }">
                { errors.non_field_errors }
            </div>

            <div class="row">
                 <div class="col-md-8">
                     <div class="form-group {has-error: errors.username}">
                        <label class="control-label">User name (will be set to your email address if left blank)</label>
                        <input name="username" type="text" class="form-control">
                        <span class="help-block" show="{ errors.username }">{ errors.username }</span>
                    </div>
                 </div>
            </div>

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

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.address_1}">
                        <label class="control-label">Address 1</label>
                        <input name="address_1" type="text" class="form-control">
                        <span class="help-block" show="{ errors.address_1 }">{ errors.address_1 }</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.address_2 }">
                        <label class="control-label">Address 2</label>
                        <input name="address_2" type="text" class="form-control">
                        <span class="help-block" show="{ errors.address_2 }">{ errors.address_2 }</span>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-4">
                    <div class="form-group {has-error: errors.city }">
                        <label class="control-label">City</label>
                        <input name="city" type="text" class="form-control">
                        <span class="help-block" show="{ errors.city }">{ errors.city }</span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group {has-error: errors.state}">
                        <label class="control-label">State</label>
                        <select name="state" class="form-control">
                            <option value="AL">Alabama</option>
                            <option value="AK">Alaska</option>
                            <option value="AZ">Arizona</option>
                            <option value="AR">Arkansas</option>
                            <option value="CA">California</option>
                            <option value="CO">Colorado</option>
                            <option value="CT">Connecticut</option>
                            <option value="DE">Delaware</option>
                            <option value="DC">District Of Columbia</option>
                            <option value="FL">Florida</option>
                            <option value="GA">Georgia</option>
                            <option value="HI">Hawaii</option>
                            <option value="ID">Idaho</option>
                            <option value="IL">Illinois</option>
                            <option value="IN">Indiana</option>
                            <option value="IA">Iowa</option>
                            <option value="KS">Kansas</option>
                            <option value="KY">Kentucky</option>
                            <option value="LA">Louisiana</option>
                            <option value="ME">Maine</option>
                            <option value="MD">Maryland</option>
                            <option value="MA">Massachusetts</option>
                            <option value="MI">Michigan</option>
                            <option value="MN">Minnesota</option>
                            <option value="MS">Mississippi</option>
                            <option value="MO">Missouri</option>
                            <option value="MT">Montana</option>
                            <option value="NE">Nebraska</option>
                            <option value="NV">Nevada</option>
                            <option value="NH">New Hampshire</option>
                            <option value="NJ">New Jersey</option>
                            <option value="NM">New Mexico</option>
                            <option value="NY">New York</option>
                            <option value="NC">North Carolina</option>
                            <option value="ND">North Dakota</option>
                            <option value="OH">Ohio</option>
                            <option value="OK">Oklahoma</option>
                            <option value="OR">Oregon</option>
                            <option value="PA">Pennsylvania</option>
                            <option value="PR">Puerto Rico</option>
                            <option value="RI">Rhode Island</option>
                            <option value="SC">South Carolina</option>
                            <option value="SD">South Dakota</option>
                            <option value="TN">Tennessee</option>
                            <option value="TX">Texas</option>
                            <option value="UT">Utah</option>
                            <option value="VT">Vermont</option>
                            <option value="VA">Virginia</option>
                            <option value="VI">Virgin Islands</option>
                            <option value="WA">Washington</option>
                            <option value="WV">West Virginia</option>
                            <option value="WI">Wisconsin</option>
                            <option value="WY">Wyoming</option>
                        </select>
                        <span class="help-block" show="{ errors.state }">{ errors.state }</span>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="form-group {has-error: errors.zip_code }">
                        <label class="control-label">Zip Code</label>
                        <input name="zip_code" type="text" class="form-control">
                        <span class="help-block" show="{ errors.zip_code }">{ errors.zip_code }</span>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.email}">
                        <label class="control-label">Email</label>
                        <input name="email" type="text" class="form-control">
                        <span class="help-block" show="{ errors.email }">{ errors.email }</span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.email_confirm}">
                        <label class="control-label">Confirm email</label>
                        <input name="email_confirm" type="text" class="form-control" onblur="{ check_email }">
                        <span class="help-block" show="{ errors.email_confirm }">{ errors.email_confirm }</span>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.password}">
                        <label class="control-label">
                            <span show="{ !editing }">Password</span>
                            <span show="{ editing }">NEW Password (optional)</span>
                        </label>
                        <input name="password" type="password" class="form-control">
                        <span class="help-block" show="{ errors.password }">
                            <ul show="{ errors.password.length> 1}">
                                <li each="{ error in errors.password }">{ error }</li>
                            </ul>
                            <span show="{ errors.password.length== 1}">{ errors.password }</span>
                        </span>
                    </div>
                </div>
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.password_confirm}">
                        <label class="control-label">Confirm password</label>
                        <input name="password_confirm" type="password" class="form-control">
                        <span class="help-block" show="{ errors.password_confirm }">
                            { errors.password_confirm }
                        </span>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-6">
                    <p>Please verify that the password entered meets the following guidelines:</p>
                    <ul>
                        <li>Minimum 8 characters</li>
                        <li>One number</li>
                        <li>One uppercase letter</li>
                        <li>One lowercase letter</li>
                    </ul>
                </div>
                <div class="col-md-6">
                    <div class="form-group {has-error: errors.role}">
                        <label class="control-label">User Role</label>
                        <select name="role" class="form-control">
                            <option each="{ IFC.constants.roles }" show="{ can_see_role(level) }" value="{ name }">{ name }</option>
                        </select>
                        <span class="help-block" show="{ errors.role }">{ errors.role }</span>
                    </div>

                    <div class="form-group {has-error: errors.can_approve}">
                        <div class="checkbox">
                            <label>
                                <input name="can_approve" type="checkbox"> Can Approve Orders
                            </label>
                        </div>
                    </div>

                    <div class="form-group {has-error: errors.spending_authority_amount}">
                        <label class="control-label">Spending Authority Amount</label>
                        <div class="input-group">
                            <span class="input-group-addon">$</span>
                            <input name="spending_authority_amount" type="number" class="form-control">
                        </div>
                        <span class="help-block" show="{ errors.spending_authority_amount }">{ errors.spending_authority_amount }</span>
                    </div>

                    <div class="form-group">
                        <label class="control-label">Spending allowance</label>
                        <div class="input-group">
                            <span class="input-group-addon">$</span>
                            <input type="number" class="form-control" disabled="disabled" value="{ selected_user.balance }">
                        </div>
                    </div>
                </div>
            </div>

            <div class="row" show="{ IFC.is_admin() }">
                <div class="col-md-12">
                    <div class="form-group {has-error: errors.companies}">
                        <label class="control-label">Company affiliation</label>
                        <!-- Have to inline style 100% width here for some reason, says select2 :) -->
                        <select name="companies" class="form-control" multiple="multiple" style="width: 100%;" onchange="{ company_selection_changed }">
                            <option each="{ IFC.state.companies }" value="{ id }">{ name }</option>
                        </select>
                        <span class="help-block" show="{ errors.companies }">{ errors.companies }</span>
                    </div>
                </div>
            </div>

            <div class="row">
                <div class="col-md-12">
                    <div class="form-group {has-error: errors.offices}">
                        <label class="control-label">
                            { IFC.state.user.company.office_title_name } affiliation
                            <button type="button" class="btn btn-sm btn-default" onclick="{ select_all_offices }">Select all</button>
                        </label>
                        <!-- Have to inline style 100% width here for some reason, says select2 :) -->
                        <select id="office_select" name="offices" class="form-control" multiple="multiple" style="width: 100%;">
                            <option each="{ offices }" value="{ id }">{ name }</option>
                        </select>
                        <span class="help-block" show="{ errors.offices }">{ errors.offices }</span>
                    </div>
                </div>
            </div>

            <input name="company" type="hidden" value="{ company.id }">

            <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 user</span>
                    </button>
                </div>
                <div class="col-md-6 text-right">
                    <input type="submit" class="btn btn-primary btn-lg" value="Add user" show="{ !editing }">
                    <input type="submit" class="btn btn-success btn-lg" value="Save user" show="{ editing }">
                </div>
            </div>
        </form>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Properties
         ----------------------------------------------------------------------------*/
        self.errors = {};
        self.editing = false;

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

        /* ----------------------------------------------------------------------------
         Component methods
        ----------------------------------------------------------------------------*/
        // Uncomment and use this whe multiple office is approved
        /*
        $(self.user_form.companies).on('select2:unselect', function (e) {
            const { id } = e.params.data;
            // console.log("Unselected company id", id);
            const activeOffices = self.offices.filter(item => item.company.id != id);
            const activeOfficesIds = activeOffices.map(item => item.id);
            // console.log("Active offices", activeOfficesIds);
            $(self.user_form.offices).val(activeOfficesIds).trigger('change');
            self.update({offices: activeOffices});
        });
        */

        self.can_see_role = function (level) {
            // Super users can see all roles, regular users can only see <= their role
            return IFC.is_admin() || IFC.state.user.role.level >= level;
        };

        self.clear_form = function () {
            $(':input', self.user_form)
                .not(':button, :submit, :reset, :hidden')
                .val('')
                .removeAttr('checked')
                .removeAttr('selected');
            self.role.value = IFC.constants.roles[0].name;  // Set role back to 'User' default
            // Have to reset select2 a special way
            $(self.user_form.companies).val(IFC.state.user.company.id).trigger('change');  // Start with current company selected
            $(self.user_form.offices).select2("val", "");

            // We don't want to accidentally keep these hidden IDs around, make sure
            // they are reset when form clears
            self.hidden_office_ids = [];

            if (self.editing) {
                // we're leaving edit mode so clear that and let everyone else know
                IFC.events.trigger('user_unselected');
                self.update({editing: false, selected_user: undefined});
            }
        };

        self.select_all_offices = function () {
            var office_ids = [];
            // console.log("Offices", self.offices)
            self.offices.forEach(function (office) {
                office_ids.push(office.id);
            });

            // `trigger('change')` is the key to making this work!
            $(self.user_form.offices).val(office_ids).trigger('change');
        };

        // Uncomment and use this whe multiple office is approved
        <!--  self.company_selection_changed = function (event) {
            // Get all offices filtered by which companies are selected
            var companies_selected = $(self.user_form.companies).val();
            // console.log("Companies selected", companies_selected)
            self.selected_companies = {
                company: companies_selected ? companies_selected : 0
            };
            // console.log("Request to send", self.selected_companies);
            if(self.selected_companies.company.length > 0){
                IFC.api.get_offices(self.selected_companies)
                    .success(function (data) {
                        /*
                        companies_selected = $(self.user_form.companies).select2('data')
                        if(companies_selected.length > 1) {
                            self.update({offices: null});
                        }
                        */
                        // To merge the two arrays, we need to make sure we don't have duplicates
                        // This is used to combine the offices of two companies
                        const mergedObj = [];
                        for (const obj of self.offices) {
                            if (!mergedObj.some((m) => m.id === obj.id)) {
                                mergedObj.push(obj);
                            }
                        }

                        for (const obj of data) {
                            if (!mergedObj.some((m) => m.id === obj.id)) {
                                mergedObj.push(obj);
                            }
                        }
                        self.update({offices: mergedObj});
                    })
                    .error(function () {
                        toastr.error("Error fetching offices");
                    });
            }    
        };  -->

        self.company_selection_changed = function (event) {
            // Get all offices filtered by which companies are selected
            var companies_selected = $(self.user_form.companies).val();
            var filters = {
                company: companies_selected ? companies_selected : 0
            };

            if(filters.company>0){
            IFC.api.get_offices(filters)
                .success(function (data) {
                    var companies_selected = $(self.user_form.companies).select2('data')
                    if(companies_selected.length > 1) {
                        self.update({offices: null});
                    }
                    self.update({offices: data});
                })
                .error(function () {
                    toastr.error("Error fetching offices");
                });
            }    
        };

        self.get_save_endpoint = function (payload) {
            if (self.editing) {
                return IFC.api.update_user(payload, self.selected_user.id);
            } else {
                return IFC.api.create_user(payload);
            }
        };

        self.check_email = function(){
            if (self.email.value != self.email_confirm.value) {
                self.errors.email_confirm = self.errors.email = "Emails do not match!";
                // toastr.error("Error submitting user form");
                self.update({errors: self.errors});
                return false;
            }else{
                self.errors.email_confirm = self.errors.email = "";
                self.update({errors: self.errors});
            }

            if ((!self.username || !self.username.length)){
                self.user_form.username = self.email.value;
                $('[name=username]').val(self.email.value)
            }
        };

        self.submit_user_form = function () {
            // Check email and password confirmations first
            if (self.password.value != self.password_confirm.value) {
                self.errors.password_confirm = self.errors.password = ["Passwords do not match!"];
                toastr.error("Error submitting user form");
                self.update({errors: self.errors});
                return false;
            }
            if (self.email.value != self.email_confirm.value) {
                self.errors.email_confirm = self.errors.email = "Emails do not match!";
                toastr.error("Error submitting user form");
                self.update({errors: self.errors});
                return false;
            }

            if ((!self.username || !self.username.length)){
                self.user_form.username = self.email.value;
            }

            var payload = $(self.user_form).serializeFormToObject();

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

            // Uncomment and use this whe multiple office is approved
            /*
            if(!payload.hasOwnProperty('offices')) {
                payload.offices = self.offices.map(item => item.id.toString());
            } else {
                payload.offices = payload.offices instanceof Array ? payload.offices : [payload.offices];
            }
            */

            // Original method. This was causing issues with the office selection
            if (payload.offices) {
                payload.offices = payload.offices instanceof Array ? payload.offices : [payload.offices];
            }

            // Add offices we had to hide from the user
            if(self.hidden_office_ids) {
                self.hidden_office_ids.forEach(function (id) {
                    payload.offices.push(id);
                });
            }

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

            self.get_save_endpoint(JSON.stringify(payload))
                .success(function (data) {
                    if (!self.editing) {
                        toastr.success("User created!");
                    } else {
                        toastr.success("User saved!");
                    }

                    self.clear_form();
                    self.update({errors: undefined});
                    IFC.events.trigger('force_user_management_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 user form");
                });
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('profile_received', function() {
            // Puts form in nice state, selects company and such
            self.clear_form();
        });

        IFC.events.on('office_selected', function () {
            self.clear_form();
        });

        IFC.events.on('offices_updated', function (offices) {
            self.update({offices: offices});
        });

        IFC.events.on('company_selected', function (company) {
            self.update({company: company});
        });

        IFC.events.on('user_selected', function (user) {
            self.update({errors: {}, editing: true, selected_user: user});

            // Set most fields
            Object.keys(user).map(function (value, index) {
                if(self.user_form[value]) {
                    self.user_form[value].value = user[value];
                }
            });

            Object.keys(user.address).map(function (value, index) {
                if(self.user_form[value]) {
                    self.user_form[value].value = user.address[value];
                }
            });

            // Save offices selected user started with that we don't have
            // (if we're not admins, which can access every office)
            if(!IFC.is_admin()) {
                // start our list out with all hidden ids, then we'll remove the ones that we have
                self.hidden_office_ids = user.offices.map(function(o) { return o.id; });
                var our_office_ids = IFC.state.user.offices.map(function(o) { return o.id; });

                self.hidden_office_ids = self.hidden_office_ids.filter(function(id) {
                    // Remove ones we have
                    return our_office_ids.indexOf(id) === -1;
                });
            }

            // Extras like confirm email/office affiliation
            self.user_form.can_approve.checked = user.can_approve;
            self.user_form.email_confirm.value = user.email;
            self.user_form.role.value = user.role.name;

            // Load select fields
            var company_ids = [];
            user.companies.forEach(function (company) {
                company_ids.push(company.id);
            });
            var office_ids = [];
            user.offices.forEach(function (office) {
                if(self.hidden_office_ids.indexOf(office.id) !== -1) {
                    // this is a hidden office, skip it!
                    return;
                }
                office_ids.push(office.id);

                // Offices might not be loaded yet so we can't select this office
                // so if it's not loaded yet add it to our offices list temporarily
                // (we will get all available offices after IFC.get_offices call)
                var found_office = false;
                self.offices.forEach(function(office_in_selector){
                    if(office_in_selector.id == office.id) {
                        found_office = true;
                    }
                });
                if(!found_office){
                    self.offices.push(office)
                }
            });

            // `trigger('change')` is the key to making select2 val updating work!
            $(self.user_form.companies).val(company_ids).trigger('change');
            $(self.user_form.offices).val(office_ids).trigger('change');

            // Let's fill the office selector based on companies we have now by calling
            // company changed selection event
            //self.company_selection_changed();
        });
    </script>
</user-form>
