<shopping-cart>
    <div show="{ is_cart_empty }">
        <h3>Cart empty</h3>
        <i>Nothing in your cart, keep shopping!</i>
    </div>

    <!-- We can show as soon as we have an office, that means cart was received -->
    <div show="{ office }">
        <h3>Order for { office.name }</h3>

        <div style="text-align: right; padding-right: 10%;" show="{ cart.buyer.id != cart.originator.id }">
            Original Buyer:
            { cart.originator.first_name } { cart.originator.last_name } ({ cart.originator.username })
            <a href="mailto:{ cart.originator.email }" target="_top" show="{ cart.originator.email }">
                &nbsp;&nbsp;<i class="pull-right glyphicon glyphicon-envelope"></i>
            </a>
        </div>
        <div style="text-align: right; padding-right: 10%;">
            Cart Comments: { cart.comments }
        </div>

        <!-- NOTE: I use no-reorder here so when we update the cart items they don't jitter/flash -->
        <ppp-item each="{ id, pack in packs_per_person }" no-reorder></ppp-item>

        <br/>

        <cart-item each="{ regular_products }" no-reorder></cart-item>

        <!-- this is in a table to line up nicely with the other totals -->
        <div class="order-total">
            <table class="table table-responsive">
                <thead>
                <tr>
                    <th></th>
                    <th></th>
                    <th></th>
                    <th></th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td class="order-total-label" colspan="3">
                        Order Total
                    </td>
                    <td class="price" width="170px">
                        <price amount="{ cart.subtotal }"></price>
                    </td>
                </tr>
                </tbody>
            </table>
        </div>

        <div class="text-right">
            <button class="btn btn-default btn-lg" onclick="{ show_collection_modal }" show="{ IFC.state.perms.can_modify_collection && cart.status !== 'Being Edited' && !cart.editor}">
                Save as collection
            </button>
            <button class="btn btn-danger btn-lg" if="{cart.status !== 'Being Edited' && !cart.editor}" onclick="{ empty_cart }">Empty cart</button>
            <button id="save_cart_button1" class="btn btn-info btn-lg" onclick="{ check_cart_comment }">Save cart</button>
            <button show="{ IFC.state.perms.can_checkout }" class="btn btn-success btn-lg" onclick="{ checkout }">Check out</button>
        </div>
    </div>
    <div id="dialog-confirm_modal" class="modal fade" role="dialog" show="false">
        <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 a shopping cart comment?</h4>
                </div>
                <form name="cart_comment_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-8">
                                <div class="form-group {has-error: errors.first_name}">
                                    <label class="control-label">Shopping Cart Comment</label>
                                    <textarea name="cart_comment" class="form-control" value="{ cart.comments }"></textarea>
                                    <span class="help-block" show="{ errors.first_name }">{ errors.cart_comment }</span>
                                </div>
                            </div>
                        </div>

                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default btn-lg" data-dismiss="modal" onclick="{ save_cart }">Close</button>
                        <input type="submit" class="btn btn-success btn-lg" value="Save" onclick="{ submit_cart_comment_form }">
                    </div>
                </form>
            </div>
        </div>
    </div>
    <pack-per-person-modal></pack-per-person-modal>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one("mount", function () {
            // Make images zoomable
            $('shopping-cart').magnificPopup({
                delegate: 'a.product-zoom-image',
                type: 'image'
            });

            // Actually get cart details
            self.update_cart();
        });


        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.set_is_cart_empty = function () {
            self.is_cart_empty = (!self.packs_per_person || Object.keys(self.packs_per_person).length == 0) &&
                (!self.regular_products || self.regular_products.length == 0);
        };

        self.update_cart = function () {
            IFC.api.get_cart()
                .success(function (cart) {
                    // Now that we have the cart, we can get the addresses associated with the carts office
                    if (cart.office) {

                        IFC.api.get_jobs({office: cart.office.id})
                            .success(function (data) {
                                self.update({jobs: data});
                            })
                            .error(function () {
                                toastr.error("Error fetching Jobs List");
                            })
                            .always(function () {
                                self.update({loading: false});
                            });

                        IFC.api.get_addresses({
                            office: cart.office.id,
                            is_ship_to: 'True',
                            originator: cart.originator.id
                        })
                            .success(function (addresses) {
                                self.update({addresses: addresses});
                                IFC.events.trigger('addresses_received');
                            })
                            .error(function () {
                                toastr.error("Could not get addresses for office " + cart.office.name);
                            });
                    }

                    // Grab items from cart and organize them into regular products or packs per person
                    var regular_products = [];
                    var packs_per_person = {};
                    cart.order_details.forEach(function (order) {
                        if (order.in_collection) {
                            // Make sure we have this object key
                            packs_per_person[order.in_collection.id] = packs_per_person[order.in_collection.id] || {};
                            packs_per_person[order.in_collection.id].order_details = packs_per_person[order.in_collection.id].order_details || [];
                            packs_per_person[order.in_collection.id].person_name = order.in_collection.person_name;
                            packs_per_person[order.in_collection.id].collection_id = order.in_collection.id;
                            packs_per_person[order.in_collection.id].order_details.push(order);
                        } else {
                            regular_products.push(order);
                        }
                    });

                    self.cart = cart;
                    self.office = cart.office;
                    self.packs_per_person = packs_per_person;
                    self.regular_products = regular_products;

                    self.set_is_cart_empty();

                    self.update();
                })
                .error(function () {
                    toastr.error("Could not get shopping cart!");
                });
        };

        self.empty_cart = function () {
            if (self.cart.status === 'Being Edited') {
                return
            }
            if (confirm("Are you sure you want to empty the cart?")) {
                IFC.api.reset_cart()
                    .success(function () {
                        self.cart = undefined;
                        self.office = undefined;
                        self.packs_per_person = undefined;
                        self.regular_products = undefined;
                        self.set_is_cart_empty();
                        // Update cart on top nav by re-fetching profile
                        IFC.get_profile();
                        self.update();
                        toastr.success("Cart emptied!");
                    })
                    .error(function (response) {
                        var error_text = "Could not empty shopping cart!";
                        if(JSON.parse(response.responseText).detail != null) {
                            error_text = JSON.parse(response.responseText).detail;
                        }
                        toastr.error(error_text);
                    });
            }
        };

        self.check_cart_comment = function () {
            $('#dialog-confirm_modal').modal('show');
       };

       self.submit_cart_comment_form = function () {
           var payload = $(self.cart_comment_form).serializeFormToObject();
           IFC.api.set_cart_comment(JSON.stringify(payload))
                .success(function () {
                    toastr.success("Shopping cart message Saved!");
                    self.save_cart();
                })
                .error(function () {
                    toastr.error("Could not save shopping cart message!");
                    self.save_cart();
                });
       };

        self.save_cart = function () {
            $('#dialog-confirm_modal').modal('hide');
            IFC.api.save_cart()
                .success(function () {
                    self.cart = undefined;
                    self.office = undefined;
                    self.packs_per_person = undefined;
                    self.regular_products = undefined;
                    self.set_is_cart_empty();
                    // Update cart on top nav by re-fetching profile
                    IFC.get_profile();
                    self.update();
                    toastr.success("Cart Saved!");
                })
                .error(function () {
                    toastr.error("Could not save shopping cart!");
                });
        };


        self.show_collection_modal = function () {
            IFC.events.trigger('show_collection_modal');
        };

        self.is_shopping_cart_valid = function () {
            var is_valid = true;

            // Validate regular products
            self.regular_products.forEach(function (product) {
                if (product.quantity <= 0) {
                    is_valid = false;
                }
                if (!product.ship_to) {
                    is_valid = false;
                }
            });

            // Validate collections
            Object.keys(self.packs_per_person).forEach(function(key){
                var pack = self.packs_per_person[key];
                if (!pack.order_details[0].ship_to) {
                    is_valid = false;
                }
            });

            return is_valid;
        };

        self.checkout = function () {
            if (!self.is_shopping_cart_valid()) {
                toastr.error("Error submitting shopping cart, make sure all items have > 0 quantity and ship to address selected for each.")
            } else {
                window.location.href = URL.pages.checkout;
            }
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('force_cart_update', self.update_cart);
        // If we are removing an item from the cart then call this function which will refresh the item list
        // Since the quantities where showing incorrectly
        IFC.events.on('force_cart_update_refresh', function () {
            // Set cart as empty before refreshing cart since it was not updating item quantities properly
            self.cart = undefined;
            self.office = undefined;
            self.packs_per_person = undefined;
            self.regular_products = undefined;
            self.set_is_cart_empty();
            self.update();
            self.update_cart();
        });

    </script>
    <style>
        .order-total {
            font-size: 16px;
        }

        .order-total-label {
            text-align: right;
            font-weight: bold;
        }

        .table {

        }

        .item-delimiter {
            height: 2px;
            width: 100%;
            background-color: #add8e6;
            clear: both;
        }
    </style>
</shopping-cart>

<ppp-item>
    <div class="pack-delimiter"></div>
    <h1>{ pack.person_name }</h1>

    <div class="form-group {has-error: errors.ship_to}" show="{ !opts.disable_editing }">
        <!-- NOTE: we had to name this `collection_ship_to_address` instead of `ship_to_address` because of our children! -->
        <select class="form-control" name="collection_ship_to_address" onchange="{ update_collection_address }">
            <option value="">Select a ship-to address</option>
            <option each="{ addresses }" value="{ id }">{ first_name } { last_name } { address_1 } { address_2 }</option>
        </select>
        <span class="help-block" show="{ errors.ship_to }">{ errors.ship_to }</span>
    </div>

    <div show="{ opts.disable_editing && opts.pack_per_person}">
        <b>Ship To:</b>
        { ship_to.company_name } { ship_to.first_name } { ship_to.last_name }&nbsp;&nbsp;&nbsp;
        { ship_to.address_1 } { ship_to.address_2 }&nbsp;&nbsp;&nbsp;
        { ship_to.city }, { ship_to.state } { ship_to.zip_code }
    </div>

    <div style="padding: 10px;">
        <cart-item each="{ pack.order_details }" pack_per_person="true" no-reorder disable_editing="{ parent.opts.disable_editing }"></cart-item>
    </div>
    <div class="pack-delimiter"></div>
    <div class="white-delimiter"></div>

    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one("update", function() {
            // All ship tos are the same for a collection, so just get the first one
            self.ship_to_id = self.pack.order_details[0].ship_to ? self.pack.order_details[0].ship_to.id : undefined;
        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.update_collection_address = function(event) {
            var ship_to_id = self.collection_ship_to_address.value;
            self.ship_to_id = ship_to_id

            if(!ship_to_id) {
                toastr.error('Cannot unset collection address, must choose an address');
                return false;
            }

            IFC.api.update_collection_ship_to(self.pack.collection_id, ship_to_id)
                .success(function() {
                    // Set this here (lazy) to make validation work (we have ship to id set)
                    self._item.pack.order_details.forEach(function(order_detail) {
                        order_detail.ship_to = ship_to_id;
                    });
                   // ship_to_address.value = ship_to_id;
                    //window.location.href = URL.pages.cart;
                    toastr.success("Updated address for collection.");
                })
                .error(function() {
                    toastr.error("Could not update address for collection!");
                });
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('addresses_received', function () {
            // We have addresses now, select our ship to if we have one
            if (self.ship_to_id) {
                self.collection_ship_to_address.value = self.ship_to_id;
            }
        });
    </script>
    <style scoped>
        :scope {
            background-color: #efffff;
            display: block;
        }

        :scope cart-item .table {
            background-color: #fff;
        }

        .pack-delimiter {
            height: 3px;
            width: 100%;
            background-color: #add8e6;
            clear: both;
        }

        .white-delimiter {
            height: 10px;
            width: 100%;
            background-color: #fff;
            clear: both;
        }
    </style>
</ppp-item>

<cart-item>
    <table class="table table-responsive table-borderless">
        <tbody>
        <tr>
            <td colspan="5">
                <i class="pull-right glyphicon glyphicon-remove remove-button" onclick="{ remove_from_cart }" show="{ !opts.disable_editing }"></i>
                <img src="{ window.URL.STATIC }img/return.png" class="pull-right return-button" data-toggle="tooltip"
                     title="Return this item" onclick="{ return_item }" show="{ opts.disable_editing && line_status_code == 'S' }" alt="return item" />

                <span class="product-name">{ product.name } { option_1.label } { option_2.label } { option_3.label }</span>
                <span show="{ line_status }">({ line_status })</span><br><br>

                <div class="form-group {has-error: errors.ship_to}" if="{ !opts.disable_editing && !opts.pack_per_person }">
                    <select class="form-control" name="ship_to_address" onchange="{ order_detail_updated }">
                        <option value="">Select a ship-to address</option>
                        <option each="{ parent.addresses }" value="{ id }">{ first_name } { last_name } { address_1 } { address_2 }</option>
                    </select>
                    <span class="help-block" show="{ errors.ship_to }">{ errors.ship_to }</span>
                </div>
                <div show="{ jobs.length > 0 &&  JSON.parse(localStorage.getItem('selected_company')).contracts_by_Line == true }">
                    <div class="form-group {has-error: errors.job}">
                        <label class="control-label">Contract Number: </label>
                        <i show="{ jobs.length == 0 }">There are no contracts assigned to the office for this order</i>
                        <select name="job_id" class="form-control"  show="{ jobs.length > 0 &&  JSON.parse(localStorage.getItem('selected_company')).contracts_by_Line == true }" onchange="{ order_detail_updated }">
                            <option value="" >Select a Contract Number</option>
                            <option each="{ jobs }" selected={job.id == id} value="{ id }">{ job_name} ({ job_number })</option>
                        </select>
                        <span class="help-block" show="{ errors.job }">{ errors.job }</span>
                    </div>
                </div>
                <div class="form-group" show="{ opts.disable_editing && !opts.pack_per_person }">
                    <b>Ship To:</b>
                    { ship_to.company_name } { ship_to.first_name } { ship_to.last_name }&nbsp;&nbsp;&nbsp;
                    { ship_to.address_1 } { ship_to.address_2 }&nbsp;&nbsp;&nbsp;
                    { ship_to.city }, { ship_to.state } { ship_to.zip_code }
                </div>

            </td>
        </tr>
        <tr>
            <td width="170px">
                <a class="product-zoom-image" href="{ image.zoomed_url }">
                    <img class="current_selected_image" src="{ image.thumbnail_url }">
                </a>
            </td>
            <td>
                <dl>
                    <dt>Qty</dt>
                    <dd>
                        <div class="form-group {has-error: errors.quantity}" show="{ !opts.disable_editing }">
                            <input name="quantity_input"
                                   type="number"
                                   class="form-control qty-input"
                                   min="1"
                                   onkeyup="{ order_detail_updated }"
                                   oninput="{ order_detail_updated }">
                            <span class="help-block" show="{ errors.quantity }">{ errors.quantity }</span>
                        </div>
                        <div show="{ opts.disable_editing }">{ quantity }</div>
                    </dd>
                </dl>
            </td>
            <td>
                <dl>
                    <dt>Item Number</dt>
                    <dd>{ sku }</dd>

                    <virtual show="{ option_1 }">
                        <dt>{ option_1_title.label }</dt>
                        <dd>{ option_1.label }</dd>
                    </virtual>
                    <virtual show="{ option_2 }">
                        <dt>{ option_2_title.label }</dt>
                        <dd>{ option_2.label }</dd>
                    </virtual>
                    <virtual show="{ option_3 }">
                        <dt>{ option_3title_.label }</dt>
                        <dd>{ option_3.label }</dd>
                    </virtual>

                    <virtual show="{ extra_instructions_formatted }">
                        <dt>Customizations</dt>
                        <dd>
                            <span each={ extra_instruction, i in extra_instructions_formatted }>
                                { extra_instruction }<br>
                            </span>
                        </dd>
                    </virtual>
                </dl>
            </td>

            <td width="170px">
                <price amount="{ product_price_without_add_ons }" show_free="true" class="black"></price>
            </td>

            <td width="170px">
                <price amount="{ parseFloat(product_price_without_add_ons * quantity).toFixed(2) }" show_free="true" class="black"></price>
            </td>
        </tr>
        <tr each="{ add_ons }" class="add-on">
            <td>
                <a class="product-zoom-image" href="{ image.zoomed_url }">
                    <img class="add-on-thumbnail" src="{ image.thumbnail_url }">
                </a>
            </td>
            <td></td>
            <td>
                <strong>{ product.name }</strong><br>
                <!-- For embroidery add ons -->
                <virtual show="{ extra_instructions }">
                    <span>{ extra_instructions }</span>
                </virtual>
            </td>
            <td><price amount="{ parseFloat(price).toFixed(2) }" show_free="true" class="black"></price></td>
            <td><price amount="{ parseFloat(price * quantity).toFixed(2) }" show_free="true" class="black"></price></td>
        </tr>
        </tbody>
    </table>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/
        self.one('mount', function () {
            self.quantity_input.value = self.quantity;

            $(self.root).tooltip({
                selector: "[title]",
                container: 'body', // setting this makes the alerts ignore overflow=hidden and such
                trigger : 'hover' // makes tooltip dissappear after it's removed
            });

            // Grab extra instructions (for example -- <title>::<value>%-e-n-d-%\n)
            // and split the string to display it nicely
            if(self.extra_instructions) {
                self.extra_instructions_formatted = [];
                self.extra_instructions.split('%-e-n-d-%\n').forEach(function(extra_instruction) {
                    var values = extra_instruction.split('::');
                    if(values.length > 1 && values[1] != "") {
                        self.extra_instructions_formatted.push(values[0] + " - " + values[1]);
                    }
                });
                self.update();
            }
        });

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.remove_from_cart = function () {
            if (confirm("Are you sure you want to remove this item from the cart?")) {
                IFC.api.remove_from_cart(self.id)
                    .success(function () {
                        IFC.events.trigger('force_cart_update_refresh');
                        IFC.get_profile();
                        toastr.success("Removed item from cart!");
                    })
                    .error(function (response) {
                        var error_text = "Could not remove item from cart!";
                        if(JSON.parse(response.responseText).detail != null) {
                            error_text = JSON.parse(response.responseText).detail;
                        }
                        toastr.error(error_text);
                    });
            }
        };

        self.return_item = function(){
            IFC.events.trigger('return_item', this._item);
        };

        self.order_detail_updated = function () {
            // make the payload
            var ship_to = self.opts.pack_per_person === "true" ? $('[name="collection_ship_to_address"]', self.parent.root).val() : self.ship_to_address.value

            var payload = {
                quantity: self.quantity_input.value,
                ship_to: ship_to || undefined, // undefined here gives us a better error from server if empty
                job:self.job_id.value
            };
            // Bubble changes back up to the cart by setting magic _item fields
            self._item.quantity = payload.quantity;
            self._item.ship_to = payload.ship_to;
            self._item.job=payload.job;

            IFC.api.update_order_detail(self.id, JSON.stringify(payload))
                .success(function () {
                    //IFC.events.trigger('force_cart_update');
                    toastr.success("Updated item details!");
                    self.errors = undefined;
                    self.update();
                    IFC.events.trigger('force_cart_update');
                })
                .error(function (response) {
                    var data = JSON.parse(response.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.errors = data;
                    self.update();
                });
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('addresses_received', function () {
            // We have addresses now, select our ship to if we have one
            if (self.ship_to) {
                self.ship_to_address.value = self.ship_to.id;
            }
            if(self.job) {
                self.job.value= self.job.id;
            }
        });

    </script>
    <style scoped>
        .table {
            border: 1px solid rgba(0, 0, 0, 0.1);
            background-color: rgba(0, 0, 0, 0.02);
        }

        .product-name {
            font-weight: bold;
            font-size: 18px;
        }

        .table-borderless tbody tr td, .table-borderless tbody tr th {
            border: none;
        }

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

        .add-on-thumbnail {
            max-height: 42px;
            float: right;
        }

        .remove-button {
            cursor: pointer;
            color: indianred;
        }

        .remove-button:hover {
            color: red;
        }

        .return-button {
            cursor: pointer;
            /*color: indianred;*/
        }

        .return-button:hover {
            color: navy;
        }

        .qty-input {
            width: 75px;
        }
    </style>
</cart-item>














<pack-per-person-modal>
    <div class="modal fade" id="collection_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">Create Collection</h4>
                </div>
                <form name="collection_form">
                    <div class="modal-body">
                        <div class="form-group {has-error: errors.name}">
                            <label class="control-label">Name</label>
                            <input name="name" type="text" class="form-control">
                            <span class="help-block" show="{ errors.name }">{ errors.name }</span>
                        </div>
                    </div>
                    <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="Save" onclick="{ save_collection }">
                    </div>
                </form>
            </div>
        </div>
    </div>
    <script>
        var self = this;

        /* ----------------------------------------------------------------------------
         Tag events
         ----------------------------------------------------------------------------*/

        /* ----------------------------------------------------------------------------
         Component methods
         ----------------------------------------------------------------------------*/
        self.save_collection = function () {
            var name = self.collection_form.name.value;

            if (!name) {
                toastr.error("Collections require a name!");
                return;
            }

            IFC.api.create_collection(JSON.stringify({name: name}))
                .success(function () {
                    IFC.events.trigger('force_cart_update');
                    $('#collection_modal').modal('hide');

                    // Update cart on top nav by re-fetching profile
                    IFC.get_profile();
                })
                .error(function (response) {
                    var data = JSON.parse(response.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("Could not save collection!");
                });
        };

        self.show_collection_modal = function () {
            $('#collection_modal').modal('show');
        };

        /* ----------------------------------------------------------------------------
         IFC.events
         ----------------------------------------------------------------------------*/
        IFC.events.on('show_collection_modal', self.show_collection_modal);

    </script>
    <style>

    </style>
</pack-per-person-modal>
