Ext.ns('ec2');

Ext.namespace ('Ext.ux');
Ext.ux.PagingToolbar	=	function (config) {
  Ext.ux.PagingToolbar.superclass.constructor.call (this, config);
};

ec2.EditGrid = Ext.extend(Ext.grid.EditorGridPanel, {
  viewConfig: {
    forceFit: true
  },
  sm: new Ext.grid.RowSelectionModel({singleSelect:true}),
  iconCls: 'icon-grid',
  insertEmptyRow: function(c) {          
    var me = this;
    var p = new me.store.recordType({}, 0); 
    me.stopEditing(0, 0);
    for (var i = 0; i< c; i++) {
      me.store.insert(0, p);
    }
    me.startEditing(0, 0);
  },
  initComponent:function() {
  
    var me = this;
    var proxy = this.proxy + '?' + 'model=' + this.model;

    this.limit = (this.limit) ? this.limit : 25;
    
    this.store = new Ext.data.Store({
      url: proxy,
      autoLoad: true,
      reader: new Ext.data.JsonReader({})
    })

    this.colModel = new Ext.grid.ColumnModel({
			defaults: {
				width: 120,
				sortable: true
			},
			columns: ec2.buildColumns(this.columns)
    });


    this.store.on('load', function(t, rec, s) {
      me.insertEmptyRow(me.blankRows);
    });
    
    this.store.on('update', function(t, rec, s) {
      // Convert the store record to form object used in ajax
      var parm =  {};
      for (var i=0; i < rec.fields.length; i++) {
        var f = rec.data[rec.fields.items[i].name];
        if (typeof f == "object" && typeof f.isLeapYear == 'function') {
          // f = f.format('Y-m-d-H.i.s');      
          f = f.format('Y-m-d');      
        }
        parm[rec.fields.items[i].name] = f;
      }
      Ext.Ajax.request({
        url: proxy,
        method: 'POST',
        jsonData: parm,
        success: function ( result, request ) {
          var r; 
          eval('r=' +result.responseText);
          if (r.success) {
            if (rec.data['id'] > 0) {
            } else {
              rec.data['id'] = r.id;
            }
          } else {
            alert(r.message);
          }          
        },
        failure: function ( result, request) {
        // error .. TODO
        }
      });
    });


    this.tbar = new Ext.PagingToolbar({
      pageSize: this.limit,
      store:this.store,
      displayInfo: true,
      emptyMsg: "No rows",
      defaultType: 'textfield'
    });

    Ext.apply(this, {
    });
    ec2.EditGrid.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.EditGrid', ec2.EditGrid);


// DateTime 
ec2.DateTime = Ext.extend(Ext.form.DateField, {
  type:'date',
  width: 135,
  anchor:null,
  format: 'Y-m-d H:i:s', 
  convert: ec2.JsonDateConvert,
  disableArrowsUpDown:true,
  initComponent:function() {
    Ext.apply(this, {
    });
    ec2.DateTime.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.DateTime', ec2.DateTime);

// TimeStamp
ec2.TimeStamp = Ext.extend(ec2.DateTime, {
  initComponent:function() {
    Ext.apply(this, {
    });
    ec2.TimeStamp.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.TimeStamp', ec2.TimeStamp);

// Date
ec2.Date = Ext.extend(ec2.DateTime, {
  format: 'Y-m-d', 
  width: 100,
  initComponent:function() {
    Ext.apply(this, {
    });
    ec2.Date.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Date', ec2.Date);

// Time only 
ec2.Time = Ext.extend(Ext.form.TimeField, {
  type:'date',
  format: 'H:i:s' ,
  convert: ec2.JsonDateConvert,
  initComponent:function() {
    Ext.apply(this, {
    });
    ec2.Time.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Time', ec2.Time);

// GUID
ec2.Guid = Ext.extend(Ext.form.Field, {
  initComponent:function() {
    Ext.apply(this, {
    });
    ec2.Guid.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Guid', ec2.Guid);

// Integer
ec2.Integer = Ext.extend(Ext.form.NumberField, {
  type:'number',
  align:"right",
  initComponent:function() {
    Ext.apply(this, {
      decimalPrecision:0,
      align:"right"
    });
    ec2.Integer.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Integer', ec2.Integer);

// Amount
ec2.Amount = Ext.extend(Ext.form.NumberField, {
  type:'number',
  align:"right",
  initComponent:function() {
    Ext.apply(this, {
      decimalPrecision:2,
      decimalSeparator: ',',
      align:"right"
    });
    ec2.Amount.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Amount', ec2.Amount);

// Percentage
ec2.Percentage = Ext.extend(Ext.form.NumberField, {
  type:'number',
  align:"right",
  initComponent:function() {
    Ext.apply(this, {
      decimalPrecision:0,
      decimalSeparator: ',',
      align:"right"
    });
    ec2.Percentage.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Percentage', ec2.Percentage);

// Hour
ec2.Hour = Ext.extend(Ext.form.NumberField, {
  type:'number',
  align:"right",
  initComponent:function() {
    Ext.apply(this, {
      decimalSeparator: ',',
      decimalPrecision: 2,
      align:"right"
    });
    ec2.Hour.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.Hour', ec2.Hour);

// Htmleditor
ec2.HtmlEditor = Ext.extend(Ext.form.HtmlEditor, {
  initComponent:function() {
    Ext.apply(this, {
      // height: this.MaxLinesShown * 15 // TODO - calculate relative to pixels size
      height:150
    });
    ec2.HtmlEditor.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.HtmlEditor', ec2.HtmlEditor);
 
ec2.TextEditor = Ext.extend(Ext.form.TextArea, {
  initComponent:function() {
    Ext.apply(this, {
      height: this.MaxLinesShown * 18 // TODO - calculate relative to pixels size
    });
    ec2.TextEditor.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.TextEditor', ec2.TextEditor);

ec2.SourceCodeEditor = Ext.extend(Ext.form.TextArea, {
  initComponent:function() {
    Ext.apply(this, {
      height: this.MaxLinesShown * 18, // TODO - calculate relative to pixels size
	  cls: 'ec2-source-editor'
    });
    ec2.SourceCodeEditor.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.SourceCodeEditor', ec2.SourceCodeEditor);

 
// basic form where meta and data service are splitted
ec2.Form = Ext.extend(Ext.form.FormPanel, {
  initComponent:function() {
    Ext.apply(this, {
      border:false,
      //loadMask : true,
      bodyStyle:'padding:5px 5px 0',
      labelWidth:150,
      formPanel: this,
      attributes: ec2.node,
      root: 0,
      layout:'form',
      monitorResize:true,
      defaults:{
        listeners:({
          'change' : {
            fn: function(field, newValue, oldValue) {
              ec2.activeObject.changePending = true;
              if (field.name == 'Title' && typeof (ec2.activeObject.node.attributes.nodeId) != 'undefined') {
                ec2.accordionMenu.fireEvent('updateNodeTitle', ec2.activeObject.node.attributes.treeId, ec2.activeObject.node.attributes.nodeId, newValue);
              }
            }
          }
        })
      }
    });
    ec2.Form.superclass.initComponent.call(this);
    var params = this.params;
    if (typeof (ec2.node.EntityId) != 'undefined') {
      params += '&entityId=' + ec2.node.EntityId + '&entityIds=' + ec2.node.EntityId;
    }
		
		ec2.waitMask.show();
    // get form data
	
    Ext.Ajax.request({
      url: ec2.extServiceUrl(this.dataUrl) + params,
      success: function ( result, request ) {
        var form = this;
        var refobj = {};
        refobj.items = [];
        
        this.root = Ext.getCmp(ec2.id);
        eval('var res =' + result.responseText);

        var data = res.rows[0];
        form.data = data;
        refobj.storeReader = {jsonData:res};
      
        if (res.IsRoot) {
          if (! res.title) res.title = "New";
          // form.setTitle(res.title);
          ec2.setTitle(form, res.title, res.name); // TODO René give me a catption  - entity name 
          this.root.headerTitle = res.title;
          this.root.caption     = res.name; // TODO René give me a catption  - entity name 
          this.root.attributes = this.root.node.attributes; // TODO !! move this to initialization  
          this.root.attributes.StateId = data.CurrentStateId;
          ec2.setToolbarMenu(this.root); 
        }

        ec2.activeObject.dataId = data.Id;
        ec2.activeObject.$type = res.dotNetType;

        for (var i = 0; i < form.items.items.length; i++) {
          var item = form.items.items[i];
          var obj = Ext.getCmp(item.id);
          obj.refobj = refobj; 
          var val = ec2.fieldRenderer(data, data[obj.name], obj.name, obj);
          obj.setValue(val);
          obj.originalValue = val;
        }
				ec2.waitMask.hide();
      },
      scope:this
    });
  }
});
Ext.reg('ec2.Form', ec2.Form);

// meta grid. Meta and data service splitted
ec2.MetaGrid = Ext.extend(Ext.grid.EditorGridPanel, {
  border:false,
  header:true,
  stateful:true,
  monitorResize:true,
  forceValidation: true,
  stripeRows: true,
  loadMask : true,
  clicksToEdit:1,
  columnLines : true,
  initComponent:function() {
  
    var url    = (this.dataUrl) ? this.dataUrl : 'GetEntities';
    var params = (this.params) ? this.params : ec2.params;
    params = params  + (ec2.node.EntityId ? ('&entityId=' + ec2.node.EntityId) : '');
    this.stateId = 'state-' + this.layoutPath;
    
    Ext.apply(this, {
      grid: this, // TODO !!!      
      store: new Ext.data.Store({
        baseurl: ec2.extServiceUrl(url) + params,
        url: ec2.extServiceUrl(url) + params,
        method: 'GET',
        comp: this,
        reader: new Ext.data.JsonReader({
          root:'rows',
          fields:[{name:'dataId',mapping:'Id'}]
        })
      }),
	  // view : new Ext.ux.grid.BufferView (),
	  cm: new Ext.grid.ColumnModel({}),
      clicksToEdit:1,
      selModel:new ec2.CellSelectionModelWithMultiRowSelect({
        addBottomRow: function(self) {
          var grid = self.grid;
          var store = grid.getStore();
          var defaults = ec2.cloneObject(store.defaultData);
          var record = new store.recordType(defaults,ec2.unique() * -1);
          grid.stopEditing();
          store.add(record);
          var rowIndex = store.getCount()-1;
          grid.startEditing(rowIndex, 0);
          ec2.activeObject.changePending = true;
        }
      })
    });
    ec2.MetaGrid.superclass.initComponent.call(this);
    
    
    this.on({
      'beforestaterestore' : {
        fn: function(me,state) {
          //me.saveState = ec2.cloneObject(state);
          return ;
        }
      }
    });
    
    // get grid columns
    var params = (this.params) ? this.params : ec2.params;
    
    this.metaData = new Ext.data.Store({
      url: ec2.extServiceUrl('GetDataStoreDescription') + params,
      reader: new Ext.data.JsonReader({
        fields:[
          {name:'metaData'}
          ,{name:'enableInsert'}
          ,{name:'enableUpdate'}
          ,{name:'enableDelete'}
        ]
      })
    });
    this.metaData.on({
      'load' : {
        fn: function() {
          var grid = this;
          var store = grid.getStore();
          var refobj = {};
          refobj.items = [];
          refobj.store = store;
          
          grid.enableInsert = grid.metaData.reader.jsonData.enableInsert;
          grid.enableUpdate = grid.metaData.reader.jsonData.enableUpdate;
          grid.enableDelete = grid.metaData.reader.jsonData.enableDelete;
          var fields = grid.metaData.fields;
          for (var i = 0; i < fields.items.length; i++) {
            var f = fields.items[i];
            var field = f;
            var column = f;

            column.editable = ! f.disabled;
            column.dataIndex = (f.dataIndex) ? f.dataIndex :  f.name;
            column.sortable  = (f.sortable)  ? f.sortable : true;
            if (f.width) column.width     = (f.width);
            // column.width     = (f.width)     ? ec2.calculateWidth(f.width) : 100;

            // set column options
            if (f.xtype) {
              // TODO !! Htmleditors in edit grid can not do focus, Q&D is to change the type to textarea
              if (f.xtype == 'ec2.HtmlEditor') {
                f.xtype = 'textarea';
              }
              
              // set options from prototype
              var prototype = Ext.ComponentMgr.types[f.xtype].prototype;
              var editor = {};
              editor.xtype = f.xtype;
              editor.name  = column.dataIndex;
              editor.allowBlank = (typeof (f.allowBlank) == 'undefined')  ? true : f.allowBlank;
              editor.hideLabel = true;
              column.editor = editor;
              delete column.xtype;

              //Ext.apply(field , prototype);
              //Ext.apply(column , prototype);
              
              field.refobj = refobj;
              
              if (! f.width) {
                if (prototype.width)      column.width        = prototype.width;
                if (prototype.width)      field.width         = prototype.width;
              }
              if (prototype.convert)      column.convert      = prototype.convert;
              if (prototype.convert)      field.convert       = prototype.convert;
              if (prototype.type)         field.type          = prototype.type;
              if (prototype.dateFormat)   field.dateFormat    = prototype.dateFormat;
              if (prototype.format)       field.format        = prototype.format;
              if (prototype.renderer)     column.renderer     = prototype.renderer;
              if (prototype.align)        column.align        = prototype.align;
              if (prototype.format)       column.format       = prototype.format;
              field.ec2Type = (prototype.ec2Type) ? prototype.ec2Type : '?';
              
              if (grid.saveState) {
                // column.width = field.width  = grid.saveState.columns[i].width;
              }
            }

            // add field and column to grid, columnModel, data store
            var o = grid.addColumn(field, column);
          }

          delete store.reader.ef;
          store.reader.buildExtractors();
          refobj.storeReader = store.reader;
          
          store.load();
          store.on('beforeload', function() {
            this.url = this.baseurl;
            // this.proxy.method = 'GET';
            this.proxy.api.read.method = 'GET';
            // this.proxy.api.update.method = 'GET';
            if ( this.comp.attributes.Filter ) this.setBaseParam ('filter' , this.comp.attributes.Filter);
          });
          
          store.on('load', function() {
            this.root = Ext.getCmp(ec2.id);
            
            this.$type = this.reader.jsonData.dotNetType;
            this.name  = this.reader.jsonData.name;
            this.defaultData = ec2.cloneObject(this.data.items[0].json);
            
            if (this.root.node.attributes.ViewType = "List") {
              ec2.setTitle(this.root , this.reader.jsonData.title, this.reader.jsonData.title);
              this.root.node.attributes.StateId = "0";
              ec2.setToolbarMenu(this.root); //!!!!!!!!!
            }
						ec2.waitMask.hide();
          });
        }
        ,scope:this
      }
    });

    this.on('rowcontextmenu', this.onRowMenu);
    this.on('afteredit', function(object) {
      ec2.activeObject.changePending = true;
      ec2.currentValue = 0;
      /* 
      var store = object.grid.getStore();
      var cm = object.grid.getColumnModel();
      var field = cm.config[object.column];
      var fieldName = field.dataIndex;
      if (field.editor) {
        field.setValue(field.editor.keyValue);
      }
      */
      if (!object.record.data.dataId || object.record.data.dataId <= 0) {
        for (var key in object.grid.store.defaultData) {
          var d = object.grid.store.defaultData[key];
          if (typeof(d) != "object") {
            object.record.modified[key] = d;          
          }
        }
      }
    })
    // convert column data, if data = object ($ref)
    this.on('beforeedit', function(object) {
      var store = object.grid.getStore();
      var cm = object.grid.getColumnModel();
      var field = cm.config[object.column];
      var fieldName = field.dataIndex;
      if (field.editor || !field.editor.xtype == 'checkbox') {
        // field.currentValue = 0; // TODO - does not belong here
        store.data.items[object.row].data[fieldName] = ec2.columnRenderer(object.value, null, object.record, object.row, object.column, object.grid.store, field);
      }
      // ec2.currentValue = field.currentValue; // TODO - move to object inter link to edit<->x-type object
      ec2.activeObject.editObject = null; 
      ec2.editCell = {
        obj: object,
        store: store,
        cm: cm,
        field: field,
        fieldName: fieldName,
        viewVal: store.data.items[object.row].data[fieldName]
      };      
    });

    // resize htmleditor column before and after editing (delay, because must be executed after keypress event)
    this.on('beforeedit', function(object) {
      object.grid.uxActiveEditor = object.grid.activeEditor; // needed by cellSelectionModel navigating
      ec2.activeObject.editObject = object;
      object.grid.currentCell = [object.row, object.column];
      var cm = object.grid.getColumnModel();
      if (cm.config[object.column].editor && cm.config[object.column].editor.xtype == 'ec2.HtmlEditor') {
        cm.config[object.column].editor.setWidth(520);
        cm.config[object.column].editor.setHeight(100);
      }
    },this,{delay:5});
    this.on('beforerender', function(grid, e) {
      grid.metaData.load();
    });
  },
  onRowMenu:function(grid, rowIndex, e) {
    e.stopEvent();

    // row menu
    if (!grid.rowMenu) {
      grid.rowMenu = new Ext.menu.Menu({
        id:'rowMenu_'+grid.id
        ,selection:{}
      });
      if (grid.enableInsert) {
        grid.rowMenu.add({id:'add_'+grid.id, text:'Add', cls:'ec2-icon-add', handler:this.onRowRightClick});
      }
      if (grid.enableUpdate) {
        grid.rowMenu.add({id:'edt_'+grid.id, text:'Edit', cls:'ec2-icon-edit', handler:this.onRowRightClick});
      }
      if (grid.enableDelete) {
        grid.rowMenu.add({id:'dlt_'+grid.id, text:'Delete', cls:'ec2-icon-delete', handler:this.onRowRightClick});
      }
    }

    var data = grid.store.data.items[rowIndex].data;
    if (!data.dataId || data.dataId <= 0) {
      Ext.getCmp('edt_'+grid.id).disable();
    } else {
      Ext.getCmp('edt_'+grid.id).enable();
    }

    var coords = e.getXY();
    grid.rowMenu.showAt([coords[0], coords[1]]);
    grid.rowMenu.selection.rowIndex = rowIndex;
    grid.rowMenu.selection.gridId = grid.id;
  },
  onRowRightClick:function(item) {
    var menu = item.findParentByType('menu');
    var grid = Ext.getCmp(menu.selection.gridId);
    var rowIndex = menu.selection.rowIndex;
    var store = grid.getStore();
    var tab = ec2.centerTabs.getActiveTab();
    switch (item.id.substring(0,3)) {
    case 'add':
      var defaults = ec2.cloneObject(store.defaultData);
      var record = new store.recordType(defaults,ec2.unique() * -1);
      grid.stopEditing();
      store.insert(rowIndex+1, record);
      grid.startEditing(rowIndex+1, 0);
      ec2.activeObject.changePending = true;
      break;
    case 'edt':
      var node = {};
      node.attributes = {};
      node.attributes.EntityType = ec2.node.EntityType;
      node.attributes.EntityId   = store.data.items[rowIndex].data.dataId;
      node.attributes.ViewType   = 'Detail';
      ec2.addTab(node);
      break;
    case 'dlt':
      Ext.Msg.show({
        title:'Delete row',
        msg:'Are you sure you want to delete this row ?',
        buttons:Ext.Msg.YESNO,
        fn:confirmDeleteResponse,
        animEl:'elId',
        icon:Ext.MessageBox.QUESTION
      });  
      break;
    }

    function confirmDeleteResponse(btn) {
      if (btn == 'yes') {
        var record = store.data.items[rowIndex];

        // deleting a old or new record (inserted)
        var addToRemoved = true;
        var records = store.getModifiedRecords();
        for (i = 0; i < records.length; i++) {
          if (!records[i].data.Id && records[i].data == record.data ) {
            addToRemoved = false;
            records[i].reject();
          }
        }

        if (addToRemoved) {
          if (!Ext.isArray(store.removedRecords)) {
            store.removedRecords = [];
          }
          store.removedRecords.push(record);
        }
        store.remove(record);
        ec2.activeObject.changePending = true;
      }
    } 
  }
});
Ext.reg('ec2.MetaGrid', ec2.MetaGrid);

// meta form. Meta and data service splitted
ec2.MetaForm = Ext.extend(Ext.form.FormPanel, {
  initComponent:function() {
    Ext.apply(this, {
      labelAlign: 'top'
      ,labelWidth:200
      ,border:false
      ,bodyStyle:'padding:5px 5px 0'
      ,defaults:{width:300}
      ,layout:'form'
      ,monitorResize:true
      ,defaults:{
        listeners:({
          'change' : {
            fn: function(field, newValue, oldValue) {
              ec2.activeObject.changePending = true;
              if (field.name == 'Title' && typeof (ec2.activeObject.node.attributes.nodeId) != 'undefined') {
                ec2.accordionMenu.fireEvent('updateNodeTitle', ec2.activeObject.node.attributes.treeId, ec2.activeObject.node.attributes.nodeId, newValue);
              }
            }
          }
        })
      }
    });
    ec2.MetaForm.superclass.initComponent.call(this);

    // get form fields
    var metaData = new Ext.data.JsonStore({
      url: ec2.extServiceUrl('GetDataStoreDescription') + '?entityType=' + ec2.node.EntityType,
      autoLoad: true
    });
    metaData.on({
      'load' : {
        fn: function() {
          var form = this;
          var fields = metaData.fields;

          var url    = (this.dataUrl) ? this.dataUrl : 'GetEntities';
          var params = (this.params)  ? this.params + '&entityId=' + ec2.node.EntityId : ec2.params;
          // get form data
          Ext.Ajax.request({
            url: ec2.extServiceUrl(url) + params,
            success: function ( result, request ) {
              var form = this;
              var refobj = {};
              refobj.items = [];
              
              eval('var res =' + result.responseText);

              var data = res.rows[0];
              form.data = data;
              refobj.storeReader = {jsonData:res};
                            
              ec2.activeObject.dataId = data.Id;
              ec2.activeObject.$type = res.dotNetType;

              for (var i = 0; i < fields.items.length; i++) {
                var field = fields.items[i];
                if (field.xtype) {
                  var prototype = Ext.ComponentMgr.types[field.xtype].prototype
                } else {
                  var prototype = {};
                  prototype.fieldLabel = '???';
                  prototype.width = 100;
                }
    
                var obj = {};
                obj.xtype      = (field.xtype) ? field.xtype : 'textfield';
                obj.name       = field.name;
                if (field.key) {
                  obj.key = field.key;
                }
                
                obj.refobj = refobj;
                obj.fieldLabel = (field.header) ? field.header : prototype.fieldLabel;
                obj.value      = ec2.fieldRenderer(data, data[obj.name], obj.name, obj);
                if (prototype.width) {
                  obj.width = (field.width) ? ec2.calculateWidth(field.width) : prototype.width;
                } else {
                  obj.anchor = '95%';
                }
                form.add(obj);
              }
              form.doLayout();
            },
            scope:form
          });
        },
        scope:this
      }
    });
  }
});
Ext.reg('ec2.MetaForm', ec2.MetaForm);

// This is called from the serverside when the upkdate is complete
function backPatch(compId,entityId) {
  var comp = Ext.getCmp(compId);

  if (ec2.editCell) {
    var e = ec2.editCell;
    e.store.data.items[e.obj.row].data[e.field.key] = entityId;
    ec2.editCell = null;
  } else {
    comp.currentValue = entityId;
    if (this.inEditor ) this.currentValue = this.obj.Id;
  }
}

ec2.FileAttachment = Ext.extend(Ext.form.TextField,  {

  // private
  hiddenIframe : {},
  me: this,
  width: 200, //NL
  ec2Type: 'love',
  dataUrl: 'FileAttachments', 
  initComponent: function(){
      ec2.FileAttachment.superclass.initComponent.call(this);

      this.on({
        'beforeshow' : {
          fn: function() {
            if (typeof (this.value) != 'undefined') {
              this.uploadComp.className = (this.value.length == 0) ? 'ec2-file-upload' : 'ec2-file-upload ec2-file-done';
            }
          }
        }
      });


      this.addEvents(
          /**
           * @event fileselected
           * Fires when the underlying file input field's value has changed from the user
           * selecting a new file from the system file selection dialog.
           * @param {Ext.ux.form.FileAttachment} this
           * @param {String} value The file value returned by the underlying file input field
           */
          'fileselected'
      );

      //ec2.hiddenIframe = Ext.DomHelper.append(Ext.getBody(), {tag : 'iframe', id : 'b1', cls : 'ec2-hidden-iframe'});
  },
  downloadFile: function() {
    var self = this.me;
    self.setUrl(self);
    ec2.hiddenIframe.src = self.url + '&func=download';
  },
  
  deleteFile: function(){
    function doDelete (btn) {
      if (btn == 'yes') {
        // get form data
        Ext.Ajax.request({
          url: self.url + '&func=delete' ,
          success: function ( result, request ) {
          },
          scope:this
        });
        ec2.activeObject.changePending = true;
      }
    }
    
    var self = this.me;
    self.setUrl(self);
    Ext.Msg.show({
      title:'Delete attachment',
      msg:'Are you sure you want to delete this attachment?',
      buttons:Ext.Msg.YESNO,
      fn:doDelete,
      animEl:'elId',
      icon:Ext.MessageBox.QUESTION
    });  
  },
  // private
  setUrl: function() {
      var params = this.params ? this.params : '' ;
      if (ec2.editCell) {
        var e = ec2.editCell;
        var v = e.store.data.items[e.obj.row].data[e.field.key];
        if (typeof(v) == "undefined") {
          this.currentValue = e.field.currentValue; // existingrows 
        } else {
          this.currentValue = e.store.data.items[e.obj.row].data[e.field.key]; // new rows
        }
      } else if (this.inEditor ) {
        this.currentValue = this.obj.Id;
      } else if (typeof(this.currentValue) == "undefined") {
        this.currentValue = 0; 
      }
      params += '?entityId=' + this.currentValue + '&entityIds=' + this.currentValue;
      params += '&thisid=' + this.id;
      this.url = ec2.extServiceUrl(this.dataUrl) + params;
  },
  
  onRender : function(ct, position){
      var btnCfg = {};
      ec2.FileAttachment.superclass.onRender.call(this, ct, position);
      this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
      this.el.addClass('x-form-file-text');
      this.el.dom.removeAttribute('name');
      
      // Create a new DIV and append it to document.body
      var b1  = Ext.DomHelper.append(this.wrap, {tag : 'div', id : 'b1', cls : 'ec2-file-upload'});
      b1.me = this;
      this._createFileInput(b1);
      var b2  = Ext.DomHelper.append(this.wrap, {tag : 'div', id : 'b2', cls : 'ec2-file-download'});
      b2.onmousedown = this.downloadFile;
      b2.me = this;
      var b3  = Ext.DomHelper.append(this.wrap, {tag : 'div', id : 'b3', cls : 'ec2-file-delete'});
      b3.onmousedown = this.deleteFile;
      b3.me = this;
      
      this.setReadOnly(true);
      this.resizeEl = this.positionEl = this.wrap;
  },

  // private
  onResize : function(ct, position){
      this.wrap = this.el.wrap({cls:'x-form-field-wrap x-form-file-wrap'});
      this.el.dom.style.width = this.wrap.dom.clientWidth - 65;
  },

  onBlur : function(){
    if(this.allowBlur === true && this.editing && this.selectSameEditor !== true){
        this.completeEdit();
    }
  },

  _attach: function (element, type, fn){
    if (element.addEventListener){
        element.addEventListener(type, fn, false);
    } else if (element.attachEvent){
        element.attachEvent('on' + type, fn);
    }
  },

  _createFileInput : function(uploadComp) {
    var id = ec2.unique();
    var frameName = 'frame' + id ; 
    uploadComp.innerHTML = '<iframe src="javascript:false;" name="' + frameName + '"  id="' + frameName + '" ' +
      'onload="this.frameload()" ' +
      'style="cursor:pointer;postition:absolute; left:0px; opacity:0; top:0px; border:none; overflow:hidden;' +
      'margin:0px; width:15px; height:100px; filter:alpha(opacity=0);"</iframe>';

    var iframe = document.getElementById(frameName);
    iframe.frameload = function () {};
    
    if (iframe.contentDocument) {
      iframeDoc = iframe.contentDocument;
    }
    else if (iframe.contentWindow) {
      iframeDoc = iframe.contentWindow.document;
    }
    else if (window.frames[iframe.name]) {
      iframeDoc = window.frames[iframe.name].document;
    }
    var formName = 'form' + id; 
    var inputName = 'input' + id;
    iframeDoc.open();
    iframeDoc.write("<html><body style='width:100px'><form id='" + formName + "' enctype='multipart/form-data' method='post'>" +   
      "<input type='file' id='" + inputName + "' name='uploadName' size='100'" + 
      "style='cursor:pointer;position:absolute; top:-5px; margin:0px; left:-5px; opacity:0; fontSize:10px; width:10px;overflow:hidden;'>" + 
      "</form></body></html></body></html>");
    iframeDoc.close();
    
    // var frameBody = iframeDoc.body;
    var form  = iframeDoc.getElementById(formName);
    var input = iframeDoc.getElementById(inputName);
    
    this.fileInput = input;
    this.form = form;
    this.uploadComp = uploadComp;
    var me = this;
    this._attach(input, 'change', function(){
      iframe.frameload = function (s) {
        uploadComp.removeChild(iframe);
        me._createFileInput(uploadComp);
        uploadComp.className = 'ec2-file-upload ec2-file-done';
      };
      uploadComp.className = 'ec2-file-upload ec2-file-loading';
      me.setUrl();
      me.form.action = me.url + '&func=upload';
      me.setValue(input.value);
      me.form.submit();        
    });
  }
});
Ext.reg('ec2.FileAttachment', ec2.FileAttachment);


/* 
ec2.ItemSelector = Ext.extend(Ext.ux.form.ItemSelector,  {
  anchor:'95%',
  itemCls: 'ec2-label'		,
  ec2Type: 'itemSelector',
  imagePath: '../ext3/examples/ux/images',
  baseUrl: ec2.extServiceUrl('GetLove'),
  multiselects: [{
    width: 250,
    height: 200,
    displayField: 'value',
    valueField: 'key'
  },{
    width: 250,
    height: 200,
    displayField: 'value',
    valueField: 'key'
  }],
  initComponent:function() {
    
    Ext.apply(this, {
      avail: this.multiselects[0],
      selected: this.multiselects[1],
      listeners: {
        render: function(me) {
          // Set vertical scroler
          var pt = Ext.query(".x-fieldset-body", this.el.dom);
          if (pt.length) {
            pt[0].style.overflowY= "auto";
            pt[1].style.overflowY= "auto";
          } 

          me.avail.store.proxy.api.read.method = 'POST';
          me.avail.store.setBaseParam ('entityType' , "EntityType");
          me.avail.store.setBaseParam ('query' , "avaialble");
          me.avail.store.load();
          
          me.selected.store.proxy.api.read.method = 'POST';
          me.selected.store.setBaseParam ('entityType' , "Field");
          me.avail.store.setBaseParam ('query' , "selected");
          me.selected.store.load();
        }
      }
    });
    this.avail.store = new Ext.data.Store({
      url: this.baseUrl ,
      reader: new Ext.data.JsonReader({
        root:'rows',
        fields:['key','value']
      })
    });
    
    this.selected.store = new Ext.data.Store({
      url: this.baseUrl ,
      reader: new Ext.data.JsonReader({
        root:'rows',
        fields:['key','value']
      })
    });
    ec2.ItemSelector.superclass.initComponent.call(this);
  }
});
Ext.reg('ec2.ItemSelector', ec2.ItemSelector);
*/ 
