<product-detail>
    <loader trigger="product_detail_load" auto_start_loading="false"></loader>

    <!--<div show="{ !style }">
        <i>Select a style before you can view product details!</i>
    </div>-->
    <div show="{ !office }">
        <i>Select an office to view product details!</i>
    </div>

    <div show="{ style && office }">
        <div class="row">
            <div class="col-sm-6">
                <h3>{ style.name }</h3>

                <form name="style_form">
                    <dl>
                        <dt>Item number</dt>
                        <dd>{ style.ecometry_style_id }</dd>

                        <dt>Price</dt>
                        <dd show="{ IFC.state.perms.can_view_prices }">
                            <price amount="{ style.min_price }"></price> - <price amount="{ style.max_price }"></price>
                        </dd>
                        <dd show="{ !IFC.state.perms.can_view_prices }">****</dd>
                        <!--<dd>${ current_sku.price }</dd>-->

                        <dt>Description</dt>
                        <dd name="long_description_element"></dd>

                        <virtual show="{ style.specifications }">
                            <dt>Specifications</dt>
                            <dd name="specifications_element"></dd>
                        </virtual>

                        <!--  Quantity doesn't mean anything until we have a SKU???

                        <dt>Quantity</dt>
                        <dd></dd>
                        -->
                        <dt>Quantity</dt>
                        <dd>
                            <input name="quantity" type="number" class="form-control" oninput="{ form_updated }" min="0" value="1">
                            <span>{ current_sku.inventory_message }</span>
                        </dd>

                        <virtual show="{ style.option_1 }">
                            <dt show="{ style.option_1 }">{ style.option_1.label }</dt>
                            <dd>
                                <select name="option_selector_1" id="option_selector_1" class="form-control" onchange="{ form_updated }">
                                    <option>-----</option>
                                    <option each="{ option_choices[1] }" value="{ value }" selected="{ selected }">{ label }</option>
                                </select>
                            </dd>
                        </virtual>
                        <virtual show="{ style.option_2 }">
                            <dt show="{ style.option_2 }">{ style.option_2.label }</dt>
                            <dd>
                                <select name="option_selector_2" class="form-control" disabled="{ option_selections.option_1 == '-----' }" onchange="{ form_updated }">
                                    <option>-----</option>
                                    <option each="{ option_choices[2] }" value="{ value }" selected="{ selected }">{ label }</option>
                                </select>
                            </dd>
                        </virtual>
                        <virtual show="{ style.option_3 }">
                            <dt>{ style.option_3.label }</dt>
                            <dd>
                                <select name="option_selector_3" class="form-control" disabled="{ option_selections.option_2 == '-----' }" onchange="{ form_updated }">
                                    <option>-----</option>
                                    <option each="{ option_choices[3] }" value="{ value }" selected="{ selected }">{ label }</option>
                                </select>
                            </dd>
                        </virtual>
                        <extra-customization each="{ style.extra_customizations }"></extra-customization>
                    </dl>
                </form>
                <button class="btn btn-default" onclick="{ show_customization_modal }"
                        show="{ IFC.state.default_customizations() !== 'forced' }">Manage add ons</button>
                <add-on-modal available_add_ons="{ style.add_ons }"></add-on-modal>
            </div>
            <div class="col-sm-6">
                <product-image-viewer-main images="{ detail_images }" selected_image="{ selected_image }"></product-image-viewer-main>

                <product-image-viewer-size images="{ sizing_images }"></product-image-viewer-size>
            </div>
        </div>

        <div class="row">
            <div class="col-md-12">
                <table class="table table-responsive">
                    <thead>
                    <tr>
                        <th></th>
                        <th>Quantity</th>
                        <th>Details</th>
                        <th>Price</th>
                        <th>Extended Price</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td>
                            <a class="product-zoom-image" href="{ selected_image ? selected_image.zoomed_url : default_image.zoomed_url }">
                                <img class="current_selected_image" src="{ selected_image ? selected_image.thumbnail_url : default_image.thumbnail_url }">
                            </a>
                        </td>
                        <td><strong>{ quantity.value }</strong></td>
                        <td>
                            <virtual show="{ style.option_1 }">
                                <dt>{ style.option_1.label }</dt>
                                <dd>{ option_selections.option_1 }</dd>
                            </virtual>
                            <virtual show="{ style.option_2 }">
                                <dt>{ style.option_2.label }</dt>
                                <dd>{ option_selections.option_2 }</dd>
                            </virtual>
                            <virtual show="{ style.option_3 }">
                                <dt>{ style.option_3.label }</dt>
                                <dd>{ option_selections.option_3 }</dd>
                            </virtual>
                        </td>

                        <td>
                            <price amount="{ product_price_no_customizations.toFixed(2) }" class="black"></price>
                        </td>
                        <td>
                            <price amount="{ (product_price_no_customizations * parseInt(quantity.value)).toFixed(2) }" class="black"></price>
                        </td>

                    </tr>
                    <tr each="{ selected_add_ons }" class="add-on">
                        <td colspan="2">
                            <a class="product-zoom-image" href="{ images[0].zoomed_url }">
                                <img class="add-on-thumbnail" src="{ images[0].thumbnail_url }">
                            </a>
                        </td>
                        <td colspan="1">
                            <strong>{ name }</strong><br>

                            <!-- For embroidery add ons -->
                            <virtual show="{ add_on_type == 'Embroidery' }">
                                <i>(one name per line)</i>
                                <textarea class="form-control" onkeyup="{ add_on_extra_details_changed }"></textarea>
                            </virtual>

                            <!-- For extra customizations -->
                            <extra-customization each="{ extra_customizations }"></extra-customization>

                        </td>
                        <td>
                            <price amount="{ price > 0 ? parseFloat(price).toFixed(2) : '' }" show_free="true" class="black"></price>
                        </td>
                        <td>
                            <price amount="{ (price * parseInt(quantity.value)).toFixed(2) }" show_free="true" class="black"></price>
                        </td>
                    </tr>
                    <tr>
                        <td class="text-right" colspan="4"><strong>Total price:</strong></td>
                        <td>
                            <price amount="{ current_total_price }"></price>
                        </td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>

        <button class="btn btn-lg btn-success pull-right" onclick="{ add_to_cart }">
            Add to Cart
        </button>
    </div>

    <script>
        var self = this;
        // console.log(this)

        /* ----------------------------------------------------------------------------
         Tag properties
         ----------------------------------------------------------------------------*/
        self.option_choices = {};
        self.option_selections = {};


        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one("mount", function () {
            // Use "event delegation" to apply zoom popups for ajax loaded html
            $('product-detail').magnificPopup({
                delegate: 'a.product-zoom-image',
                type: 'image'
            });
        });
        self.on("update", function () {
            // console.log(this)
            // Here it is mounted
        })


       /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.form_updated = function () {
            self.update_options();
            self.update_selected_image();
            self.update_total_price();
            self.form_is_valid = self.get_form_is_valid(false);
            self.update();
        };

        self.get_option_value = function (option_number) {
            var option = self['option_selector_' + option_number];
            // ----- is the default value in the selections, ignore those
            //var value = option.value && option.value !== '-----' ? " " + option.value : '';
            var value = "";
            if(option.value && option.value !== '-----') {
                value = option.value;
                if(value != "" && value < 10) {
                    // Prepend single digits with a 0
                    //value = '0' + value;
                    value = ('0' + value).slice(-2)
                }
                value = " " + value;
                // "Here change the color from the selector"
                // console.log("val"+value);
            }
            return value;
        };

        self.get_option_string = function () {
            // Returns the end of sku, i.e. 1750 BLK NL ZZ where BLK NN ZZ is the part this generates
            return [1, 2, 3].reduce(function (previous, current) {
                return previous + self.get_option_value(current);
            }, '');
        };

        // called by form_updated, which updates
        self.update_options = function (event) {
            [1, 2, 3].forEach(function (i) {
                // Helpers to get selection values, so we can print self.option_selections['option_1']
                var selector = self['option_selector_' + i];
                if(selector.selectedIndex < 0) { return; }
                self.option_selections['option_' + i] = selector[selector.selectedIndex].text;

                // Filter skus that don't have the previous option (all skus have to have pricing!)
                var filtered_skus = self.style.skus.filter(function(sku) {
                    return sku.price && sku.price != '';
                });

                // Get previous option IF it exists
                var previous_option = self['option_selector_' + (i - 1)] ? self['option_selector_' + (i - 1)].value : undefined;
                if(previous_option && previous_option != '-----') {
                    // Filter skus that dont have the previous option
                    filtered_skus = filtered_skus.filter(function(sku) {
                        return sku['option_' + (i - 1)].value == previous_option;
                    });
                }

                // Loop over the remaining skus, add any options available
                self.option_choices[i] = [];
                filtered_skus.forEach(function(sku) {

                    if(sku['option_' + i]) {
                        // Make sure option isn't already a choice
                        var does_exist = self.option_choices[i].filter(function(c) {
                            return c.id == sku['option_' + i].id;
                        });
                        if(does_exist.length == 0) {
                            self.option_choices[i].push(sku['option_' + i]);
                        }
                    }
                });

                // Sort by ranking from ecometry
                self.option_choices[i].sort(function(a, b){
                    return a.rank - b.rank;
                });
            });

            // Filter out the images for color options which are not available
            var color_options = self.option_choices[1];
            if(Number(self.style.color_option_number) == 2){
                color_options = self.option_choices[2];
            } else if (Number(self.style.color_option_number) == 3){
                color_options =self.option_choices[3];
            }
  //          if(color_options.length == 1){
  //             var opt = document.getElementById("option_selector_1").options[0];
  //            console.log('opt',opt)
  //              if(opt != 'undefined' && opt.value == '-----'){
  //                  console.log("here");
  //                 opt.remove();
  //            }
  //       }
            // console.log('color_options',color_options)
            var temp_detail_images = self.detail_images.slice();
            for(var c = temp_detail_images.length -1; c >= 0 ; c--){
                var itemfound = false;
                for (var d = 0; d < color_options.length; d++) {
                    if(color_options[d].value == temp_detail_images[c].pointer || temp_detail_images[c].pointer == "#default") {
                        itemfound = true;
                        break;
                    }
                }

                if(!itemfound){
                    self.detail_images.splice(c, 1);
                }

            }

            // Tie our option string to ecometry_style_id, so we get
            // "1750" + " BLK NL ZZ" for example
            var sku = self.style.ecometry_style_id + self.get_option_string();

            self.current_sku = self.style.skus.filter(function (product) {
                return product.sku === sku;
            })[0];
        };

        // called by form_updated, which updates
        self.update_total_price = function () {
            if (!self.current_sku) {
                // Don't have all options selected yet, bail!
                self.product_price_no_customizations = '';
                self.current_total_price = '';
                return;
            }

            self.current_total_price = 0;

            // Add all prices of add ons
            if (self.selected_add_ons && self.selected_add_ons.length > 0) {
                self.selected_add_ons.forEach(function (add_on) {
                    if(add_on.price) {
                        self.current_total_price += parseFloat(add_on.price);
                    }
                });
            }

            // Get price of item
            var product_price = parseFloat(self.current_sku.price);

            self.product_price_no_customizations = product_price;
            self.current_total_price += product_price;

            var qty = parseInt(self.quantity.value);
            self.current_total_price = (self.current_total_price * qty).toFixed(2);
        };

        // called by form_updated, which updates
        self.update_selected_image = function () {
            if (!self.style) {
                return undefined;
            }
            var color = self['option_selector_' + self.style.color_option_number].value;
            var selected_image = undefined;
            var first_default_image = undefined;
            var first_default_image = undefined;
            if(self.style.images.length > 0){
                first_default_image = self.style.images[1]
            }
            self.style.images.forEach(function (image) {

                //if(image.is_default && typeof first_default_image == "undefined" && ){
                // console.log("image",image)
                //    first_default_image = image;
                //}
                if (image.pointer == color) {
                    selected_image = image;
                }
            });
            if(typeof selected_image == "undefined"){
                selected_image = first_default_image;
            }
            self.selected_image = selected_image;
        };

        self.get_form_is_valid = function (toast_errors) {
            var quantity = parseInt(self.quantity.value);
            // WORKINGON
            var textarea = document.querySelector("textarea");

            // Check if all options are selected, giving us a valid SKU
            if (self.current_sku === undefined || !self.current_sku) {
                if (toast_errors) {
                    var labels = self.style.option_1 ? ' - ' + self.style.option_1.label + '<br>' : '';
                    labels += self.style.option_2 ? ' - ' + self.style.option_2.label + '<br>' : '';
                    labels += self.style.option_3 ? ' - ' + self.style.option_3.label + '<br>' : '';
                    toastr.error('Please fill in all options for this product: <br>' + labels);
                }
                return false;
            }

            // Check quantity IF the item is status C1 aka item discontinued
            if (self.current_sku.status == 'C1') {
                if (self.current_sku.inventory_count == 0 || quantity > self.current_sku.inventory_count) {
                    if (toast_errors) {
                        toastr.error("Cannot purchase this product, not enough available!")
                    }
                    return false;
                }
            }

            // Check all add ons for proper custom fields
            if (self.selected_add_ons && self.selected_add_ons.length > 0) {
                // Make sure addon quantity exists
                var add_ons_without_enough_quantity = self.selected_add_ons.filter(function(add_on){
                    return add_on.status == 'C1' && (add_on.inventory_count == 0 || quantity > add_on.inventory_count);
                });
                if (add_ons_without_enough_quantity > 0) {
                    if (toast_errors) {
                        var add_on_string = add_ons_without_enough_quantity.map(function(i) {
                            return "<strong>" + i.name + "</strong>";
                        }).join("<br>");
                        toastr.error("Cannot purchase these add ons, not enough available:<br><br>" + add_on_string);
                    }
                    return false;
                }

                // Make sure the fields have any data at all, if we have them (type of Embroidery or add on has extra_customizations)
                var add_ons_missing_extra_detail = self.selected_add_ons.filter(function (add_on) {
                    if(add_on.add_on_type == 'Embroidery') {
                        return add_on.extra_details === '' || add_on.extra_details == undefined;
                    }
                    if(add_on.extra_customizations.length > 0) {
                        var missing_customizations = add_on.extra_customizations.filter(function(customization) {
                            // If value hasn't been set yet, or value is nothing
                            return !customization.value || customization.value.content == '';
                        });
                        return missing_customizations.length > 0;
                    }
                });
                if (add_ons_missing_extra_detail.length > 0) {
                    // Some add on is missing something, not valid!
                    if (toast_errors) {
                        var add_on_string = add_ons_missing_extra_detail.map(function(i) {
                            return "<strong>" + i.name + "</strong>";
                        }).join("<br>");
                        toastr.error("Please fill in all extra details for the product add ons:<br>" + add_on_string);
                    }
                    return false;
                }

                // Make # of embroidery messages match quantity
                var add_ons_without_enough_messages = self.selected_add_ons.filter(function (add_on) {
                    return add_on.add_on_type == 'Embroidery' && add_on.extra_details.split('\n').length !== parseInt(self.quantity.value);
                });
                if(add_ons_without_enough_messages.length > 0) {
                    if (toast_errors) {
                        toastr.error('Make sure all embroidery add ons have ' + self.quantity.value + ' messages, separated by new lines');
                    }
                    return false;
                }
            }

            // Make sure office is selected, although we should never get this error!
            if (!IFC.state.office || IFC.state.office.id == '') {

                if (toast_errors) {
                    toastr.error('You must select an office before you can add a product to the cart.')
                }
                return false;
            }
            
            // Make sure there are less than 700 items in cart
            if (IFC.state.user.cart_quantity > 699) {

                if (toast_errors) {
                    toastr.error('Your cart is full.')
                }
                return false;
            }

            // If we made it this far without returning, form is valid!
            return true;
        };

        self.show_customization_modal = function () {
            $('#customization_modal').modal('show');
        };

        self.clear_form = function() {
            // Remove add ons
            self.selected_add_ons = undefined;

            // Reset quantity
            self.quantity.value = 1;

            // Reset options 1 2 3
            [1, 2, 3].forEach(function(i){
                var selector = self['option_selector_' + i];
                if(selector) {
                    selector.value = '-----'
                }
            });

            // Reset extra customizations
            $('extra-customization textarea').val('');
            $('#add_recipient_prompt').val(self.recipient_name);
            $('extra-customization select').val('-----');

            self.form_updated();
        };

        self.add_to_cart = function () {
            if (!self.get_form_is_valid(true)) {
                return;
            }

            //Check if add_recipient_prompt recipient name is set
            recipient_prompt_fail = false
            if(IFC.state.user.company.add_recipient_prompt) {
                self.style.extra_customizations.forEach(function (customization) {
                    if (customization.id < 0) {
                        if (customization.value.content == null || customization.value.content.trim() == '') {
                            toastr.error("The Recipient name is required!");
                            recipient_prompt_fail = true;
                        }
                    }
                });
            }
            if(recipient_prompt_fail){
                return;
            }

            var payload = {};

            payload.product = self.current_sku.id;
            payload.quantity = self.quantity.value;

            // Add extra customizations manually, they don't have form names
            var set_recipient_name = "";
            payload.extra_customizations = [];
            self.style.extra_customizations.forEach(function (customization) {
                if(customization.id < 0){
                    if(customization.value.content != null) {
                        set_recipient_name = customization.value.content;
                    }else{
                        set_recipient_name = '';
                    }
                }

                payload.extra_customizations.push({
                    title: customization.title,
                    value: customization.value.content
                });
            });
            //if add_recipient_prompt is true get last extra_customization recipient_name
            if(IFC.state.user.company.add_recipient_prompt) {
                if (typeof(Storage) !== "undefined") {
                    // Store the last set recipient name
                    sessionStorage.setItem("recipient_name", set_recipient_name);
                    self.recipient_name = set_recipient_name;
                }
            }

            // Add ons
            if (self.selected_add_ons) {
                payload.add_ons = [];

                self.selected_add_ons.forEach(function (add_on) {
                    var extra_customizations = [];
                    add_on.extra_customizations.forEach(function (customization) {
                        extra_customizations.push({
                            title: customization.title,
                            value: customization.value.content
                        });
                    });

                    payload.add_ons.push({
                        product: add_on.id,
                        extra_details: add_on.extra_details,  // extra details holds embroidery stuff
                        extra_customizations: extra_customizations  // any other customization data
                    })
                });
            }

            // Set the office
            payload.office = IFC.state.office.id;

            // READY TO SEND TO CART WOOO!
            IFC.api.add_to_cart(JSON.stringify(payload))
                .success(function () {
                    toastr.success("Added to shopping cart!");

                    // Reset detail selections
                    self.clear_form();

                    // Update cart on top nav by re-fetching profile
                    IFC.get_profile();
                })
                .error(function (errors) {
                    if (errors) {
                        var data = JSON.parse(errors.responseText);
                        var msg = data.error || data.non_field_errors;
                        // Our message is in another format, like {"quantity": "Bad quantity!"} so print that nicely
                        if(!msg) {
                            msg = "";
                            Object.keys(data).forEach(function(key){
                                var value = data[key] instanceof Array ? data[key][0] : data[key];
                                msg += "<strong>" + key + " -</strong> " + value + "\n";
                            });
                        }
                        toastr.error(msg);
                    } else {
                        toastr.error("Could not add item to shopping cart!");
                    }
                })
                .complete(function(){
                    // Reset auto adding add-ons
                    if(IFC.state.default_customizations() !== "optional"){
                        IFC.events.trigger('auto_set_add_ons');
                    }
                });
        };

        self.add_on_extra_details_changed = function (event) {
            this._item.extra_details = event.target.value;
            self.form_updated();
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        // This is only fired for admins! This triggers filling the options
        IFC.events.on('office_selected', function (office) {
            if (!office || office.id === "") {
                self.update({office: undefined});
                return;
            } else {
                self.office = office;
            }

            IFC.start_loader('product_detail_load');

            IFC.api.get_style_detail(self.opts.product_pk, IFC.state.user.company.id, office.id)
                .success(function (style) {
                    // Set description HTML insides (otherwise it'd be plain text, not processed HTML)
                    self.long_description_element.innerHTML = style.long_description;
                    self.specifications_element.innerHTML = style.specifications;

                    // Pick first default image
                    /*get_default_image(style.images)*/

                    // Assign images if available
                    var detail_images = style.images.filter(function (image) {
                        return image.pointer != '#sizing';
                    });
                    var sizing_images = style.images.filter(function (image) {
                        return image.pointer == '#sizing';
                    });
                    var default_image = undefined;
                    style.images.forEach(function (image) {
                        if (image.is_default) {
                            default_image = image;
                            return false;
                        }
                    });

                    // Set default img if none found
                    default_image = default_image || style.images[0];

                    // First save style to update selectors and such for color option grabbing
                    self.update({
                        style: style,
                        detail_images: detail_images,
                        sizing_images: sizing_images,
                        default_image: default_image
                    });

                    //if add_recipient_prompt is true add a new extra_customization by hand
                    if(IFC.state.user.company.add_recipient_prompt) {
                        var recipient_name = "";
                        if (typeof(Storage) !== "undefined") {
                            // Retrieve last stored name
                            self.recipient_name = sessionStorage.getItem("recipient_name");
                            if(self.recipient_name == null){
                                self.recipient_name = '';
                            }
                        }
                        self.style.extra_customizations.push({
                            id: -1,
                            title: 'Recipient',
                            content: self.recipient_name
                        });
                    };

                    // Then change selected image/prices
                    self.form_updated();

                    if(IFC.state.default_customizations() !== "optional"){
                        IFC.events.trigger('auto_set_add_ons');
                    }

                    // Stop loading spinner
                })
                .error(function () {
                    toastr.error("Could not get product detail!");
                })
                .always(function() {
                    IFC.end_loader('product_detail_load');
                    $('select[name=option_selector_1]').trigger('change');
                    $('select[name=option_selector_2]').trigger('change');
                    $('select[name=option_selector_3]').trigger('change');
                    // Here it is updated depending on the select
                });
        });

        IFC.events.on("thumbnail_selected", function (image) {
            self.selected_image = image;
            self.update();
        });

        IFC.events.on('add_ons_saved', function (add_ons) {
            self.selected_add_ons = add_ons;
            //self.update();  // update fired from form_updated for us
            self.form_updated();
        });
    </script>
    <style scoped>
        dt {
            margin-top: 10px;
        }

        .table {
            margin-top: 20px;
        }

        input[type="number"] {
            width: 75px;
            display: inline-block;
        }

        .add-on {
            background-color: rgba(100, 100, 250, 0.08);
        }

        .add-on-thumbnail {
            max-height: 42px;
            float: right;
        }
    </style>
</product-detail>

<product-image-viewer-main>
    <div class="thumbnails_wrapper">
        <!-- If we have a selected image -->
        <a class="product-zoom-image" href="{ selected_image.zoomed_url }" show="{ selected_image }">
            <img class="current_selected_image" src="{ selected_image.detail_url }">
        </a>

        <!-- We don't have selected image, just grab the first if we have it -->
        <a class="product-zoom-image" href="{ opts.images.length > 0 && opts.images[1].zoomed_url }" show="{ !opts.selected_image }">
            <img class="current_selected_image" src="{ opts.images.length > 0 && opts.images[1].detail_url }">
        </a>

        <ul class="thumbnail_selector" show="{ opts.images.length > 1 }">
            <li each="{ opts.images }">
                <img src="{ thumbnail_url }" onclick="{ select_thumbnail }">
            </li>
        </ul>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("update", function () {
            // We need to keep track of which image is selected, we just get
            // first default image from opts, but this could change from options changing
            // or something
            // console.log("optsssssssssssssss",self.opts)
            if(self.opts.images != undefined && self.selected_image == undefined){
                self.selected_image = self.opts.images[0];
            }

        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.select_thumbnail = function (event) {
            // Here change the color in the color select. Under Quantity input
            IFC.events.trigger('thumbnail_selected', event.item);
            IFC.events.trigger('change_select_from_selected', event.item);
        };


        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on("thumbnail_selected", function (image) {
            self.selected_image = image;
        });

        IFC.events.on("change_select_from_selected", function (image) {
            // Here puts the color in the details table. Right to Quantity label
            const selectEl = document.getElementById('option_selector_1');
            selectEl.value = image.pointer; // Set the value of the select element
            $('select[name=option_selector_1]').trigger('change');
        });
    </script>
    <style scoped>
        .thumbnails_wrapper {
            margin-top: 20px;
            text-align: center;
        }

        .current_selected_image {

        }

        .thumbnail_selector {
            margin: 2px;
            padding: 2px;
            border: 1px solid rgba(0, 0, 0, 0.25);
            list-style-type: none;
            text-align: left;
            /*display: flex;

            flex-wrap: wrap;
            flex-direction: row;
            align-items: left;
            justify-content: left;*/
            /*flex-flow: row wrap;
            justify-content: space-between;*/
        }

        /*.thumbnail_selector:after {
          content: "";
          flex: auto;
        }*/

        .thumbnail_selector li {
            display: inline-block;
            margin: 2px;
            /*display: inline-block;*/
            /*margin-right: 20px;*/
            /*flex: 1 0 42px;*/
        }

        .thumbnail_selector img:hover {
            cursor: pointer;
            border: 1px solid rgba(100, 100, 250, 0.75);
            -moz-box-sizing: border-box;
            -webkit-box-sizing: border-box;
            box-sizing: border-box;
        }

        .thumbnail_selector img {
            border: 1px solid rgba(100, 100, 250, 0.25);
            width: 42px;
        }

        img.selected {
            border: 1px solid rgba(100, 100, 255, 1);
        }
    </style>
</product-image-viewer-main>

<product-image-viewer-size>
    <div class="size_thumbnails_wrapper">
        <!-- If we have a selected image -->
        <a class="product-zoom-image" href="{ selected_image.zoomed_url }" show="{ selected_image }">
            <img class="current_selected_image" src="{ selected_image.detail_url }">
        </a>

        <!-- We don't have selected image, just grab the first if we have it -->
        <a class="product-zoom-image" href="{ opts.images.length > 0 && opts.images[1].zoomed_url }" show="{ !opts.selected_image }">
            <img class="current_selected_image" src="{ opts.images.length > 0 && opts.images[1].detail_url }">
        </a>
    </div>
    <script>
        const self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("update", function () {
            if(self.opts.images != undefined){
                self.selected_image = self.opts.images[0];
            }
        });
    </script>
    <style scoped>
        .size_thumbnails_wrapper {
            margin-top: 20px;
            text-align: center;
        }
        .current_selected_image {

        }

        img.selected {
            border: 1px solid rgba(100, 100, 255, 1);
        }
    </style>
</product-image-viewer-size>

<add-on-modal>
    <div class="modal fade" id="customization_modal" tabindex="-1" 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">Customizations</h4>
                </div>
                <form name="customization_selection_form">
                    <div class="modal-body">
                        <i show="{ opts.available_add_ons.length == 0 }">No add ons available for this style and office combination!</i>
                        <add-on-check-box each="{ opts.available_add_ons }"></add-on-check-box>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default btn-lg" data-dismiss="modal">Close</button>

                        <input type="button" class="btn btn-success btn-lg" value="Save" onclick="{ save_add_ons }"
                               show="{ opts.available_add_ons.length > 0 }">
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("update", function () {
            self.selected_image = self.opts.selected_image;
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.save_add_ons = function () {
            var add_on_ids = $(self.customization_selection_form).serializeFormToObject().add_ons;

            var add_ons = undefined;

            if (add_on_ids && add_on_ids.length > 0) {
                add_ons = self.opts.available_add_ons.filter(function (add_on) {
                    // convert id to string and compare
                    return add_on_ids.indexOf("" + add_on.id) !== -1;
                });
            }
            IFC.events.trigger('add_ons_saved', add_ons);
            $('#customization_modal').modal('hide');
        };


        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
         IFC.events.on('auto_set_add_ons', function () {
             self.save_add_ons();
         });

    </script>
    <style scoped>

    </style>
</add-on-modal>

<add-on-check-box>
    <div>
        <div class="row">
            <div class="col-md-2">
                <a class="product-zoom-image" href="{ image.zoomed_url }">
                    <img class="thumbnail" src="{ image.thumbnail_url }">
                </a>
            </div>
            <div class="col-md-10">
                <div class="pull-right">
                    <price amount="{ price }" show_free="true"></price>
                </div>

                <strong>{ name }</strong> <br>

                <span name="rendered_description"></span>

                <div class="form-group text-right">
                    <div class="checkbox">
                        <label>
                            <input name="add_ons" type="checkbox" value="{ id }"
                                   checked="{ IFC.state.default_customizations() !== 'optional' && !is_optional_type }">
                            Select this add on?
                        </label>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.on("update", function () {
            self.image = get_default_image(self.images);
            self.rendered_description.innerHTML = self.description;
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/


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

    </script>
    <style scoped>
        :scope {
            display: block;
            border: 1px solid #52a0bc;
            padding: 10px;
            margin: 5px;
        }

        .thumbnail {
            max-width: 64px;
        }
    </style>
</add-on-check-box>

<extra-customization>
    <dt>{ title }</dt>
    <dd>
        <!-- This customization has some options, display them instead of allowing free text input -->
        <select show="{ content && content != '' && id > 0 }" class="form-control" onchange="{ updated_customization }">
            <option>-----</option>
            <option each="{ option in content.split(',') }">{ option }</option>
        </select>
        <!-- This customization has no content, so allow user to input data -->
        <textarea maxlength="50" rows="1" id="txt" onKeyUp=checktxt() show="{ !content && id >= 0 }" class="form-control" onchange="{ updated_customization }"></textarea>
        <div style="color:red;" id="warning-txt"></div>
        <!-- This customization has no content, so allow user to input data -->
        <textarea maxlength="50" rows="1" id="add_recipient_prompt" onKeyUp=checkrecipient() show="{ id < 0 }" class="form-control" onchange="{ updated_customization }">{ content }</textarea>
        <div style="color:red;" id="warning-recipient"></div>
    </dd>

    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one("updated", function () {
            // Set our default values if we have any
            var content_values = self.content != undefined && self.content.split(',');
            self._item.value = {
                title: self.title,
                // Used to set default value here, let's just keep it blank though, as
                // customizations are not required
                content: ''//content_values.length > 0 ? content_values[0] : ''
            };
            if(self.id == -1){
                self._item.value = {
                    title: self.title,
                    content: self.content
                };
            }
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.updated_customization = function (event) {
            self._item.value = {
                title: self.title,
                content: event.target.value
            };
        };
        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
    </script>
    
</extra-customization>
