/*
 Ext.override(Ext.Container, {
 originalAdd: INF.util.clone(Ext.Container.prototype.add),
 //add: Ext.Container.prototype.add.createInterceptor(function(comp){
 
 add: function(comp){
 if (!Ext.isEmpty(comp.append)) {
 var append = comp.append;
 //var oldConfig = INF.util.clone(this.initialConfig);
 var oldConfig = INF.util.clone(comp);
 
 delete oldConfig.append;
 
 var newItems = [];
 newItems.push(oldConfig);
 
 Ext.each(append, function(item){
 newItems.push(item);
 });
 
 return this.originalAdd.call(this, {
 xtype: 'panel',
 layout: 'table',
 layoutConfig: {
 columns: append.length + 1
 },
 items: newItems
 });
 
 }else {
 return this.originalAdd.call(this, comp);
 }
 }
 });
 */
Ext.override(Ext.form.Field, {
    deleteList: [],
    
    //NOTE: one problem is that appended items are not available (eg. via form.items.find()) until their parent is rendered.
    initComponent: Ext.form.Field.prototype.initComponent.createSequence(function(){
        if (!Ext.isEmpty(this.append)) {
            var append = [];
            
            Ext.each(this.append, function(item){
                //Make sure they have an id so they get added correctly to the item collection and overwritten when
                item.id = item.id || Ext.id();
                
                var field = new Ext.ComponentMgr.create(item, 'button');
                
                field.onRender = field.onRender.createSequence(function(ct, position){
                    var form = (this.getForm) ? this.getForm() : undefined;
                    if (form && this.isFormField) {
                        form.items.add(this);
                    }
                });
                
                append.push(field);
                
            }, this);
            
            this.append = append;
        }
    }),
    
    onRender: Ext.form.Field.prototype.onRender.createSequence(function(ct, position){
    
        if (!this.el) {
            var cfg = this.getAutoCreate();
            if (!cfg.name) {
                cfg.name = this.name || this.id;
            }
            if (this.inputType) {
                cfg.type = this.inputType;
            }
            this.el = ct.createChild(cfg, position);
        }
        var type = this.el.dom.type;
        
        if (type) {
            if (type == 'password') {
                type = 'text';
            }
            this.el.addClass('x-form-' + type);
        }
        
        if (this.readOnly) {
            this.el.dom.readOnly = true;
        }
        
        if (this.tabIndex !== undefined) {
            this.el.dom.setAttribute('tabIndex', this.tabIndex);
        }
        this.el.addClass([this.fieldClass, this.cls]);
        // everything above is from the original onRender function
        
        var deleteList = [];
        
        // create the appended fields
        var ac = this.append || [];
        if (ac.length > 0) {
            //remove anchor we don't support it
            delete this.anchor;
            
            var form = this.getForm();
            
            // create a wrap for all the fields including the one created above
            this.wrap = this.el.wrap({
                cls: 'app-append-field-body'
            });
            deleteList.unshift(this.wrap.id);
            
            // also, wrap the field create above with the same div as the appending fields
            var fieldWrap = this.el.wrap({
                tag: 'div',
                style: 'float: left; padding-right: 3px;'
            });
            deleteList.unshift(fieldWrap.id);
            
            Ext.each(ac, function(item, index, all){
                // if the append field has append fields, delete this
                delete item.append;
                // create a div wrapper with the new field within it.
                var cell = this.wrap.createChild({
                    tag: 'div',
                    style: 'float: left; padding-right: 3px;'
                });
                deleteList.unshift(cell.id);
                
                var overrides = {
                    ownerCt: this.ownerCt, //added so that normal field functions work (findparentbytype etc)
                    getErrorCt: this.getErrorCt.createDelegate(this)
                };
                
                var field = Ext.apply(item, overrides);
                
                // render the field
                field.render(cell);
                
            }, this);
            
        }
        
        // if there is helpText create a div and display the text below the field
        if (typeof this.helpText == 'string') {
            var helpTextEl = this.el.wrap().createChild({
                tag: 'div',
				cls: 'ux-helptext',
                style: 'font-size: 9px; color: #888; padding-top: 3px;',
                html: this.helpText
            });
            deleteList.unshift(helpTextEl.id);
        }
        if (!Ext.isEmpty(deleteList)) {
            this.deleteList = deleteList;
        }
    }),
    
    onDestroy: Ext.form.Field.prototype.onDestroy.createInterceptor(function(){
        //Remove all the extra elements created by this fields helptext and append fields.
        //TODO: some helptext elements are still reminent. i think it is the appeneded fields that have help text the cell gets removed beforethe helptext
        if (!Ext.isEmpty(this.deleteList)) {
            for (var itemId in this.deleteList) {
            
                var item = Ext.get(this.deleteList[itemId]);
                if (!Ext.isEmpty(item)) {
                    delete this.deleteList[itemId];
                    item.remove();
                }
                
            }
            
        }
    }),
    
    getErrorCt: function(){
        var ac = this.append || [];
        if (ac.length > 0) {
            return this.el.findParent('.app-append-field-body', 5, true); // else direct field wrap
        }
        else {
            //original from Ext.form.Field
            return this.el.findParent('.x-form-element', 5, true) || // use form element wrap if available
            this.el.findParent('.x-form-field-wrap', 5, true); // else direct field wrap
        }
    },
    
    getForm: function(){
        var form;
        if (this.ownerCt) {
            // this has been added to something as a proper component
            this.ownerCt.bubble(function(container){
                if (container.form) {
                    form = container.form;
                    return false;
                }
            }, this);
            
            return form;
        }
        else {
            // try and access it anyway
            var formPanel = this.findParentByType('form');
            if (formPanel === null) {
                formPanel = this.findParentByType('dominoform');
            }
            
            if (formPanel !== null) {
                return formPanel.form;
            }
            
            return formPanel;
        }
    }
});
