Ext.ns("Rebul.Item");

Rebul.Item.Edit = function(config){

	this.config = config || {};
	this.config.intID = this.config.intID || 0;
	this.config.orderID = this.config.orderID || 0;
	this.config.tablename = this.config.tablename || 'cart';
	this.config.ts = this.config.ts || {};
	this.config.clientID = this.config.clientID || 0;
	this.config.url = this.config.tablename == 'cart' ? 'viewcart.cfm?intID=' + this.config.intID : 'viewcart_saved.cfm?intID=' + this.config.intID + '&orderID=' + this.config.orderID;
	if(this.config.o2) this.config.o2 = decodeURI(this.config.o2);
		
	Ext.QuickTips.init();
	Ext.form.Field.prototype.msgTarget = 'side';
	
	var cardNav = function(incr){
        var p = Ext.getCmp('item-panel');
		var l = p.getLayout();
        var i = l.activeItem.id.split('card-')[1];
        var next = parseInt(i) + incr;
        if (next == 2) {
            this.submitForm();
			//this.getPricing();
            //this.setPanelTitle(2);            
        }
        else {
            this.setPanelTitle(next);
            l.setActiveItem(next);
            Ext.getCmp('btn-prev').setDisabled(next == 0);
            Ext.getCmp('btn-next').setDisabled(next == 2);
            Ext.getCmp('btn-next').setVisible(next == 0);
            Ext.getCmp('btn-add').setVisible(next == 1);
        }
		p.doLayout();
    };
    
    var toggleTemplate = function(e){
        var el = Ext.getCmp('obj-template-container');
        var val = e.getGroupValue();
		if (val !== null) {
			if (Number(val) == 2) {
				Ext.getCmp('obj-template').allowBlank=false;
				el.setVisible(true);
				Ext.getCmp('obj-wrapping').setValue(6);
			}
			else{
				Ext.getCmp('obj-template').allowBlank=true;
				el.setVisible(false);
				Ext.getCmp('obj-wrapping').setValue(3);
			}	
        }
    };

	var jsonReader = new Ext.data.JsonReader({
            root: 'data'
        }, [{
            name: 'TXTTITLE',
            type: 'string'
        }, {
            name: 'INTID',
            type: 'int'
        }, {
            name: 'INTORDERID',
            type: 'int'
        }, {
            name: 'INTCRATETYPEID',
            type: 'int'
        }, {
            name: 'INTCRATETEMPLATEID',
            type: 'int'
        }, {
            name: 'INTWRAPPING',
            type: 'int'
        }, {
            name: 'INTQUANTITY',
            type: 'int'
        }, {
            name: 'TXTOBJWEIGHT',
            type: 'string'
        }, {
            name: 'FLTCRATEWEIGHT',
            type: 'float'
        }, {
            name: 'FLTUNITPRICE',
            type: 'float'
        }, {
            name: 'FLTTOTALPRICE',
            type: 'float'
        }, {
            name: 'FLTOBJLENGTH',
            type: 'float'
        }, {
            name: 'FLTOBJWIDTH',
            type: 'float'
        }, {
            name: 'FLTOBJHEIGHT',
            type: 'float'
        }, {
            name: 'FLTINTLENGTH',
            type: 'float'
        }, {
            name: 'FLTINTWIDTH',
            type: 'float'
        }, {
            name: 'FLTINTHEIGHT',
            type: 'float'
        }, {
            name: 'FLTEXTLENGTH',
            type: 'float'
        }, {
            name: 'FLTEXTWIDTH',
            type: 'float'
        }, {
            name: 'FLTEXTHEIGHT',
            type: 'float'
        }, {
            name: 'FLTFLTLENGTH',
            type: 'float'
        }, {
            name: 'FLTFLTWIDTH',
            type: 'float'
        }, {
            name: 'FLTFLTHEIGHT',
            type: 'float'
        }, {
            name: 'INTCLIENTID',
            type: 'int'
        }, {
            name: 'BLNDELETED',
            type: 'boolean'
        }]
	);
	
    Rebul.Item.Edit.superclass.constructor.call(this, {
        id: 'item-panel',
        title: 'Add Crate (Step 1 of 2)',
        layout: 'card',
        activeItem: 0,
        width: 800,
        height: 370,
        border: true,
        frame: true,
        buttonAlign: 'center',
        url: 'jsonPricing.cfm',
        method: 'post',
		reader: jsonReader,
        buttons: [{
            id: 'btn-prev',
            text: '&laquo; Previous',
            handler: cardNav.createDelegate(this, [-1]),
            disabled: true
        }, {
            id: 'btn-next',
            text: 'Next &raquo',
            handler: cardNav.createDelegate(this, [1])
        }, {
            id: 'btn-add',
            text: 'Get Price',
            iconCls: 'addCart',
            hidden: true,
            tooltip: 'Save item. Note: you will have the option to save your quote for later.',
            handler: this.submitForm.createDelegate(this)
        }],
        items: [{
            //////////////////////////////////////
            //////////////////////////////////////
            ///    Card 0, Step 1 of Wizard     //
            //////////////////////////////////////
            //////////////////////////////////////
            id: 'card-0',
            layout: 'table',
            cls: 'divToCenter',
            defaults: {
                bodyStyle: 'text-align:center',
                border: false
            },
            layoutConfig: {
                columns: 2
            },
            items: [{
                html: '&nbsp;',
                cls: 'crateStandard'
            }, /*{
                html: '&nbsp;',
                cls: 'crateLite'
            },*/ {
                html: '&nbsp;',
                cls: 'crateSpecialty'
            }, {
                items: {
                    //////////////////////////////
                    // "Standard" crate type radio field
                    //////////////////////////////
                    xtype: 'radio',
                    name: 'INTCRATETYPEID',
                    boxLabel: 'Standard Crate',
                    inputValue: 1,
                    checked: true,
                    listeners: {
                        'check': function(){
                            toggleTemplate(this);
                        }
                    }
                }
            }, /* {
                items: {
                    //////////////////////////////
                    // "Lite" crate type radio field
                    //////////////////////////////
                    xtype: 'radio',
                    name: 'INTCRATETYPEID',
                    boxLabel: 'Lite Crate',
                    inputValue: 3,
                    listeners: {
                        'check': function(){
                            toggleTemplate(this);
                        }
                    }
                }
            },*/ {
                items: {
                    //////////////////////////////
                    // "Specialty" crate type radio field
                    //////////////////////////////
                    xtype: 'radio',
                    name: 'INTCRATETYPEID',
                    boxLabel: 'Specialty Crate',
                    inputValue: 2,
                    listeners: {
                        'check': function(){
                            toggleTemplate(this);
                        }
                    }
                }
            }]
        }, {
            //////////////////////////////////////
            //////////////////////////////////////
            ///    Card 1, Step 2 of Wizard     //
            //////////////////////////////////////
            //////////////////////////////////////
            id: 'card-1',
			bodyStyle: 'padding-top:20px',
            items: [{
                xtype: 'fieldset',
                title: 'Object Information',
            	cls: 'divToCenter',
				width:550,
                autoHeight: true,
                defaults: {
                    layout: 'form',baseCls:'x-plain'
                },
                items: [{
                    id: 'obj-template-container',
                    height: 30,
					labelWidth:123,
					defaults:{width:356},
                    hidden: true,
                    items: {
                        //////////////////////////////
                        // "Specialty Crate" combo box
                        //////////////////////////////
                        xtype: 'combo',
						listWidth: 356,
                        fieldLabel: 'Specialty Crate',
                        id: 'obj-template',
                        hiddenName: 'INTCRATETEMPLATEID',
                        store: this.config.ts,
                        displayField: 'title',
                        valueField: 'id',
                        forceSelection: true,
                        allowBlank: true,
                        emptyText: 'Other',
                        triggerAction: 'all',
                        emptyValue: 0,
                        mode: 'local',
                        listeners: {
                            "select": function(){
                                Ext.getCmp('obj-title').setValue(Ext.getDom('obj-template').value);
                            }
                        },
						alignErrorIcon:function(){
							this.errorIcon.alignTo(this.el, 'tl-tr',[2+this.el.next().getWidth(), 0]);
						}
                    }
                }, {
                    height: 30,
					labelWidth:123,
					defaults:{width:373},
                    items: {
                        //////////////////////////////
                        // "Object Description textfield
                        //////////////////////////////
                        xtype: 'textfield',
                        id: 'obj-title',
                        fieldLabel: 'Object Description',
                        name: 'TXTTITLE',
                        allowBlank: false
                    }
                }, {
					xtype:'panel',
                    layout: 'column',
                    defaults: {width: 128,layout:'form',baseCls:'x-plain',height: 30,labelWidth: 45},
                    items: [{
						defaults:{width:50},
                        items: {
                            //////////////////////////////
                            // "Object Length" numberfield
                            //////////////////////////////
                            id: 'obj-length',
                            xtype: 'numberfield',
                            fieldLabel: 'Length',
                            name: 'FLTOBJLENGTH',
                            allowBlank: false
                        }
                    }, {
						defaults:{width:50},
                        items: {
                            //////////////////////////////
                            // "Object Width" numberfield
                            //////////////////////////////
                            id: 'obj-width',
                            xtype: 'numberfield',
                            fieldLabel: 'Width',
                            name: 'FLTOBJWIDTH',
                            allowBlank: false
                        }
                    }, {
						defaults:{width:50},
                        items: {
                            //////////////////////////////
                            // "Object Height" numberfield
                            //////////////////////////////
                            id: 'obj-height',
                            xtype: 'numberfield',
                            fieldLabel: 'Height',
                            name: 'FLTOBJHEIGHT',
                            allowBlank: false
                        }
                    }, {
						defaults:{width:49},
                        items: {
                            //////////////////////////////
                            // "Units of Measurement" combobox
                            //////////////////////////////
                            id: 'obj-unit',
                            xtype: 'combo',
                            fieldLabel: 'Units',
                            name: 'TXTUNIT',
                            value: 'cm',
                            store: ['mm', 'cm'],
                            triggerAction: 'all',
                            editable: false,
                            mode: 'local'
                        }
                    }]
                }, {
                    height: 30,
					labelWidth:173,
					defaults:{width:356},					
                    items: {
                        //////////////////////////////
                        // "Wrapping" combo box
                        //////////////////////////////
                        id: 'obj-wrapping',
                        xtype: 'combo',
						listWidth:144,
                        fieldLabel: 'Wrapping tolerance (cm)',
                        name: 'INTWRAPPING',
                        allowBlank: false,
                        value: '3',
                        store: ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '12', '15', '20'],
                        editable: false,
                        triggerAction: 'all',
                        mode: 'local',
						helpText: 'The additional space allowance for wrapping and packing, on top of the provided object dimensions.',
						afterRender: function(){
							var label = findLabel(this);
							var helpImage = label.createChild({
								tag:'img',
								src:'http://img.bokkaassets.com/fam/information.png',
								style:'float:right;margin:0px 4px 0 0;padding:0;',
								width:16,
								height:16
							});
							Ext.QuickTips.register({
								target:helpImage,
								text:this.helpText,
								enabled:true
							});
							this.setValue(3);
						}
                    }
                },{
                    height: 30,
					labelWidth:173,
					defaults:{width:306},
                    items: {
                        //////////////////////////////
                        // "Object Weight" combo box
                        //////////////////////////////
                        id: 'obj-weight',
                        xtype: 'combo',
						width:147,
						listWidth:144,
                        fieldLabel: 'Object Weight',
                        name: 'TXTOBJWEIGHT',
                        allowBlank: false,
                        value: '0-50 kg',
                        store: ['0-50 kg', '51-100 kg', '101-200 kg', 'over 200 kg'],
                        editable: false,
                        triggerAction: 'all',
                        mode: 'local'
                    }
                }, {
                    height: 30,
					labelWidth:173,
					defaults:{width:306},
                    items: {
                        //////////////////////////////
                        // "Quantity" combo box
                        //////////////////////////////
                        id: 'obj-quantity',
                        xtype: 'combo',
						width:147,
						listWidth: 144,
                        fieldLabel: 'Crate Quantity',
                        name: 'INTQUANTITY',
                        allowBlank: false,
                        value: 1,
                        store: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
                        editable: true,
                        forceSelection: false,
                        typeAhead: false,
                        triggerAction: 'all',
                        mode: 'local'
                    }
                }, {
                    id: 'obj-unitPrice',
                    xtype: 'hidden',
                    name: 'FLTUNITPRICE'
                }, {
                    id: 'obj-totalPrice',
                    xtype: 'hidden',
                    name: 'FLTTOTALPRICE',
                    value: 0
                }, {
                    xtype: 'hidden',
                    name: 'INTID',
					value: 0
                }, {
                    xtype: 'hidden',
                    name: 'INTORDERID',
					value: 0
                }, {
                    id: 'il',
                    xtype: 'hidden',
                    name: 'FLTINTLENGTH'
                }, {
                    id: 'iw',
                    xtype: 'hidden',
                    name: 'FLTINTWIDTH'
                }, {
                    id: 'ih',
                    xtype: 'hidden',
                    name: 'FLTINTHEIGHT'
                }, {
                    id: 'el',
                    xtype: 'hidden',
                    name: 'FLTEXTLENGTH'
                }, {
                    id: 'ew',
                    xtype: 'hidden',
                    name: 'FLTEXTWIDTH'
                }, {
                    id: 'eh',
                    xtype: 'hidden',
                    name: 'FLTEXTHEIGHT'
                }, {
                    id: 'fl',
                    xtype: 'hidden',
                    name: 'FLTFLTLENGTH'
                }, {
                    id: 'fw',
                    xtype: 'hidden',
                    name: 'FLTFLTWIDTH'
                }, {
                    id: 'fh',
                    xtype: 'hidden',
                    name: 'FLTFLTHEIGHT'
                }, {
                    xtype: 'hidden',
                    name: 'INTCLIENTID',
                    value: this.config.clientID || 0
                }]
            }]
        }, {
            //////////////////////////////////////
            //////////////////////////////////////
            ///    Card 2, Step 3 of Wizard     //
            //////////////////////////////////////
            //////////////////////////////////////
            id: 'card-2',
			bodyStyle: 'padding-top:20px',
            border: true,
            items: [{
                xtype: 'fieldset',
                title: 'Summary',
                width: 550,
                cls: 'divToCenter',
                autoHeight: true,
                items: [{
                    items: [{
                        html: '' +
                        '<table id="summaryTable">' +
                        '	<tr class="stripe">' +
                        '		<td width="50%" class="labelCell">Crate Type:</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjCrateType"></span><span id="txtObjCrateTemplate"></span></td>' +
                        '	</tr>' +
                        '	<tr>' +
                        '		<td width="50%" class="labelCell">Object Description:</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjDescription"></span></td>' +
                        '	</tr>' +
                        '	<tr class="stripe">' +
                        '		<td width="50%" class="labelCell">Object Dimensions (mm):</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjDimensions"></span></td>' +
                        '	</tr>' +
                        '	<tr>' +
                        '		<td width="50%" class="labelCell">Object Weight:</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjWeight"></span></td>' +
                        '	</tr>' +
                        '	<tr class="stripe">' +
                        '		<td width="50%" class="labelCell">Wrapping Tolerance:</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjWrapping"></span></td>' +
                        '	</tr>' +
                        '	<tr>' +
                        '		<td width="50%" class="labelCell">Quantity:</td>' +
                        '		<td width="50%" class="dataCell"><span id="txtObjQuantity"></span></td>' +
                        '	</tr>' +
                        '	<tr class="stripe">' +
                        '		<td width="50%" class="labelCell">Unit Price (excl GST):</td>' +
                        '		<td width="50%" class="dataCell blue"><span id="txtObjUnitPrice"></span></td>' +
                        '	</tr>' +
                        '	<tr>' +
                        '		<td width="50%" class="labelCell">Total Price (excl GST):</td>' +
                        '		<td width="50%" class="dataCell blue bold"><span id="txtObjTotalPrice"></span></td>' +
                        '	</tr>' +
                        '</table>'
                    
                    }]
                }]
            }]
        }]
    });
};
Ext.extend(Rebul.Item.Edit, Ext.FormPanel, {
    afterRender: function(){
		Rebul.Item.Edit.superclass.afterRender.call(this);
        if (this.config.intID) {
            this.form.load({
                url: 'jsonGateway.cfm?tablename=' + this.config.tablename + '&intID=' + this.config.intID,
                waitMsg: 'Loading Item',
				success:this.convertToCm
            });
        }
    },
    setPanelTitle: function(v){
        this.setTitle('Add Crate (Step ' + (v + 1) + ' of 2)');
    },
	convertToCm:function(){
		var f = Ext.getCmp('item-panel').getForm();
		f.findField('INTWRAPPING').setValue(f.findField('INTWRAPPING').getValue()/10);
		f.findField('FLTOBJHEIGHT').setValue(f.findField('FLTOBJHEIGHT').getValue()/10);
		f.findField('FLTOBJWIDTH').setValue(f.findField('FLTOBJWIDTH').getValue()/10);
		f.findField('FLTOBJLENGTH').setValue(f.findField('FLTOBJLENGTH').getValue()/10);
	},
    getPricing: function(){
		if (this.form.isValid()) {
			this.form.submit({
				url: this.url,
				method: 'post',
				scope: this,
				waitMsg: 'Retrieving Price...',
				failure: function(form, action){
					Ext.MessageBox.alert('Error', 'The price could not be retrieved as planned.');
				},
				success: function(form, action){
					var cardNext = Ext.getCmp('btn-next');
					var add2Cart = Ext.getCmp('btn-add');
					var crateType = Number(this.getForm().findField('INTCRATETYPEID').getGroupValue());
					var crateText = '';
					this.getForm().setValues(action.result.data);
					if (crateType == 1) {
						crateText = 'Standard';
					}
					else 
						if (crateType == 3) {
							crateText = 'Lite';
						}
						else 
							if (crateType == 2) {
								crateText = 'Specialty (' + Ext.fly('obj-template').getValue() + ')';
							};
					Ext.getDom('txtObjCrateType').innerHTML = crateText;
					Ext.getDom('txtObjDescription').innerHTML = Ext.fly('obj-title').getValue();
					Ext.getDom('txtObjDimensions').innerHTML = 'Length: ' + Ext.fly('obj-length').getValue() + ' | Width: ' + Ext.fly('obj-width').getValue() + ' | Height: ' + Ext.fly('obj-height').getValue();
					Ext.getDom('txtObjWeight').innerHTML = Ext.fly('obj-weight').getValue();
					Ext.getDom('txtObjWrapping').innerHTML = Ext.fly('obj-wrapping').getValue();
					Ext.getDom('txtObjQuantity').innerHTML = Ext.fly('obj-quantity').getValue();
					Ext.getDom('txtObjUnitPrice').innerHTML = Ext.util.Format.usMoney(Ext.fly('obj-unitPrice').getValue());
					Ext.getDom('txtObjTotalPrice').innerHTML = Ext.util.Format.usMoney(Ext.fly('obj-totalPrice').getValue());
					//Ext.getDom('intDim').innerHTML = Ext.fly('il').getValue() + ' x ' + Ext.fly('iw').getValue() + ' x ' + Ext.fly('ih').getValue();
					//Ext.getDom('extDim').innerHTML = Ext.fly('el').getValue() + ' x ' + Ext.fly('ew').getValue() + ' x ' + Ext.fly('eh').getValue();
					//Ext.getDom('fltDim').innerHTML = Ext.fly('fl').getValue() + ' x ' + Ext.fly('fw').getValue() + ' x ' + Ext.fly('fh').getValue();
					cardNext.setDisabled(true);
					add2Cart.setVisible(true);
					this.getLayout().setActiveItem(2);
				}
			});
		}
		else{
			Ext.MessageBox.alert('Sorry', 'There are fields on the form that still required your attention.');
		}
    },
    submitForm: function(){
        if (this.form.isValid()) {
			this.standardSubmit = true;
			if (this.getForm().findField('INTORDERID').getValue() == 0) {
				this.getForm().findField('INTORDERID').setValue(this.config.orderID);
			}
			this.getForm().getEl().dom.action = this.config.url;
			this.getForm().getEl().dom.submit();			            
        }
        else {
            Ext.MessageBox.alert('Sorry', 'There are fields on the form that still required your attention.');
        }
    }
});

Rebul.Item.List = function(config){
    this.myPageSize = 8;
    this.config = config || {};
	this.config.orderID = this.config.orderID || 0;
	this.config.tablename = this.config.tablename || 'cart';
	this.config.url = this.config.tablename == 'cart' ? 'viewcart.cfm' : 'viewcart_saved.cfm';
	this.config.readonly = this.config.readonly || false;
    
    var selectBoxModel = new Ext.grid.CheckboxSelectionModel();
    selectBoxModel.on('selectionchange', function(sm){
        if (sm.getSelections().length > 0) {
            Ext.getCmp('item-delete-button').enable();
            if (sm.getSelections().length == 1) {
                Ext.getCmp('item-edit-button').enable();
            }
            else {
                Ext.getCmp('item-edit-button').disable();
            }
        }
        else {
            Ext.getCmp('item-delete-button').disable();
            Ext.getCmp('item-edit-button').disable();
        }
    }, this);
    
    var menubar = [{
        id: 'item-add-button',
        text: 'Add Crate',
        tooltip: 'Add Crate',
        iconCls: 'addItem',
		config: this.config,
        handler: function(){
            location.href = 'additem.cfm?tablename=' + this.config.tablename + '&orderID=' + this.config.orderID;
        }
    }, '-', {
        id: 'item-edit-button',
        text: 'Edit Crate',
        tooltip: 'Edit the selected item',
        iconCls: 'editItem',
		config: this.config,
        disabled: true,
        handler: function(){
            var record = Ext.getCmp('item-grid').getSelectionModel().getSelected();
            location.href = 'additem.cfm?tablename=' + this.config.tablename + '&orderID=' + this.config.orderID + '&intID=' + record.id;
        }
    }, '-', {
        id: 'item-delete-button',
        text: 'Delete Crate',
        tooltip: 'Delete the selected item',
        iconCls: 'remove',
		config: this.config,
        disabled: true,
        handler: function(){
            var record = Ext.getCmp('item-grid').getSelectionModel().getSelected();
			location.href = this.config.url + '?deleteID=' + record.id;
        }
    }];    
    
    this.dataStore = new Rebul.Store({
        url: 'jsonGateway.cfm?tablename=' + config.tablename + '&orderID=' + config.orderID,
        fields: [{
            name: 'INTID',
            type: 'int'
        }, {
            name: 'INTORDERID',
            type: 'int'
        }, {
            name: 'INTCLIENTID',
            type: 'int'
        }, {
            name: 'INTCRATETYPEID',
            type: 'int'
        }, {
            name: 'INTCRATETEMPLATEID',
            type: 'int'
        }, {
            name: 'INTWRAPPING',
            type: 'int'
        }, {
            name: 'INTQUANTITY',
            type: 'int'
        }, {
            name: 'INTORDERQUANTITY',
            type: 'int'
        }, {
            name: 'TXTTITLE',
            type: 'string'
        }, {
            name: 'TXTOBJWEIGHT',
            type: 'string'
        }, {
            name: 'FLTORDERPRICE',
            type: 'float'
        }, {
            name: 'FLTCRATEWEIGHT',
            type: 'float'
        }, {
            name: 'FLTUNITPRICE',
            type: 'float'
        }, {
            name: 'FLTTOTALPRICE',
            type: 'float'
        }, {
            name: 'FLTOBJLENGTH',
            type: 'float'
        }, {
            name: 'FLTOBJWIDTH',
            type: 'float'
        }, {
            name: 'FLTOBJHEIGHT',
            type: 'float'
        }, {
            name: 'FLTINTLENGTH',
            type: 'float'
        }, {
            name: 'FLTINTWIDTH',
            type: 'float'
        }, {
            name: 'FLTINTHEIGHT',
            type: 'float'
        }, {
            name: 'FLTEXTLENGTH',
            type: 'float'
        }, {
            name: 'FLTEXTWIDTH',
            type: 'float'
        }, {
            name: 'FLTEXTHEIGHT',
            type: 'float'
        }, {
            name: 'FLTFLTLENGTH',
            type: 'float'
        }, {
            name: 'FLTFLTWIDTH',
            type: 'float'
        }, {
            name: 'FLTFLTHEIGHT',
            type: 'float'
        }]
    });
    
    this.dataStore.load({
		loadMask: {
            msg: 'Loading Items'
        }
	});
	
	this.dataStore.on('load',function(){
		if(this.getTotalCount()){
			if(Ext.getCmp('btnSave')){
				Ext.getCmp('btnSave').enable();
			}
			if(Ext.getCmp('btnOrder')){
				Ext.getCmp('btnOrder').enable();
			}
		}
	});
    
    Rebul.Item.List.superclass.constructor.call(this, {
        id: 'item-grid',
        width: 800,
        autoHeight: true,
        title: 'Current Quote',
        ds: this.dataStore,
        sm: selectBoxModel,
        waitMsg: 'Loading items',
        tbar: menubar,
        bbar: new Ext.Toolbar({
            autoHeight: true,
            items: ['->', {
                xtype: 'tbtext',
                text: '<div id="bbarText" style="float:right;padding:5px;text-align:right;width:200px;color:#4379C3;font-weight:bold;">$0</div>'
            }]
        }),
        enableColumnHide: false,
        stripeRows: true,
        columns: [{
            id: 'id',
            header: 'Identify',
            dataIndex: 'INTID',			
            hidden: true
        }, {
			header: 'Crate Info',
			dataIndex: 'INFO',
			width:58,
			sortable:false,
			align:'center',
			renderer:this.infoRenderer.createDelegate(this)
		}, {
            header: 'Object Description',
            dataIndex: 'TXTTITLE',
            width: 179,
            sortable: true
        }, {
            header: 'Object Length (mm)',
            dataIndex: 'FLTOBJLENGTH',
            width: 104,
            sortable: true,
            align: 'right'
        }, {
            header: 'Object Width (mm)',
            dataIndex: 'FLTOBJWIDTH',
            width: 99,
            sortable: true,
            align: 'right'
        }, {
            header: 'Object Height (mm)',
            dataIndex: 'FLTOBJHEIGHT',
            width: 102,
            sortable: true,
            align: 'right'
        }, {
            header: 'Wrapping (mm)',
            dataIndex: 'INTWRAPPING',
            width: 86,
            sortable: true,
            align: 'right'
        }, {
            header: 'Quantity',
            dataIndex: 'INTQUANTITY',
            width: 52,
            sortable: true,
            align: 'right'
        }, {
            header: 'Unit Price (excl GST)',
            dataIndex: 'FLTUNITPRICE',
            width: 115,
            sortable: false,
            renderer: 'usMoney',
            align: 'right'
        }]
    });
    
    this.on('rowdblclick', function(gridPanel, rowIndex, e){
		if (!this.config.readonly) {
			var selectedId = this.dataStore.data.items[rowIndex].id;
			location.href = 'additem.cfm?tablename=' + this.config.tablename + '&orderID=' + this.config.orderID + '&intID=' + selectedId;
		}
    });
        
    this.on('beforerender', this.beforeRenderTasks);
	
	this.getView().on('beforerefresh',this.setTotal);
    
};
Ext.extend(Rebul.Item.List, Ext.grid.GridPanel, {
	afterRender: function(){
		Rebul.Item.List.superclass.afterRender.call(this);
        if (this.config.readonly) {
			Ext.getCmp('item-grid').hideTbar();
        }
    },
	beforeRenderTasks: function(){
		this.setTotal();
		if (this.config.tablename !== 'cart') {
			if(this.config.readonly)
				Ext.getCmp('item-grid').setTitle('Crates Ordered');
			else
				Ext.getCmp('item-grid').setTitle('Viewing Quote: ' + this.config.reference);	
		}
	},	
    setTotal: function(){
		var el = Ext.getCmp('item-grid');
       	if (el.store.getAt(0) !== undefined) {
            var totalVal = el.store.getAt(0).get('FLTORDERPRICE') || 0;
			Ext.getDom('bbarText').innerHTML = 'Total Price (excl GST): ' + Ext.util.Format.usMoney(totalVal);
        }       
    },
	saveCart: function(config){
		config = config || {};
		new Rebul.Item.Window(config);			
	},
	placeOrder:function(config){
		config = config || {};
		config.status = 'order';
		new Rebul.Item.Window(config);
	},
	infoRenderer: function(val, cell, record){
		var data = record.data;
		var qtip = this.qtipTpl.apply(data);
		return '<div qtip="' + qtip + '" style="height:16px;width:50px;background:url(http://img.bokkaassets.com/fam/information.png) no-repeat 50% 0">&nbsp;</div>';
	},
	qtipTpl:new Ext.XTemplate(
		'<h3>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Crate Dimensions (mm):</h3>',
		'<div>',  
		'	<table width=300 cellpadding=2 cellspacing=2 border=0>',
		'	 	<tr>',
		'			<td width=60>&nbsp;</td>',
		'			<td><b>Length</b></td>',
		'			<td><b>Width</b></td>',
		'			<td><b>Height</b></td>',
		'		</tr>',
		'		<tr>',
		'			<td><b>Internal</b></td>',
		'			<td>{FLTINTLENGTH}</td>',
		'			<td>{FLTINTWIDTH}</td>',
		'			<td>{FLTINTHEIGHT}</td>',
		'		</tr>',
		'		<tr>',
		'			<td><b>External</b></td>',
		'			<td>{FLTEXTLENGTH}</td>',
		'			<td>{FLTEXTWIDTH}</td>',
		'			<td>{FLTEXTHEIGHT}</td>',
		'		</tr>',
		'		<tr>',
		'			<td><b>Flatpack</b></td>',
		'			<td>{FLTFLTLENGTH}</td>',
		'			<td>{FLTFLTWIDTH}</td>',
		'			<td>{FLTFLTHEIGHT}</td>',
		'		</tr>',
		'	</table>',
		'</div>'
	)	
});

Rebul.Item.Window = function(config){
   	var currentDate = new Date();
   	currentDate = addWorkingDays(currentDate,3);
		
	this.config = config || {};	
	this.config.status = this.config.status || 'quote';
	this.config.orderID = this.config.orderID || 0;
	this.config.url = this.config.status == 'quote' ? 'savedcarts.cfm?orderID=' + this.config.orderID : 'orderhistory.cfm?orderID=' + this.config.orderID;
		
	Ext.QuickTips.init();
   	Ext.form.Field.prototype.msgTarget = 'side';
	
	var formPanel = new Ext.form.FormPanel({ 
        id: 'formPanel',
		config: this.config,
		labelWidth:150,
        baseCls: 'x-plain',
        bodyStyle:'padding:10px 0 10px 10px',
        frame:true,
		autoHeight:true,
        autoWidth: true,
		standardSubmit:true,
		defaults: {
			width: 140,
			layout: 'form',
			anchor: '94%'
		},
        items: [{
			xtype: 'textfield',
			id: 'quote-field1',
			fieldLabel: 'Reference Number',
			name: 'TXTREFERENCE',
            allowBlank: false,
			value:this.config.q1 || undefined
		}, new Ext.ux.form.XDateField({
				name:'DTREQUESTED',
				id: 'quote-field2',
				fieldLabel:'Expected Delivery Date',
				submitFormat:'Y-m-d',
				format:'d/m/Y',
				minValue:currentDate,
				disabledDays:[0,6],
				readOnly:true,
				showToday:false,
				allowBlank:false,
				value:this.config.q2 || undefined
		}), {
			id: 'order-requirements',
			baseCls: 'x-plain',
			hidden:this.config.status=='quote',
			autoWidth:true,
			defaults:{width:140,layout:'form',anchor:'94%'},
			items:[{
				xtype: 'textfield',
				id: 'order-field1',
				fieldLabel: 'Purchase Order',
				name: 'TXTPURCHASEORDER',
				allowBlank:true,
				value:this.config.o1 || undefined
			},{
				xtype: 'textarea',
				id: 'order-field2',
				fieldLabel: 'Delivery Address',
				name: 'TXTSHIPPINGADDRESS',
				height:50,
				allowBlank:true,
				value:this.config.o2 || undefined
			}]
		}]
	});
	
	formPanel.submitForm = function() {
        if (formPanel.form.isValid()) {
			formPanel.form.getEl().dom.action = formPanel.config.url;
		    formPanel.form.getEl().dom.submit();			
	    } else{
			Ext.MessageBox.alert('Errors', 'Please fix the errors noted.');
		}             
    };
		
    Rebul.Item.Window.superclass.constructor.call(this, {
		id:'confirm-save',
		title:'Save quote for later',
		width:360,
		autoHeight:true,
		minWidth:350,
		minHeight:250,
		layout:'fit',
		bodyStyle:'padding:5px',
		buttonAlign:'right',
		modal:true,
		items: formPanel,
		buttons: [{
			id:'saveBtn',
            text: 'Save/Close', 		
 			iconCls:'saveItem',
            handler: formPanel.submitForm
		},{
            text: 'Cancel',
	        iconCls:'cancelItem',
            handler: function(){
				Ext.getCmp('confirm-save').close();
			}
        }]
	});
	
	this.on('beforerender',function(){
		if(this.config.status=='order'){
			this.setTitle('Place crate order');
			Ext.getCmp('order-field1').allowBlank = false;
			Ext.getCmp('order-field2').allowBlank = false;
			var saveBtn = Ext.getCmp('saveBtn');
			saveBtn.setText('Place Order');
			saveBtn.setIconClass('placeOrder');
		}
	});
	
	this.show();
};
Ext.extend(Rebul.Item.Window, Ext.Window, {});

