Ext.namespace('Ext.ux.plugins');

Ext.ux.plugins.FitToParent = function(parent){

    return {

        init: function(c){

            c.on('render', function(c){

                parent = Ext.get(parent || c.el.dom.parentNode);

            });

            c.monitorResize = true;

            c.doLayout = c.doLayout.createInterceptor(function(){

                var pos = this.getPosition(), size = parent.getViewSize();

                this.setSize(size.width - pos[0], size.height - pos[1]);

            }, c);

        }

    }

}



/*

 * plugin to CLEAR (NOT RESET) all form fields. Required when one form is used for edit and add both

 */

Ext.ux.FormClear = function(){



    this.init = function(_object){

        if (typeof _object.form == "object") { //we are a formpanel and have a form, be kind and also add the method to the basic form

            //clear method for the underlying form:

            _object.form.clear = function(){

                var data = {};

                this.items.each(function(item){

                    data[item.getName()] = null;

                });

                

                var emptyRecord = new Ext.data.Record(data);

                this.loadRecord(emptyRecord);

            };

            

            //clear method for the forpanel itself

            _object.clear = function(){

                var data = {};

                this.items.each(function(item){

                    data[item.getName()] = null;

                });

                

                var emptyRecord = new Ext.data.Record(data);

                this.form.loadRecord(emptyRecord);

            };

            

        }

        else { //we are a basicform

            _object.clear = function(){

                var data = {};

                this.items.each(function(item){

                    data[item.getName()] = null;

                });

                

                var emptyRecord = new Ext.data.Record(data);

                this.loadRecord(emptyRecord);

            };

        }

    };

    

};

/*

 * Form Clear plugin

 */

Ext.Component.override({

    initState: function(config){

        if (Ext.state.Manager) {

            var id = this.getStateId();

            if (id) {

                var state = Ext.state.Manager.get(id);

                if (state) {

                    if (this.fireEvent('beforestaterestore', this, state) !== false) {

                        this.applyState(state);

                        this.fireEvent('staterestore', this, state);

                    }

                }

            }

        }

    },

    saveState: function(){

        if (Ext.state.Manager) {

            var id = this.getStateId();

            if (id) {

                var state = this.getState();

                if (this.fireEvent('beforestatesave', this, state) !== false) {

                    Ext.state.Manager.set(id, state);

                    this.fireEvent('statesave', this, state);

                }

            }

        }

    },

    getStateId: function(){

        return this.stateId || ((this.id.indexOf('ext-comp-') == 0 || this.id.indexOf('ext-gen') == 0) ? null : this.id);

    }

});



Ext.util.Format.FormatterFactory = function(c, d, t, s, ap){

    return function(n){

        if (n != '') {

            var m = (c = Math.abs(c) + 1 ? c : 2, d = d || ",", t = t || ".", /(\d+)(?:(\.\d+)|)/.exec(n + "")), x = m[1].length > 3 ? m[1].length % 3 : 0;

            var ret = '';

            if (ap == 1) 

                ret += s + ' '

            

            ret += ((x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : ""));

            if (ap == 0) 

                ret += ' ' + s

            return ret;

        }

        //return s+' '+((x ? m[1].substr(0, x) + t : "") + m[1].substr(x).replace(/(\d{3})(?=\d)/g,          "$1" + t) + (c ? d + (+m[2] || 0).toFixed(c).substr(2) : ""));

    }

}



Ext.form.VTypes['numeric'] = function(Z, v){

    var E = /^[0-9]*$/;

    return E.test(Z);

}

Ext.form.VTypes.numericText = "field must contain only numbers.";



Ext.form.VTypes['phone'] = function(Z, v){

    var E = /^(\d{3}[-]?){1,2}(\d{4})$/;

    return E.test(Z);

}

Ext.form.VTypes.phoneText = "Not a valid phone number.  Must be in the format 123-4567 or 123-456-7890.";

Ext.form.VTypes.phoneMask = /[\d-]/;



Ext.override(Ext.form.Field, {

    showContainer: function(){

        this.enable();

        this.show();

        this.getEl().up('.x-form-item').setDisplayed(true); // show entire container and children (including label if applicable)

    },

    setColor: function(){

        this.getEl().up('.x-form-item').setStyle('color', '#c1000f'); // show entire container and children (including label if applicable)

    },

    hideContainer: function(){

        if (this.xtype != 'select') {

            //this.disable(); // for validation

            this.hide();

            this.getEl().up('.x-form-item').setDisplayed(false); // hide container and children (including label if applicable)

        }

        

    },

    

    setContainerVisible: function(visible){

        if (visible) {

            this.showContainer();

        }

        else {

            this.hideContainer();

        }

        return this;

    }

});



BoxButton = Ext.extend(Ext.BoxComponent, Ext.apply({

    cls: 'x-form-button-pad',

    constructor: Ext.Button

}, Ext.Button.prototype));

Ext.reg('boxbutton', BoxButton);

Ext.Button.superclass = Ext.Component.prototype;



Ext.ux.MediaField = function(config) {

	Ext.ux.MediaField.superclass.constructor.call(this, config);

};



Ext.extend(Ext.ux.MediaField, Ext.form.TextField, {

	                        width: 120,

                        	readOnly: true

})

Ext.override(Ext.ux.MediaField, {

	onRender : Ext.form.TextField.prototype.onRender.createSequence(function() {

			var d = new Date()
var Fid = typeof this.ownerCt.form == "object" ? this.ownerCt.form.id  : this.getForm().id;
			this.el.wrap().createChild({

                tag: 'button',

                onclick: "mcFileManager.open('" +  Fid + "', '" + this.name + "', '', '', { relative_urls: false, remove_script_host: true,rootpath: '" + DocPather + "/DigitalAssets/" + UserIdentSession + "/'})",

                //onclick: "mcFileManager.open('" + owner.form.id + "', 'UpLoAd[]', '', '', { relative_urls: false, remove_script_host: true,rootpath: '" + DocPather + "/DigitalAssets/" + UserIdentSession + "/'})",

                html: "Browse"

                ,href: "#"

            })

			

			//Ext.ux.addMore.superclass.onRender.call(this, ct, position); // render the Ext.Button

		})

	

})

Ext.reg('mediafield', Ext.ux.MediaField);

/*

 * add more plugin

 */

Ext.ux.addMore = Ext.extend(Ext.Panel, {

    getValue: function(){

        return false

    },

    initComponent: function(){

        //console.log(this)

        Ext.apply(this, {

            border: false,

            items: {

                xtype: 'button',

                text: 'attachments',

                qtip: "click to add new attachment ",

                handler: function(){

                

                

                    //console.log(this.ownerCt.getPosition())

                    var owner = this.ownerCt.ownerCt;

                    owner.items.findIndex('id', this.ownerCt.id)

                    var ct = this.ownerCt.ownerCt.items.findIndex('id', this.ownerCt.id)// owner.items.getCount();

                    //console.log(ct)

                    //console.log(owner)

                    var lastField = owner.getComponent(ct);

                    

                    

                    

                    /*

                     * Text Field

                     */

                    //console.log(ct)

                    var d = new Date()

                    var f = new Ext.form.TextField({

                        width: 120,

                        // anchor: '90%',

                        //emptyText: 'Click browse',

                        readOnly: true,

                        fieldLabel: 'attachment ',

                        listeners: {

                            render: function(){

                                this.el.wrap().createChild({

                                    tag: 'button',

                                    cls: 'x-form-helptext',

                                    onclick: "mcFileManager.open('" + owner.form.id + "', 'UpLoAd" + d.getTime() + "', '', '', { relative_urls: false, remove_script_host: true,rootpath: '" + DocPather + "/DigitalAssets/" + UserIdentSession + "/'})",

                                    //onclick: "mcFileManager.open('" + owner.form.id + "', 'UpLoAd[]', '', '', { relative_urls: false, remove_script_host: true,rootpath: '" + DocPather + "/DigitalAssets/" + UserIdentSession + "/'})",

                                    html: "Browse",

                                    href: "#"

                                });

                            },

                            focus: function(){

                                //console.log("er")

                                this.validate()

                            }

                        }

                    });

                    

                    

                    //f.id = 'UpLoAd' + d.getTime()

                    f.id = 'UpLoAd' + d.getTime()

                    f.name = 'UpLoAdTiTlE[' + d.getTime() + '][path]'

                    

                    

                    var Panel = new Ext.Panel({

                        layout: 'column',

                        defaults: {

                            border: false

                            // actionMode: 'container'

                        },

                        border: false,

                        items: [{

                            //bodyStyle: 'padding:5px 0 ',

                            columnWidth: .5,

                            layout: 'form',

                            border: false,

                            items: [f]

                        }, {

                            columnWidth: .2,

                            layout: 'form',

                            border: false,

                            items: [{

                                xtype: 'textfield',

                                emptyText: 'title',

                                anchor: '90%',

                                hideLabel: true,

                                //name: 'UpLoAdTiTlE' + d.getTime()

                                name: 'UpLoAdTiTlE[' + d.getTime() + '][title]'

                            }]

                        }, {

                            columnWidth: .3,

                            layout: 'form',

                            border: false,

                            items: [{

                                xtype: 'boxbutton',

                                text: 'remove',

                                anchor: '90%',

                                handler: function(){

                                    owner.remove(owner.items.get(owner.items.findIndex('id', this.ownerCt.ownerCt.id)))

                                }

                            }]

                        }]

                    })

                    

                    owner.insert(ct, Panel).show();

                    owner.doLayout();

                }

                

            }

        })

        Ext.ux.addMore.superclass.initComponent.apply(this);

    },

    onRender: function(ct, position){

        Ext.ux.addMore.superclass.onRender.call(this, ct, position); // render the Ext.Button

    }

});

Ext.reg('addmore', Ext.ux.addMore);

Ext.onReady(function(){

    var formWindow = function(config){

        var myConfig = {};

        

        // make these externally facing so you can

        // change stuff if you want.

        this.btnSave = new Ext.Button({

            text: 'Add and Exit',

            handler: this.submitForm,

            scope: this

        });

        this.btnSaveAndNew = new Ext.Button({

            text: 'Add and New',

            handler: this.submitFormAndNew,

            scope: this

        });

        

        

        this.btnReset = new Ext.Button({

            text: 'Reset',

            handler: this.resetForm,

            scope: this

        });

        

        this.btnCancel = new Ext.Button({

            text: 'Cancel',

            handler: this.closeWindow,

            scope: this

        });

        

        this.formPanel = new Ext.FormPanel({

            //labelWidth: config.labelWidth != '' ? config.labelWidth : 200, // label settings here cascade unless overridden

            labelWidth: config.labelWidth != '' ? config.labelWidth : 150, // label settings here cascade unless overridden

            url: config.formUrl || 'save-form.php',

            bodyStyle: 'padding:5px 5px 0',

            width: config.width != '' ? config.width : 350,

            frame: true,

            autoScroll: true,

            monitorValid: true,

            plugins: [new Ext.ux.FormClear()],

            //autoHeight:true,

            baseParams: {

                recordID: 0

            },

            defaults: {

                labelSeparator: ''

                //width: 200

            },

            //defaultType      : 'textfield',

            trackResetOnLoad: true,

            //items: [].concat(config.fieldList)

            items: config.fieldList,

            tbar: ['->', {

                "text": "show optional Fields",

                "pressed": false,

                "enableToggle": true,

                "toggleHandler": function(asd, istoggled){

                    //console.log(asd);

                    if (!istoggled) 

                        asd.setText("show optional Fields");

                    else 

                        asd.setText("hide optional Fields");

                    this.onShowRequired(istoggled);

                },

                

                scope: this

            }]

        });

        

        //Defaults

        Ext.apply(myConfig, config, {

            width: 400,

            height: 450,

            //autoScroll	: true,

            closable: true,

            resiable: false,

            plain: true,

            closeAction: 'hide',

            layout: 'fit',

            modal: true,

            minWidth: 400,

            maximizable: true,

            

            items: [this.formPanel],

            bodyStyle: 'padding:5px;',

            buttonAlign: 'center',

            buttons: [this.btnSave, this.btnSaveAndNew, this.btnReset, this.btnCancel],

            listeners: {

                show: {

                    fn: function(){

                        this.onShowRequired(false);

                    }

                }

            }

        });

        

        

        //call the parent class constructor with the scope of 'this'

        formWindow.superclass.constructor.call(this, myConfig);

    }

    

    

    Ext.FormWindow = Ext.extend(formWindow, Ext.Window, {

        show: function(url, param2, toRefresh){

            this.formPanel.form.clearInvalid();

            if (!param2) 

                param = grider.selModel.selections.keys;

            else 

                param = param2;

            this.addSystem()

            

            if ((param.length == 0 || param.length > 1) && param2 == '' && toRefresh.indexOf("relationalTree") == -1) 

                Ext.MessageBox.alert('Item Check', "Please select ONLY 1 record to assign/update " + this.title)

            else {

                this.addSystem()

                if (this.formPanel.findByType('addmore')) 

                    this.addAttachments(url, param);

                

                

                Ext.apply(this.formPanel.form.baseParams, {

                    recordID: param

                });

                toRefresh != null ? this.toRefresh = toRefresh : this.toRefresh = null;

                this.btnSaveAndNew.hide();

                this.btnSave.setText("Save");

                

                this.formPanel.form.load({

                    url: url, // Coldfusion

                    // url:'json-form-getjson.php', // PHP

                    method: 'POST',

                    waitMsg: 'Loading',

                    scope: this,

                    

                    // Alternatively, instead of using actionfailed / complete (below)

                    // you could use these functions:

                    

                    success: function(form, action){ // Optional function

                        //var json_response = Ext.util.JSON.decode(action.response);

                        

                        //Ext.Msg.alert('Submit Status', json_response.statusText);

                        formWindow.superclass.show.call(this);

                        if (typeof action.result.data == 'object') {

                            //alert("Data Exists"+action.result.data);

                            this.formDataObj = action.result.data; // set it for the reset function

                            this.loadData(action.result.data);

                        }

                        else {

                            //this.resetForm();

                            this.closeWindow();

                        }

                        // Ext.MessageBox.alert('Message', 'Loaded OK');

                    },

                    

                    failure: function(form, action){

                    

                        Ext.MessageBox.alert('Oops', 'We could not load the form at this time. Please try again. <br>We know its annoying, but it happens');

                        this.closeWindow();

                    }

                    

                });

            }

        },

        addAttachments: function(url, param){

        

            var addMore = this.formPanel.findByType('addmore');

            if (addMore.length > 0) {

                var addmoreOwner = addMore[0].ownerCt;

                var addmoreIndex = addmoreOwner.items.findIndex('id', addMore[0].id)

                var Panel = new Ext.Panel({

                    title: 'current attachments',

                    layout: 'column',

                    collapsible: true,

                    defaults: { ///border: false

}                    ,

                    //border: false,

                    items: [{

                        //bodyStyle: 'padding:5px 0 ',

                        columnWidth: .3,

                        layout: 'form',

                        //border: false,

                        items: [{

                            xtype: 'box',

                            anchor: '',

                            autoEl: {

                                tag: 'div',

                                style: 'margin:8px 0 8px 105px',

                                children: [{

                                    tag: 'div',

                                    style: 'margin:0 0 4px 0',

                                    html: "<b>title</b>"

                                }]

                            }

                        }]

                    }, {

                        //bodyStyle: 'padding:5px 0 ',

                        columnWidth: .2,

                        layout: 'form',

                        border: false,

                        items: [{

                            xtype: 'box',

                            anchor: '',

                            autoEl: {

                                tag: 'div',

                                style: 'margin:8px 0 8px 105px',

                                children: [{

                                    tag: 'div',

                                    style: 'margin:0 0 4px 0',

                                    html: "<b>&nbsp;</b>"

                                }]

                            }

                        }]

                    }]

                })

                

                //console.log(url)

                Ext.Ajax.request({

                    url: url,

                    params: {

                        ReQuEsTTyPe: "Attachment",

                        recordID: param

                    },

                    failure: function(response, options){

                        Ext.MessageBox.alert('Warning', 'Oops...');

                    },

                    success: function(response, options){

                        var responseData = Ext.util.JSON.decode(response.responseText);// passed

                        if (responseData.success) {

                            for (var x = 0; x < responseData.data.length; x++) {

                            

                            

                                Panel.items.get(0).items.add(new Ext.BoxComponent({

                                    anchor: '',

                                    autoEl: {

                                        tag: 'div',

                                        style: 'margin:8px 0 8px 10px',

                                        children: [{

                                            tag: 'div',

                                            style: 'margin:0 0 4px 0',

                                            html: responseData.data[x].MediaTitle

                                        }]

                                    }

                                }))

                                Panel.items.get(1).items.add(new Ext.Button({

                                    text: 'remove this',

                                    xid: responseData.data[x].MediaId,

                                    handler: function(btn){

                                    

                                    

                                        //owner.remove(owner.items.get(owner.items.findIndex('id', this.ownerCt.ownerCt.id)))

                                        Ext.Ajax.request({

                                            url: '/index.php/DataService/Type,RemoveMedia',

                                            params: {

                                                recordID: this.xid,

                                                FormId: 1

                                            },

                                            failure: function(response, options){

                                                Ext.MessageBox.alert('Warning', 'Oops...');

                                            },

                                            success: function(response, options){

                                            

                                                var responseData = Ext.util.JSON.decode(response.responseText);// passed

                                                if (responseData.success) {

                                                

                                                    btn.setText("removed");

                                                    btn.disable();

                                                }

                                                

                                            }

                                        }, btn);

                                    }

                                }))

                                

                            }

                        }

                    }

                });

                

                addmoreOwner.insert(addmoreIndex, Panel).show();

                //Panel.doLayout();

                //this.addAttachments();

            }

        },

        addSystem: function(){

            //console.log(this.formPanel.form.items)

            //console.log(Ext.getCmp("SystemInfo"))

            if (!this.formPanel.findById('SystemInfo')) 

                this.formPanel.add({

                    xtype: 'fieldset',

                    id: "SystemInfo",

                    checkboxToggle: false,

                    title: 'system information',

                    autoHeight: true,

                    collapsed: false,

                    items: [{

                        layout: 'column',

                        id: "SystemInfo0",

                        items: [{

                            columnWidth: .5,

                            id: "SystemInfo1",

                            layout: 'form',

                            items: [{

                                xtype: 'textfield',

                                fieldLabel: 'created by',

                                name: 'CreatedBy',

                                readOnly: true,

                                allowBlank: false,

                                anchor: '95%'

                            }, {

                                xtype: 'textfield',

                                fieldLabel: 'created on',

                                name: 'CreatedOn',

                                readOnly: true,

                                allowBlank: false,

                                anchor: '95%'

                            }]

                        }, {

                            columnWidth: .5,

                            layout: 'form',

                            id: "SystemInfo2",

                            items: [{

                                xtype: 'textfield',

                                fieldLabel: 'modified by',

                                name: 'ModifiedBy',

                                readOnly: true,

                                allowBlank: false,

                                anchor: '95%'

                            }, {

                                xtype: 'textfield',

                                fieldLabel: 'modified on',

                                name: 'ModifiedOn',

                                readOnly: true,

                                allowBlank: false,

                                anchor: '95%'

                            }]

                        }]

                    }]

                })

            this.formPanel.doLayout();

            

        },

        showBlank: function(toRefresh){

            // call the parent class's method with the scope of this

            this.formPanel.form.clearInvalid();

            this.formPanel.remove('SystemInfo')

            formWindow.superclass.show.call(this);

            

            this.toRefresh = toRefresh;

        },

        showBlankSupport: function(toRefresh){

            this.btnSaveAndNew.hide();

            this.btnSave.setText("Send");

            

            this.formPanel.remove('SystemInfo')

            formWindow.superclass.show.call(this);

            

            this.toRefresh = toRefresh;

        },

        showStatus: function(toRefresh){

            var param = grider.selModel.selections.keys;

            

            if (param.length != 1) {

            

                Ext.MessageBox.alert('Item Check', "Please select ONLY 1 record to update " + this.title + ".")

            }

            else {

                Ext.apply(this.formPanel.form.baseParams, {

                    recordID: grider.selModel.selections.map[grider.selModel.selections.keys].data.formRecordId

                });

                

                formWindow.superclass.show.call(this);

            }

            this.toRefresh = toRefresh;

        },

        submitFormAndNew: function(){

            this.formPanel.form.submit({

                success: this.onSubmitFormSuccessAndNew,

                failure: this.onSubmitFormFailure,

                scope: this,

                waitMsg: 'Submitting data',

                waitTitle: "Please wait"

            });

        },

        submitForm: function(){

            this.formPanel.form.submit({

                success: this.onSubmitFormSuccess,

                failure: this.onSubmitFormFailure,

                scope: this,

                waitMsg: 'Submitting data',

                waitTitle: "Please wait"

            });

        },

        onSubmitFormSuccessAndNew: function(form, action){

            //alert(action.failureType);

            //Ext.MessageBox.alert('hurray', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));

            //alert(dataView);

            this.resetForm();

            form.clearInvalid();

            eval(this.toRefresh);

            //Ext.MessageBox.alert('Hooray', 'action performed successfully');

        

        },

        onSubmitFormSuccess: function(form, action){

            //alert(action.failureType);

            //Ext.MessageBox.alert('hurray', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));

            //alert(dataView);

            this.resetForm();

            form.clearInvalid();

            this.closeWindow();

            eval(this.toRefresh);

            Ext.MessageBox.alert('Hooray', 'action performed successfully');

            

        },

        onSubmitFormFailure: function(form, action){

        

            Ext.MessageBox.alert('Eh...', action.failureType == 'client' ? 'Please fill all the required fields!' : (action.result.errorMessage || 'I dont know what but something went wrong.. '));

        },

        onEsc: function(){

            this.closeWindow();

        },

        resetForm: function(){

            if (this.formDataObj) {

                this.loadData(this.formDataObj);

                this.formPanel.form.clearInvalid();

            }

            else {

                // set all values to null manually, being that we loaded

                // a record and .reset() will not work

                Ext.each(this.formPanel.form.items.items, function(formItem, index, allItems){

                    //console.log(formItem);

                    formItem.reset();

                    //formItem.setValue(null);

                });

                this.formPanel.form.clearInvalid();

            }

            

            

            if (this.formPanel.findByType('panel')) {

                this.formPanel.findByType('panel').each(function(items){

                    if (items.id != 'SystemInfo' && items.id != 'SystemInfo1' && items.id != 'SystemInfo0' && items.id != 'SystemInfo2') {

                        items.ownerCt.remove(items); //.hide()

                    }

                })

                this.formPanel.findByType('addMore').each(function(items){

                    items.remove()

                })

                

                this.formPanel.doLayout();

            }

        },

        onShowRequired: function(btn){

            // set all values to null manually, being that we loaded

            // a record and .reset() will not work

            

            Ext.each(this.formPanel.form.items.items, function(formItem, index, allItems){

            

                if (formItem.allowBlank && btn && formItem.inputType != 'hidden') // ADDED   && formItem.inputType != 'hidden' 26th sept 

                    formItem.setContainerVisible(true);

                else 

                    if (formItem.allowBlank && !btn && formItem.inputType != 'hidden') { // ADDED   && formItem.inputType != 'hidden' 26th sept

                        this.hasNonRequiredFields = true;

                        formItem.setContainerVisible(false)

                    }

                if (formItem.allowBlank == false && formItem.inputType != 'hidden') 

                    formItem.setColor();

                

                /*

                 *

                 if(formItem.allowBlank == false)

                 formItem.getEl().up('.x-form-item').applyStyles('color:#c1000f');

                 */

                //formItem.hideLabel = true;

                //

            }, this);

            if (!this.hasNonRequiredFields) 

                this.formPanel.tbar.hide();

            

            //this.formPanel.form.clearInvalid();

        

        },

        loadData: function(record){

        

            if (typeof record == 'object') {

                // Ext record object

                if (typeof record.override == 'function') {

                    this.formPanel.form.loadRecord(record);

                }

                // Assume it's a Json obj

                else {

                    this.formPanel.form.setValues(record);

                }

            }

        },

        closeWindow: function(){

            //cleanup and reset

            if (this.formDataObj) {

                delete this.formDataObj;

                this.resetForm();

                this.formPanel.form.clear()

            }

            

            //console.log(this.formPanel.getTopToolbar().items.get(1).getText())

            if (this.formPanel.getTopToolbar().items.get(1).getText() == "hide optional Fields") 

                this.formPanel.getTopToolbar().items.get(1).toggle();

            //console.log(this.formPanel.getTopToolbar())

            if (this.formPanel.findByType('panel')) {

                this.formPanel.findByType('panel').each(function(items){

                    if (items.id != 'SystemInfo' && items.id != 'SystemInfo1' && items.id != 'SystemInfo0' && items.id != 'SystemInfo2') {

                        items.ownerCt.remove(items); //.hide()

                    }

                })

                this.formPanel.findByType('addMore').each(function(items){

                    items.remove()

                })

                

                this.formPanel.doLayout();

            }

            this.hide();

        }

    });

});



Ext.override(Ext.form.ComboBox, {

    setLoadValue: function(v){

        if (this.mode == 'remote') {

            this.store.on('load', this.setValue.createDelegate(this, arguments), null, {

                single: true

            });

            if (this.store.lastOptions === null) {

                this.store.load();

            }

            return;

        }

        var text = v;

        if (this.valueField) {

            var r = this.findRecord(this.valueField, v);

            if (r) {

                text = r.data[this.displayField];

            }

            else 

                if (this.valueNotFoundText !== undefined) {

                    text = this.valueNotFoundText;

                }

        }

        this.lastSelectionText = text;

        if (this.hiddenField) {

            this.hiddenField.value = v;

        }

        Ext.form.ComboBox.superclass.setValue.call(this, text);

        this.value = v;

    }

});





Ext.override(Ext.grid.GridView, {

    layout: function(){

        if (!this.mainBody) {

            return;

        }

        var g = this.grid;

        var c = g.getGridEl(), cm = this.cm, expandCol = g.autoExpandColumn, gv = this;

        var csize = c.getSize(true);

        var vw = csize.width;

        if (vw < 20 || csize.height < 20) {

            return;

        }

        if (g.autoHeight) {

            csize.height = this.mainHd.getHeight() + this.mainBody.getHeight();

            if (!this.forceFit) {

                csize.height += this.scrollOffset;

            }

        }

        this.el.setSize(csize.width, csize.height);

        var hdHeight = this.mainHd.getHeight();

        var vh = csize.height - (hdHeight);

        this.scroller.setSize(vw, vh);

        if (this.innerHd) {

            this.innerHd.style.width = (vw) + 'px';

        }

        if (this.forceFit) {

            if (this.lastViewWidth != vw) {

                this.fitColumns(false, false);

                this.lastViewWidth = vw;

            }

        }

        else {

            this.autoExpand();

        }

        this.onLayout(vw, vh);

    }

});





// REMOTE COMBO LOADING FIX

Ext.override(Ext.form.ComboBox, {

    setValue: Ext.form.ComboBox.prototype.setValue.createSequence(function(v){

        var idx = this.store.find(this.valueField, v);

        

        if (v && this.mode == 'remote' && idx == -1 && !this.Loaded) {

            var p = {};

            p[this.valueField] = v;

            

            this.store.load({

                scope: this,

                params: p,

                callback: function(r, op, success){

                    this.Loaded = true;

                    this.setValue(v);

                    this.collapse();

                }

            });

        }

    })

});


