// User interface code for rightsize
// Version 1.0 - Martin Arrand 14/08/07 - PRODUCTION

Ext.onReady(function() {
    Ext.BLANK_IMAGE_URL = 'wp-content/uploads/ext/resources/images/default/s.gif';
    
    Ext.get('no-js-info').remove();
    
    var form_rightsize = new Ext.form.Form({
        labelAlign: 'right',
        labelWidth: 90,
        buttonAlign: 'right'
    });
    
    form_rightsize.fieldset(
        {legend:'Product dimensions'},
        
        new Ext.form.NumberField({
            fieldLabel: 'Width (X)',
            name: 'prod_x',
            width: 90,
            value: 10,
            allowBlank: false,
            allowNegative: false
        }),
        
        new Ext.form.NumberField({
            fieldLabel: 'Depth (Y)',
            name: 'prod_y',
            width: 90,
            value: 10,
            allowBlank: false,
            allowNegative: false
        }),
        
        new Ext.form.NumberField({
            fieldLabel: 'Height (Z)',
            name: 'prod_z',
            width: 90,
            value: 10,
            allowBlank: false,
            allowNegative: false
        }),
        
        new Ext.form.NumberField({
            fieldLabel: 'Weight',
            name: 'prod_weight',
            width: 90,
            allowBlank: true,
            allowNegative: false
        })
    );
    
    
    form_rightsize.add(
        new Ext.form.NumberField({
            fieldLabel: 'Qty to store',
            labelWidth: 200,
            name: 'qts',
            width: 80,
            value: 10
        })
    );
    
    form_rightsize.add(
        new Ext.form.TextField({
            fieldLabel: 'Best module',
            labelWidth: 200,
            name: 'best_mod',
            width: 150,
            readOnly: true,
            value: "Calculate..."
        })
    );
    
    
    
    form_rightsize.render('rightsize-form');
    
    // shorthand alias
    var fm = Ext.form, Ed = Ext.grid.GridEditor;
    // editors
    
    var cm = new Ext.grid.ColumnModel([{
            header: "Module Type",
            dataIndex: 'mod',
            width: 90,
            editor: new Ed(new fm.TextField({
                allowBlank: false
            }))
        },{
            header: "Width (X)",
            dataIndex: "mod_x",
            width: 65,
            editor: new Ed(new fm.NumberField({
                allowBlank: false,
                allowNegative: false
            }))
        },{
            header: "Depth (Y)",
            dataIndex: "mod_y",
            width: 65,
            editor: new Ed(new fm.NumberField({
                allowBlank: false,
                allowNegative: false
            }))
        },{
            header: "Height (Z)",
            dataIndex: "mod_z",
            width: 65,
            editor: new Ed(new fm.NumberField({
                allowBlank: false,
                allowNegative: false
            }))
        },{
            header: "Max Weight",
            dataIndex: "mod_maxWeight",
            width: 65,
            editor: new Ed(new fm.NumberField({
                allowBlank: true,
                allowNegative: false
            }))
        },{
            header: "Capacity",
            dataIndex: "cap",
            width: 60
        }]);
    
    // by default columns are sortable
    cm.defaultSortable = true;
    
    // array of initial module types
    var moduleTypesInitial = [
        ['Lin Bin Size 1', 105, 105, 50, 20, "-", false],
        ['Lin Bin Size 2', 105, 135, 75, 20, "-", false],
        ['Lin Bin Size 3', 105, 190, 75, 20, "-", false],
        ['Pallet', 1200, 1000, 1000, 1000, "-", false]
        /* ... and the rest ... */
    ];
    
    var modStore = new Ext.data.SimpleStore({
        fields: ['mod', 'mod_x', 'mod_y', 'mod_z', 'mod_maxWeight', 'cap'],
        data: moduleTypesInitial
    });
    
    // create editor grid
    
    var modGrid = new Ext.grid.EditorGrid('rightsize-grid', {
        ds: modStore,
        cm: cm,
        enableColLock: false
    });
    
    var modLayout = Ext.BorderLayout.create({
        center: {
            margins: {left:3,top:3,right:3,bottom:3},
            panels: [new Ext.GridPanel(modGrid)]
        }
    }, 'rightsize-grid-layout');
    
    // override grid view to allow highlighting best row
    modGrid.getView().getRowClass = function(record, index){
        return record.get("best") ? "rs-best" : "";
    };
    
    Ext.util.CSS.createStyleSheet(".rs-best td { background-color:#89c4a9; }","rs-best");
    
    modGrid.render();
    
    var Module = Ext.data.Record.create([
           // the "name" below matches the tag name to read, except "availDate"
           // which is mapped to the tag "availability"
           {name: 'mod', type: 'string'},
           {name: 'mod_x', type: 'float'},
           {name: 'mod_y', type: 'float'},
           {name: 'mod_z', type: 'float'},
           {name: 'mod_maxWeight', type: 'float'},
           {name: 'cap', type: 'string'},
           {name: 'best', type: 'boolean'}
      ]);
    
    var gridHead = modGrid.getView().getHeaderPanel(true);
    var gridFoot = modGrid.getView().getFooterPanel(true);
    var tbFoot = new Ext.Toolbar(gridFoot, [{
        text: 'New module',
        handler : function(){
            var p = new Module({
                mod: 'New module 1',
                mod_x: 0,
                mod_y: 0,
                mod_z: 0,
                mod_maxWeight: '',
                cap: "-",
                best: false
            });
            modGrid.stopEditing();
            modStore.insert(0, p);
            modStore.commitChanges();
            modGrid.startEditing(0, 0);
        }},{
            text: 'Delete module',
            handler: function(){
                var rec = modGrid.getSelectionModel().selection;
                if (rec) {
                    rec = rec.record;
                }
                if (rec) {
                    modStore.remove(rec);
                    modStore.commitChanges();
                }
            }
        }
    ]);
  
    var tbHead = new Ext.Toolbar(gridHead, [    
        {
            text: 'Calculate',
            handler: function(){
                // test function to iterate through store
                var i, recCount, eachMod, modDims, v = form_rightsize.getValues(), cap; //, bestCap = 9999999, bestMod = "No fit";
                
                var bestMod = { cap:9999999, mod:"No fit" };
                
                modGrid.stopEditing();
                
                recCount = modStore.getTotalCount();
                
                
                // Iterate using each()
                modStore.each(function(record) {
                    var cap, modDims;
                    
                    modDims = {
                        x: record.get("mod_x"),
                        y: record.get("mod_y"),
                        z: record.get("mod_z"),
                        maxWeight: record.get("mod_maxWeight")
                    };
                    
                    cap = pallCap(modDims, {x:v.prod_x, y:v.prod_y, z:v.prod_z, weight:v.prod_weight}, 0);
                    
                    if (cap<bestMod.cap && cap>=v.qts) {
                        bestMod.cap = cap;
                        bestMod.mod = record.get("mod");
                    }
                        
                    record.set("best", false);
                    record.set("cap",cap);
                    
                    return true;
                });
                
                modStore.each(function(record) {
                    if (record.get("mod")==bestMod.mod) {
                        record.set("best", true);
                }});
                
                modStore.commitChanges();
                
                form_rightsize.setValues([{id:'best_mod', value:bestMod.mod}]);
            }
        }
    ]);
    
    
    
    
});

