<html>
    <head>

        <title>Crafting</title>

        <link rel="stylesheet" href="../css/style.css" type="text/css" />

        <script type="text/javascript" src="../js/jquery.js"></script>
        <script type="text/javascript" src="../js/handlebars.js"></script>
        <script type="text/javascript" src="../js/ember.js"></script>
        <script type="text/javascript" src="../js/common.js"></script>

        <style>
            #category-area { padding: 4px 10px 10px; position: relative; }

                #availability-container { float: right; margin-top: 2px; }
                #availability-container input { margin: 0; }
                #availability-container label { font-size: 12px; margin-left: 5; position: relative; top: 0px; }

            .subcategory .items { margin-left: 15px; }

            #materials-window { position: absolute; left: 285px; top: 54px; }

                #materials-window .header { padding: 0 5px 6px; position: relative; }
                #materials-window .header img { vertical-align: text-top; margin-right: 5px; }
                #materials-window .header #materials-item { position: relative; top: 5px; font-size: 18px; }
                #materials-window .header #item-surface { float: right; padding: 10px 0 0; }

                #materials-window td.content { width: 240px; }
                #materials-window .items { padding: 6px 5px 6px; }

            .items { margin: 0 0 5px 15px; }
            .item { padding: 5px 0px 5px 5px; border-radius: 5px; margin-right: 10px;  }

                .item:hover { background-color: rgba(0, 0, 0, 0.1); box-shadow: inset 0 0 3px 0 rgba(0, 0, 0, 0.5); }
                .item.selected { background-color: rgba(0, 0, 0, 0.2); box-shadow: inset 0 0 3px 0 rgba(0, 0, 0, 0.5); }

                .item img { vertical-align: text-top; margin-right: 5px; }
                .item-name { color: #fff; font-size: 14px; position: relative; top: 3px; margin-left: 2px; }
                .unavailable .item-name { color: #bbb; }
                .available { color: #fff; }
                .unavailable-surface { color: #DB8296; }

            .materials-area .items { margin-left: 0; }

                .materials-area .item { margin-right: 0; }
                .materials-area .item:hover { background: rgba(0, 0, 0, 0.0); box-shadow: none; }
                .materials-area .item .item-availability {
                    color: #fff;
                    font-size: 14px;
                    position: relative;
                    top: 3px;
                }
                .materials-area .item.unavailable .item-availability { color: #bbb; }
                .materials-area .item-quantity { float: right; }

            .item-unique { top: 8px; margin-top: 3px; margin-left: 4px; }
            .material-slot { margin-left: -5px; }

            .subcategory-area { padding: 0; min-width: 300px; margin: 10px 0 0; height: 300px; overflow: auto; }
            .subcategory { }

                .subcategory_label { margin: 0 0 5px; color: #fff; font-size: 18px; font-weight: normal;
                    background: url(../images/arrow.png) no-repeat 0 5px; padding-left: 15px; }

                    .open .subcategory_label { background-image: url(../images/arrow-open.png); }

            .quantity_input {
                width: 40px;
                text-align: right;
            }

            .max_button {
                width: 60px;
            }

            .craft_button {
                width: 60px;
                float: right;
            }

        </style>
    </head>
    <body>

        <div id="crafting" class="window with-header" data-handle="Crafting">

            <script data-template-name="categories" type="text/x-handlebars">
                <div class="categories group">
                    <div id="availability-container" class="availability-container">
                        <label class="serif">
                            Only Available
                            {{view App.ToggleButton checkedBinding="App.categoryView.filter"}}
                        </label>
                    </div>
                    {{#each category in App.categories}}
                        {{#view App.CategoryView contentBinding="category"}}
                            <img width="24" height="24" {{bindAttr class="category.isSelected:category-selected :category-icon" src="category.icon"}}></img>
                        {{/view}}
                    {{/each}}
                </div>
            </script>

            <script data-template-name="subcategory-template" type="text/x-handlebars">
                {{#each subcategory in App.categoryView.selected.subcategories}}
                {{#if subcategory.shouldShow}}
                    <div {{bindAttr class="subcategory.isExpanded:open :subcategory :serif"}}>
                        {{#view App.SubcategoryView contentBinding="subcategory"}}
                            <div>
                                <h2 class="subcategory_label serif">{{subcategory.name}}</h2>
                            </div>
                        {{/view}}
                        {{#if subcategory.isExpanded}}
                        <div class="items group">
                            {{#each item in subcategory.availableItems}}
                                {{#view App.CraftItemView contentBinding="item"}}
                                <div {{bindAttr class="item.isSelected:selected item.isUnavailable:unavailable :item"}}>
                                    {{#view App.IconItemView contentBinding="item"}}
                                        <img width="24" height="24" {{bindAttr id="item.elementId" src="item.icon"}}></img>
                                    {{/view}}
                                    <span class="item-name serif"}}>{{item.name}}</span>
                                </div>
                                {{/view}}
                            {{/each}}
                        </div>
                        {{/if}}
                    </div>
                {{/if}}
                {{/each}}
            </script>

            <div id="category-area" class="header category-area serif group"></div>

            <div id="subcategory-area" class="subcategory-area"></div>

        </div>

        <div id="materials-section"></div>

        <script data-template-name="materials-template" type="text/x-handlebars">

            {{#if App.materialsView.selected}}

            <div class="window-container" id="materials-window">
                <div class="materials-area">

                <table cellspacing="0" cellpadding="0" class="window-framework">
                    <tbody>
                        <tr class="header-top">
                            <td class="top-left"></td>
                            <td class="top"></td>
                            <td class="top-right"></td>
                        </tr>
                        <tr class="header-middle">
                            <td class="middle-left"></td>
                            <td class="middle content">
                                <div class="header">
                                    {{#view App.IconItemView contentBinding="App.materialsView.selected"}}
                                        <img width="24" height="24" {{bindAttr src="App.materialsView.selected.icon"}} />
                                    {{/view}}
                                    <span id="materials-item" class="serif">{{App.materialsView.selected.name}}</span>
                                    {{#if App.materialsView.selected.service}}
                                        <span id="item-surface" {{bindAttr class="App.materialsView.selected.service.isAvailable:available:unavailable-surface :serif :small"}}>{{App.materialsView.selected.service.name}}</span>
                                    {{/if}}
                                </div>
                            </td>
                            <td class="middle-right"></td>
                        </tr>
                        <tr class="header-bottom">
                            <td class="bottom-left"></td>
                            <td class="bottom"></td>
                            <td class="bottom-right"></td>
                        </tr>
                        <tr class="window-content">
                            <td class="middle-left"></td>
                            <td class="middle content">

                                <div class="items group">
                                    {{#each material in App.materialsView.selected.uniqueMaterials}}
                                        <div {{bindAttr class="material.isReady::unavailable :item"}}>
                                            {{#if material.isKnown}}
                                                {{#view App.MaterialItemView contentBinding="material"}}
                                                <div class="itemslot material-slot">
                                                    {{#if view.content.showIcon}}
                                                        <img width="24" height="24" {{bindAttr src="view.content.icon"}}></img>
                                                    {{/if}}
                                                    <div class="qty_div">
                                                        {{#if view.content.held}}
                                                            <span class="quantity tiny-text">{{view.content.held}}<span>
                                                        {{/if}}
                                                    </div>
                                                </div>
                                                {{/view}}
                                                <span class="item-name item-unique serif">{{material.name}}</span>
                                            {{else}}
                                                {{#view App.IconItemView contentBinding="material"}}
                                                    <img width="24" height="24" {{bindAttr src="material.icon"}}></img>
                                                {{/view}}
                                                <span class="item-name item-unique serif">{{material.name}}</span>
                                            {{/if}}
                                        </div>
                                        <div style="clear: both;"></div>
                                    {{/each}}
                                    {{#if App.materialsView.selected.showDivisor}}
                                        <div class="content-divisor"></div>
                                    {{/if}}
                                    {{#each material in App.materialsView.selected.commonMaterials}}
                                        <div {{bindAttr class="material.isAvailable::unavailable :item"}}>
                                            {{#if material.isKnown}}
                                                {{#view App.IconItemView contentBinding="material" canScroll="true"}}
                                                    <img width="24" height="24" {{bindAttr src="material.icon"}}></img>
                                                {{/view}}
                                                <span class="item-name serif">{{material.name}}</span>
                                                <span class="item-availability item-quantity serif">({{material.item.quantity}}/{{material.quantity}})</span>
                                            {{else}}
                                                {{#view App.IconItemView contentBinding="material"}}
                                                    <img width="24" height="24" {{bindAttr src="material.icon"}}></img>
                                                {{/view}}
                                                <span class="item-name serif">{{material.name}}</span>
                                            {{/if}}
                                        </div>
                                        <div style="clear: both;"></div>
                                    {{/each}}
                                </div>

                                <div class="submission">
                                    {{view Ember.TextField type="number" class="quantity_input" valueBinding="App.materialsView.quantity" disabledBinding="App.materialsView.selected.isNotReady"}}
                                    <button class="max_button" {{action maxQuantity target="view"}} {{bindAttr disabled="App.materialsView.selected.isNotReady"}}>Max</button>
                                    <button class="craft_button" {{action craft target="view"}} {{bindAttr disabled="App.materialsView.selected.isNotReady"}}>Craft</button>
                                </div>

                            </td>
                            <td class="middle-right"></td>
                        </tr>
                        <tr>
                            <td class="bottom-left"></td>
                            <td class="bottom"></td>
                            <td class="bottom-right"></td>
                        </tr>
                    </tbody>
                </table>

                </div>
            </div>

            {{/if}}
        </script>

        <script type="text/javascript" src="../js/model.js"></script>
        <script type="text/javascript">
            $(document).bind('creaWindowLoaded', function() {
                App.Category = Ember.Object.extend({
                    name: "",
                    icon: "",
                    isSelected: false,
                    subcategories: null,
                    init: function() {
                        this._super();
                        this.subcategories = Ember.ArrayController.create({content: []});
                    },
                    shouldShow: function() {
                        var result = this.subcategories.find(function(item, index, enumerable) {
                            return item.get("shouldShow");
                        });
                        return result;
                    }.property('subcategories.@each.shouldShow'),
                });

                App.ItemsController = Ember.ArrayController.extend({
                    content: null,
                    learnedItems: function() {
                        var content = this.get('content');
                        return this.filter(function(item, index, enumerable) {
                            return item.get("learned");
                        });
                    }.property('content.@each.learned'),
                    availableItems: function() {
                        var content = this.get('content');
                        return this.filter(function(item, index, enumerable) {
                            return item.get("isAvailable") && item.get("learned");
                        });
                    }.property('content.@each.isAvailable'),
                });

                App.MaterialsController = Ember.ArrayController.extend({
                    content: null,
                    commonMaterials: function() {
                        var content = this.get('content');
                        return this.filter(function(material, index, enumerable) {
                            return !material.item.get("isUnique");
                        });
                    }.property('content.@each.isUnique'),
                    uniqueMaterials: function() {
                        var content = this.get('content');
                        return this.filter(function(material, index, enumerable) {
                            return material.item.get("isUnique");
                        });
                    }.property('content.@each.isUnique')
                });

                App.Subcategory = Ember.Object.extend({
                    name: "",
                    isExpanded: true,
                    filter: false,
                    items: null,
                    init: function() {
                        this._super();
                        this.items = App.ItemsController.create({content: []});
                    },
                    availableItems: function() {
                        if (this.filter) {
                            return this.items.get('availableItems');
                        } else {
                            return this.items.get('learnedItems');
                        }
                    }.property('items.availableItems', "items.learnedItems", 'filter'),
                    shouldShow: function() {
                        return this.get('availableItems').length > 0;
                    }.property('availableItems'),
                    observeIsExpanded: function() {
                        forceRedraw();
                    }.observes('isExpanded')
                });

                App.Item = Ember.Object.extend({
                    id: 0,
                    name: "",
                    icon: "",
                    output: 1,
                    service: null,
                    quantity: 0, //Available quantity
                    materials: null,
                    isUnique: false,
                    isSelected: false,
                    init: function() {
                        this._super();
                        this.materials = App.MaterialsController.create({content: []});
                    },
                    content: function() {
                        return this.get('id');
                    }.property('id').cacheable(),
                    elementId: function() {
                        return "item-" + this.id.toString();
                    }.property('id'),
                    commonMaterials: function() {
                        return this.materials.get("commonMaterials");
                    }.property('materials.commonMaterials'),
                    uniqueMaterials: function() {
                        return this.materials.get("uniqueMaterials");
                    }.property('materials.uniqueMaterials'),
                    showDivisor: function() {
                        return this.materials.get("commonMaterials").length > 0 && this.materials.get("uniqueMaterials").length > 0;
                    }.property('materials.commonMaterials', 'materials.uniqueMaterials'),
                    learnMaterial: function(material) {
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            if (this.materials.content[i].get('item').get('id') == material) {
                                this.materials.content[i].set('known', true);
                                break;
                            }
                        }
                    },
                    learned: function() {
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            if (this.materials.content[i].get('known')) {
                                return true;
                            }
                        }
                        return false;
                    }.property('materials.content.@each.isKnown'),
                    isAvailable: function() {
                        if (this.service && !this.service.isAvailable) {
                            return false;
                        }
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            if (!this.materials.content[i].get('isAvailable')) {
                                return false;
                            }
                        }
                        return true;
                    }.property('materials.content.@each.isAvailable', 'service.isAvailable').cacheable(),
                    isUnavailable: Ember.computed.not('isAvailable'),
                    isReady: function() {
                        if (this.service && !this.service.isAvailable) {
                            return false;
                        }
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            if (!this.materials.content[i].get('isReady')) {
                                return false;
                            }
                        }
                        return true;
                    }.property('materials.content.@each.isReady', 'service.isAvailable').cacheable(),
                    isNotReady: Ember.computed.not('isReady'),
                    getMax: function() {
                        var amount = 99;
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            var material = this.materials.content[i];
                            var materialMax = Math.floor(material.get('item').get('quantity') / material.get('quantity'));
                            if (materialMax < amount) {
                                amount = materialMax;
                            }
                        }
                        return amount;
                    },
                    reset: function() {
                        for (var i = 0; i < this.materials.content.length; ++i) {
                            var material = this.materials.content[i]
                            if (material.get('item').get('isUnique')) {
                                material.set('id', 0);
                                material.set('held', 0);
                                break;
                            }
                        }
                    }
                });

                App.Material = Ember.Object.extend({
                    item: null,
                    index: 0,
                    quantity: 0,
                    id: 0,
                    held: 0,
                    known: false,
                    name: function() {
                        return this.get('isKnown') ? this.item.name : '???';
                    }.property('item.name', 'isKnown'),
                    content: function() {
                        return this.item.get('id');
                    }.property('item.id').cacheable(),
                    icon: function() {
                        return this.get('isKnown') ? this.item.icon : '../images/unknown_material.png';
                    }.property('item.icon', 'isKnown'),
                    isAvailable: function() {
                        return this.quantity <= this.item.quantity && this.get('isKnown');
                    }.property('item.quantity', 'quantity', 'isKnown').cacheable(),
                    isReady: function() {
                        return this.item.get('isUnique') ? this.held : this.get('isAvailable');
                    }.property('item.isUnique', 'isAvailable', 'held').cacheable(),
                    isKnown: function() {
                        return this.get('known');
                    }.property('known').cacheable(),
                    showIcon: function() {
                        return this.get('icon') && this.held;
                    }.property('held')
                });

                App.Service = Ember.Object.extend({
                    key: "",
                    name: "",
                    isAvailable: false
                });

                App.categories = Ember.ArrayController.create({
                    content: []
                });

                App.CategorySelectView = Ember.View.extend({
                    templateName: 'categories',
                    controller: App.categories,
                    content: null,
                    selected: null,
                    filter: false,
                    isFiltered: function() {
                        for (var c = 0; c < this.controller.content.length; ++c) {
                            var category = this.controller.content[c];
                            for (var s = 0; s < category.subcategories.content.length; ++s) {
                                category.subcategories.content[s].set('filter', this.filter);
                            }
                        }
                        var selected = App.materialsView.get('selected');
                        if (this.filter && selected != null && selected.get('isUnavailable')) {
                            App.materialsView.get('selected').set('isSelected', false);
                            App.materialsView.set('selected', null);
                        }
                        forceRedraw();
                    }.observes('filter'),
                    selectCategory: function(category) {
                        if (App.categoryView.get('selected')) {
                            App.categoryView.get('selected').set('isSelected', false);
                        }
                        App.categoryView.set('selected', category);
                        category.set('isSelected', true);
                        App.materialsView.setSelected(null);
                        forceRedraw();
                    }
                });
                App.CategoryView = Ember.View.extend({
                    content: null,
                    classNames: ['category-icons'],
                    click: function() {
                        App.categoryView.selectCategory(this.content);
                    },
                    mouseEnter: function() {
                        Crea.invoke('showTooltip', 'simple', getArea(this.$()), this.content.get('name'));
                    }
                });
                App.SubcategoryView = Ember.View.extend({
                    content: null,
                    click: function() {
                        this.content.set('isExpanded', !this.content.get('isExpanded'));
                        if (this.content.get('items').contains(App.materialsView.get('selected'))) {
                            App.materialsView.setSelected(null);
                        }
                    }
                });
                App.CraftItemView = Ember.View.extend({
                    content: null,
                    click: function() {
                        App.materialsView.setSelected(this.content);
                    },
                });
                App.MaterialsView = Ember.View.extend({
                    templateName: 'materials-template',
                    content: null,
                    selected: null,
                    quantity: 1,
                    quantityChanged: function() {
                        if (isNaN(this.quantity) || this.quantity <= 0) {
                            this.set('quantity', 1);
                        }
                        var max = this.selected.getMax();
                        if (this.quantity > max) {
                            this.set('quantity', max);
                        }
                    }.observes('quantity'),
                    maxQuantity: function() {
                        this.set('quantity', this.selected.getMax());
                    },
                    setSelected: function(item) {
                        if (this.get('selected') != null) {
                            this.get('selected').reset();
                            this.get('selected').set('isSelected', false);
                        }
                        if (item && this.get('selected') != item) {
                            this.set('selected', item);
                            item.set('isSelected', true);
                        } else {
                            this.set('selected', null);
                        }
                        this.set('quantity', 1);
                        Crea.invoke('selectItem', this.get('selected') != null ? this.get('selected').id : 0);
                        forceRedraw();
                    },
                    craft: function() {
                        Crea.invoke('craft', this.selected.id, this.quantity);
                        this.set('quantity', 1);
                    }
                });

                App.MaterialItemView = App.ItemView.extend({
                    mouseUp: function(event) {
                        if (this.content && this.content == App.clicked) {
                            if (event.which == 1) {
                                Crea.invoke('clickedItem', App.clicked.get('index'));
                            } else if (event.which == 3) {
                                Crea.invoke('splitItem', App.clicked.get('index'));
                            }
                        }
                    },
                    mouseDown: function(event) {
                        App.clicked = this.content;
                    },
                    mouseEnter: function() {
                        if (this.content != null &&
                           (this.content.get('id') != 0 || this.content.get('content') != 0) &&
                           (!this.content.hasOwnProperty('isKnown') || this.content.get('isKnown')))
                        {
                            var area = getArea(this.$('div'));
                            Crea.invoke('showTooltip', 'item', area, this.content.get('id'), this.content.get('content'));
                        }
                    }
                });

                App.IconItemView = Ember.View.extend({
                    content: null,
                    tagName: 'span',
                    canScroll: false,
                    click: function() {
                        if (this.canScroll) {
                            goToItem(this.content.item);
                        }
                    },
                    mouseEnter: function() {
                        if (this.content != null && (!this.content.hasOwnProperty('isKnown') || this.content.get('isKnown'))) {
                            var area = getArea(this.$());
                            area.x -= 4;
                            area.y -= 4;
                            area.width += 8;
                            area.height += 8;
                            Crea.invoke('showTooltip', 'item', area, 0, this.content.get('content'));
                        }
                    }
                });

                App.clicked = null;

                //List of all items (craftable or only material)
                App.items = {};
                //List of services that items may require
                App.services = Ember.ArrayController.create({content: []});

                App.categoryView = App.CategorySelectView.create();
                App.categoryView.appendTo("#category-area");
                App.ContentView = Ember.View.extend({
                    templateName: 'subcategory-template',
                    selected: null
                });
                App.contentView = App.ContentView.create();
                App.contentView.appendTo("#subcategory-area");

                App.materialsView = App.MaterialsView.create();
                App.materialsView.appendTo("#materials-section");

                App.onlyAvailable = false;
                App.addObserver('onlyAvailable', function() {});

                populate();
            });

            var goToItem = function(item) {
                for (var i = 0; i < App.categories.content.length; ++i) {
                    var category = App.categories.content[i];
                    for (var j = 0; j < category.subcategories.content.length; ++j) {
                        var subcategory = category.subcategories.content[j];
                        if (subcategory.items.find(function(i, index, enumerable) { return i == this; }, item) != null) {
                            App.categoryView.selectCategory(category);
                            subcategory.set('isExpanded', true);
                            Ember.run.scheduleOnce('afterRender', this, function() {
                                var x = $("#" + item.get('elementId')).offset().top;
                                jQuery('#subcategory-area').animate({scrollTop: x}, 300);
                                App.materialsView.setSelected(item);
                            });
                        }
                    }
                }
            }
        </script>
    </body>
</html>
