Ext.util.Format.dkMoney = function(v){
  v = (Math.round(v*100))/100;
  v = (v == Math.floor(v)) ? v + ".00" : ((v*10 == Math.floor(v*10)) ? v + "0" : v);
  v = String(v);
  var ps = v.split('.'),
  whole = ps[0],
  sub = ps[1] ? ','+ ps[1] : ',00',
  r = /(\d+)(\d{3})/;
  while (r.test(whole)) {
    whole = whole.replace(r, '$1' + '.' + '$2');
  }
  v = whole + sub;
  if(v.charAt(0) == '-'){
    return '(kr. ' + v.substr(1)+')';
  }
  return "kr. " +  v;
}
Ext.namespace('cmv.cloth');

cmv.cloth.colModel=Ext.extend(Ext.grid.ColumnModel,{
  constructor:function(config){
    config=Ext.apply({
      columns:[
      {
        id:'antal',
        header: 'Antal',
        width: 35,
        dataIndex: 'antal'
      },{
        id:'artikel',
        header: 'Artikel',
        width: 225,
        dataIndex: 'artikel'
      },{
        id:'size',
        header: 'Str.',
        width: 60,
        dataIndex: 'size'
      },
      {
        header: 'Pris',
        width: 75,
        renderer: 'dkMoney',
        dataIndex: 'pris',
        align:'right'
      }
      ],
      defaults:{
        sortable:false
      }
    },config);
    cmv.cloth.colModel.superclass.constructor.call(this, config);
  }
})

//Extension holding availabe sizes depending on cloth type
cmv.cloth.storeSize = Ext.extend(Ext.data.JsonStore,{
  type:'',
  constructor:function(config){
    config=Ext.apply({
      autoDestroy: true,
      url: 'json/clothsize.php?type='+config.type,
      // reader configs
      idProperty: 'sizeID',
      root: 'data',
      totalProperty: 'total',
      fields: [{
        name:'value',
        type:'int'
      }, {
        name:'text'
      }]
    },config);
    cmv.cloth.storeSize.superclass.constructor.call(this, config);
  }
});

cmv.cloth.sizeComboBox = Ext.extend(Ext.form.ComboBox,{
  clothtype: '',
  formButton: undefined,
  useButton: true,
  store: undefined,
  clothid:'',
  constructor: function(config){
    config = Ext.apply({
      displayField: 'text',
      valueField: 'value',
      typeAhead: true,
      triggerAction: 'all',
      mode: 'local',
      emptyText: 'Vælg størrelse',
      selectOnFocus: true,
      forceSelection: true,
      id:config.clothtype+'size'+config.clothid,
      hiddenName: config.clothid+'size'+config.clothtype,
      width:130
    }, config);
    cmv.cloth.sizeComboBox.superclass.constructor.call(this, config);
    this.on({
      change:{
        fn: function(field, newVal, oldVal){
          if(this.useButton)
            this.formButton.enable();
          else          
            Ext.getCmp('clothordergrid').updateSizeData(this.clothid,this.getRawValue());          
        }
      }
    })
    if(this.clothtype==='')
    {
      this.disable();
      this.emptyText='One Size';
    }
  },
  setValue: function(value){
    if(value!=11)
      cmv.cloth.sizeComboBox.superclass.setValue.call(this,value);
    else
      cmv.cloth.sizeComboBox.superclass.clearValue.call(this);
  }
});

Ext.reg('cmvclothsizecombobox', cmv.cloth.sizeComboBox);

cmv.cloth.ArrayComboBox = Ext.extend(Ext.form.ComboBox,{
  clothid:undefined,
  type:undefined,
  grundpakke:false,
  data: [],
  constructor: function(config){
    config = Ext.apply({
      store : new Ext.data.ArrayStore({
        fields: [{
          name: 'value',
          type:'int'
        },
        {
          name: 'text'
        }
        ]
      }),
      hiddenName:config.clothid+(config.grundpakke?'gp':'')+config.type,
      displayField: 'text',
      valueField: 'value',
      typeAhead: true,
      triggerAction: 'all',
      mode: 'local',
      selectOnFocus: true,
      forceSelection: true,
      width:130,
      id: (config.grundpakke?'gp':'')+config.type+config.clothid,
      listeners: {
        change:{
          fn: function(field, newVal, oldVal){
            Ext.getCmp('clothordergrid').updateDescData(this.clothid);
          }
        }
      }
    }, config);
    cmv.cloth.ArrayComboBox.superclass.constructor.call(this, config);
    this.store.loadData(this.data);
  },
  getSizeCode:function(code){
    var sizecode=cmv.cloth.getSizeCode(code)+(this.grundpakke?'gp':'')+'size'+this.clothid;
    return Ext.getCmp(sizecode).getRawValue();
  }
});

cmv.cloth.getSizeCode=function(code){
  var sizecode;
  switch(code)
  {
    case 1:
      sizecode='bluse';
      break;
    case 2:
      sizecode='bukser';
      break;
    case 3:
      sizecode='handsker';
      break;
    case 4:
      sizecode='stroemper';
      break;
    case 5:
      sizecode='sko';
      break;
    case 7:
      sizecode='blusemf';
      break;
    default:
      sizecode='';
  }
  return sizecode
}

Ext.reg('cmvclotharraycombobox', cmv.cloth.sizeComboBox);

cmv.cloth.amountComboBox = Ext.extend(cmv.cloth.ArrayComboBox,{
  data:[[1,'1 stk.'],[2,'2 stk.'],[3,'3 stk.'],[4,'4 stk.']],
  constructor: function(config){
    config = Ext.apply({
      type:'antal',
      emptyText: 'Vælg antal',
      width:90,
      listeners: {
        change:{
          fn: function(field, newVal, oldVal){
            var rec = cmv.cloth.store.getAt(cmv.cloth.store.find('Varenummer',this.clothid));
            if(oldVal=='')
            {
              var size = this.getSizeCode(rec.get('sizecode'));
              var item = rec.get('item');
              if(rec.get('sizecode')==2)
              {
                item+=', '+Ext.getCmp('seler'+this.clothid).getRawValue();
                if(!Ext.getCmp('skind'+this.clothid).disabled)
                  item+=', '+Ext.getCmp('skind'+this.clothid).getRawValue()
              }
              Ext.getCmp('clothordergrid').addData([newVal,item,size,rec.get('price'),rec.get('Varenummer')]);
            }
            if(newVal=='')
              Ext.getCmp('clothordergrid').deleteData(rec.get('Varenummer'));
            if(newVal!=''&&oldVal!='')
              Ext.getCmp('clothordergrid').updateData(rec.get('Varenummer'),newVal,rec.get('price'));
          }
        }
      }
    }, config);
    cmv.cloth.amountComboBox.superclass.constructor.call(this, config);
  }
});

Ext.reg('cmvclothamountcombobox', cmv.cloth.amountComboBox);

cmv.cloth.selerComboBox = Ext.extend(cmv.cloth.ArrayComboBox,{
  data:[[0,'u/seler'],[1,'m/seler']],
  constructor: function(config){
    config = Ext.apply({
      type: 'seler',
      value:1,
      emptyText: 'Vælg seler',
      allowBlank: false
    }, config);
    cmv.cloth.selerComboBox.superclass.constructor.call(this, config);
  }
});

Ext.reg('cmvclothselercombobox', cmv.cloth.sizeComboBox);

cmv.cloth.skindComboBox = Ext.extend(cmv.cloth.ArrayComboBox,{
  data:[[0,'skindindlæg herrer'],[1,'skindindlæg damer']],
  kvinde: false,
  constructor: function(config){
    config = Ext.apply({
      type: 'skind',
      emptyText: 'Vælg skind',
      allowBlank: true
    }, config);
    cmv.cloth.skindComboBox.superclass.constructor.call(this, config);
  }
});

Ext.reg('cmvclothskindcombobox', cmv.cloth.sizeComboBox);

cmv.cloth.FormTab = Ext.extend(Ext.Panel,{
  type:undefined,
  constructor: function(config){
    config=Ext.apply({
      layout:'form',
      labelWidth:300,
      id:'cmvclothformtab'+config.type
    },config);
    cmv.cloth.FormTab.superclass.constructor.call(this, config);
    var gp=false;
    switch(this.type)
    {
      case 1:
        this.setTitle('Overdele');
        cmv.cloth.store.filter({
          fn:function(rec){
            return rec.get('sizecode')==1||rec.get('sizecode')==7;
          }
        });
        break;
      case 2:
        this.setTitle('Bukser');
        clothtype='bukser';
        cmv.cloth.store.filter('sizecode',2);
        break;
      case 3:
        this.setTitle('Grundpakke');
        cmv.cloth.store.filter({
          fn:function(rec){
            return rec.get('grundpakke')&&rec.get('Varenummer')!=1;
          }
        });
        gp=true;
        break;
      default:
        this.setTitle('Diverse');
        cmv.cloth.store.filter({
          fn:function(rec){
            return rec.get('Varenummer')!=1&&rec.get('sizecode')!=1&&rec.get('sizecode')!=2&&rec.get('sizecode')!=7;
          }
        });
    }
    cmv.cloth.store.each(function(rec){
      var store=cmv.cloth.storeClothSize;
      var clothtype=cmv.cloth.getSizeCode(rec.get('sizecode'));
      var clothid=rec.get('Varenummer');
      var items=[new cmv.cloth.amountComboBox({
        clothid:clothid,
        grundpakke:gp,
        value:gp?1:undefined,
        disabled:gp
      })];
      //Special handling for sizecodes
      switch(rec.get('sizecode'))
      {
        case 1:
          break;
        case 2:
          var uden=rec.get('item').indexOf('uden')!=-1;
          items.push([new cmv.cloth.selerComboBox({
            clothid:clothid,
            disabled:!rec.get('seler'),
            grundpakke:gp
          }),new cmv.cloth.skindComboBox({
            clothid:clothid,
            emptyText:uden?'Uden skind':'Vælg skind',
            disabled:uden,
            grundpakke:gp
          })]);
          break;
        case 7:
          break;
        default:
          switch(rec.get('sizecode'))
          {
            case 3:
              store=cmv.cloth.storeGloveSize
              break;
            case 4:
              store=cmv.cloth.storeSockSize
              break;
            case 5:
              store=cmv.cloth.storeShoeSize
              break;
            default:
          }
      }
      items.push(new cmv.cloth.sizeComboBox({
        useButton:false,
        clothtype:(gp?'gp':'')+clothtype,
        clothid:clothid,
        store: store,
        allowBlank:true
      }));
      this.add(new Ext.form.CompositeField({
        fieldLabel:rec.get('item')+' ('+Ext.util.Format.dkMoney(rec.get('price'))+')',
        items:items
      }));
      cmv.cloth.store.clearFilter();
    },this)
  }
})

Ext.reg('cmvclothformtab', cmv.cloth.FormTab);

cmv.cloth.FormPanel = Ext.extend(Ext.form.FormPanel,{
  grundpakke:true,
  constructor: function(config){
    config = Ext.apply({
      frame:true,
      defaults:{
        frame:true,
        border:false
      }
    }, config);
    cmv.cloth.FormPanel.superclass.constructor.call(this, config);
  },
  setGrundpakke:function(bool){
    var parent=this.get(0);
    bool?parent.get(0).enable():parent.get(0).disable();
    for(var i=1;i<4;i++)
      bool?parent.get(i).disable():parent.get(i).enable();
    parent.activate(bool?0:1);
  }
});

Ext.reg('cmvclothformpanel', cmv.cloth.FormPanel);

cmv.cloth.OrderGridPanel = Ext.extend(Ext.grid.GridPanel,{
  data: [],
  constructor: function(config){
    config=Ext.apply({
      stripeRows: true,
      autoExpandColumn: 'artikel',
      autoHeight: true,
      store : new Ext.data.ArrayStore({
        fields: [{
          name: 'antal'
        },
        {
          name: 'artikel'
        },
        {
          name: 'size'
        },
        {
          name: 'pris',
          type: 'float'
        },
        {
          name: 'varenummer',
          type: 'int'
        }
        ]
      }),
      colModel: new cmv.cloth.colModel(),
      viewConfig:{
        headersDisabled:true
      }
    },config);
    cmv.cloth.OrderGridPanel.superclass.constructor.call(this, config);
    this.store.loadData(this.data);
  },
  addData: function(arr){
    if(this.data.length>1)
      this.data.pop();//Pop summation
    if(arr[0]!='-')
      arr[3]=arr[0]*arr[3];
    this.data.push(arr);
    this.sumData();
  },
  deleteData: function(varenummer){
    this.data.pop();
    var lgt=this.data.length;
    for(var i=0;i<lgt;i++)
      if(this.data[i][4]==varenummer&&this.data[i][3]>0)
      {
        this.data.splice(i,1);
        break;
      }
    if(this.data.length>0)
      this.sumData();
    else
    {
      Ext.getCmp('clothorderbutton').disable();
      this.store.loadData(this.data);
    }
  },
  updateData: function(varenummer,antal,pris){
    this.data.pop();
    var lgt=this.data.length;
    for(var i=0;i<lgt;i++)
      if(this.data[i][4]==varenummer&&this.data[i][3]>0)
      {
        this.data[i][0]=antal;
        this.data[i][3]=antal*pris;
        break;
      }
    this.sumData();
  },
  updateSizeData: function(varenummer,size){
    var lgt=this.data.length;
    for(var i=0;i<lgt;i++)
      if(this.data[i][4]==varenummer&&this.data[i][3]>0)
      {
        this.data[i][2]=size;
        break;
      }
    this.store.loadData(this.data);
  },
  updateDescData: function(varenummer){
    var lgt=this.data.length;
    for(var i=0;i<lgt;i++)
      if(this.data[i][4]==varenummer&&this.data[i][3]>0)
      {
        var item = cmv.cloth.store.getAt(cmv.cloth.store.find('Varenummer',varenummer)).get('item');
        item+=', '+Ext.getCmp('seler'+varenummer).getRawValue();
        if(!Ext.getCmp('skind'+varenummer).disabled)
          item+=', '+Ext.getCmp('skind'+varenummer).getRawValue()
        this.data[i][1]=item;
        break;
      }
    this.store.loadData(this.data);
  },
  clearData: function()
  {
    var lgt=this.data.length;
    for(var i=0;i<lgt;i++)
      this.data.pop();
    this.store.loadData(this.data);
    Ext.getCmp('clothorderbutton').disable();
  },
  sumData: function()
  {
    var lgt=this.data.length;
    var sum=0;
    for(var i=0;i<lgt;i++)
      sum+=this.data[i][3]>0?this.data[i][3]:0;
    //Add summation has varenummer=-1
    this.data.push(['','<b>Samlet ordre pris</b>','-',sum,-1]);
    Ext.getCmp('clothorderbutton').enable();
    this.store.loadData(this.data);
  }
});

Ext.reg('cmvclothordergridpanel', cmv.cloth.OrderGridPanel);
