/* TEMPORARY OVERRIDES */

/* IE9 createContextualFramework Fix */
if ((typeof Range !== "undefined") && !Range.prototype.createContextualFragment){
	Range.prototype.createContextualFragment = function(html){
		var frag = document.createDocumentFragment(),
		div = document.createElement("div");
		frag.appendChild(div);
		div.outerHTML = html;
		return frag;
	};
}

/* TriggerField */
Ext.override(Ext.form.TriggerField, {
    afterRender : function(){
        Ext.form.TriggerField.superclass.afterRender.call(this);
        var y;
        if(Ext.isIE && !this.hideTrigger && this.el.getY() != (y = this.trigger.getY())){
            this.el.position();
            this.el.setY(y);
        }
    }
});

/* OVERRIDES */

/* Combobox */
Ext.override(Ext.form.ComboBox, {
    setValue : function(v){
        var text;
        var value;
        if(this.valueField){
            var r = this.findRecord(this.valueField, v);
            if(r){
                text = r.data[this.displayField];
                value = v;
            }else if(this.valueNotFoundText !== undefined){
                text = this.valueNotFoundText;
                value = '';
            }else{
                text = '';
                value = '';
            }
        }else{
            text = v;
            value = v;
        }
        this.lastSelectionText = text;
        if(this.hiddenField){
            this.hiddenField.value = value;
        }
        Ext.form.ComboBox.superclass.setValue.call(this, text);
        this.value = value;
    }
});

/* NumberField */
Ext.override(Ext.form.NumberField, {
    getValue : function(){
        return Ext.form.NumberField.superclass.getValue.call(this);
    },
    setValue : function(v){
    	Ext.form.NumberField.superclass.setValue.call(this, String(v).replace(".", this.decimalSeparator));
    },
    beforeBlur : function(){
    }
});

/* Button */
Ext.override(Ext.Button, {
    onMouseOver : Ext.Button.prototype.onMouseOver.createSequence(function(e) {
        if(!this.disabled){
            var internal = e.within(this.el,  true);
            if(!internal && this.overCls){
                this.el.addClass(this.overCls);
            }
        }
    }),

    onMouseOut : Ext.Button.prototype.onMouseOut.createSequence(function(e) {
        if(this.overCls){
            this.el.removeClass(this.overCls);
        }
    })
});

/* Store */
Ext.override(Ext.data.Store, {
    clone : function(store){
        this.data = store.data.clone();
        this.fireEvent("datachanged", this);
    }
});

/* FormLayout */
Ext.override(Ext.layout.FormLayout, {
    renderItem : function(c, position, target){
        if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){
            var args = [
                   c.id, c.fieldLabel,
                   c.labelStyle||this.labelStyle||'',
                   this.elementStyle||'',
                   typeof c.labelSeparator == 'undefined' ? this.labelSeparator : c.labelSeparator,
                   (c.itemCls||this.container.itemCls||'') + (c.hideLabel ? ' x-hide-label' : ''),
                   c.clearCls || 'x-form-clear-left'
            ];
            if(typeof position == 'number'){
                position = target.dom.childNodes[position] || null;
            }
            if(position){
                c.formItem = this.fieldTpl.insertBefore(position, args, true);
            }else{
                c.formItem = this.fieldTpl.append(target, args, true);
            }
            c.render('x-form-el-'+c.id);
            c.container = c.formItem;
            c.actionMode = 'container';
        }else {
            Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
        }
    }
});

/* EXTENSIONS */

/* Field XType - IconComboBox */
Ext.ux.IconComboBox = Ext.extend(Ext.form.ComboBox, {
    initComponent : function() {
        Ext.apply(this, {
            tpl:  '<tpl for="."><div class="x-combo-list-item ux-icon-combo-item" style="background-image: url(/include/images/backend/icons/{' +
this.iconClsField + '})">{' + this.displayField + '}</div></tpl>'
        });

        Ext.ux.IconComboBox.superclass.initComponent.call(this);
    },

    onRender : function(ct, position) {
        Ext.ux.IconComboBox.superclass.onRender.call(this, ct, position);

        this.wrap.applyStyles({position:'relative'});
        this.el.addClass('ux-icon-combo-input');

        this.icon = Ext.DomHelper.append(this.el.up('div.x-form-field-wrap'), {
            tag: 'div', style:'position: absolute;'
        });
    },

    setIconCls : function() {
        if (this.getValue() != ''){
            var rec = this.store.query(this.valueField, this.getValue()).itemAt(0);
            if(rec) {
                this.icon.className = 'ux-icon-combo-icon';
                this.icon.style.backgroundImage = 'url(/include/images/backend/icons/' + rec.get(this.iconClsField) + ')';
            }
        }
    },

    setValue : function(value) {
        Ext.ux.IconComboBox.superclass.setValue.call(this, value);
        this.setIconCls();
    }
});
Ext.reg('iconcombo', Ext.ux.IconComboBox);

/* Field XType - TwinTriggerComboBox */
Ext.ux.TwinTriggerComboBox = Ext.extend(Ext.form.ComboBox, {
    initComponent : Ext.form.TwinTriggerField.prototype.initComponent,
    getTrigger : Ext.form.TwinTriggerField.prototype.getTrigger,
    initTrigger : Ext.form.TwinTriggerField.prototype.initTrigger,
    trigger1Class : 'x-form-clear-trigger',
    hideTrigger1 : true,
    onTrigger2Click : Ext.form.ComboBox.prototype.onTriggerClick,

    reset : Ext.form.Field.prototype.reset.createSequence( function(){
        this.triggers[0].hide();
    }),

    onViewClick : Ext.form.ComboBox.prototype.onViewClick.createSequence( function(){
        this.triggers[0].show();
    }),

    onTrigger1Click : function(){
        this.clearValue();
        this.triggers[0].hide();
        this.fireEvent('select', this);
    },

    setValue : Ext.form.ComboBox.prototype.setValue.createSequence( function(v){
        if(v !== undefined && v !== null) {
	        this.triggers[0].show();
	} else {
	        this.triggers[0].hide();
	}
    })
});
Ext.reg('twintriggercombo', Ext.ux.TwinTriggerComboBox);

/* Field XType - TreeComboBox */
Ext.ux.TreeComboBox = Ext.extend(Ext.form.ComboBox, {
    maxHeight : 600,
    readOnly : true,
    editable : false,

    initList : function() {
        this.list = new Ext.tree.TreePanel({
            root: new Ext.tree.AsyncTreeNode({
                id: 'root',
                expanded: true,
                children: this.children
            }),
            loader: new Ext.tree.TreeLoader(),
            rootVisible: false,
            floating: true,
            useArrows:true,
            listeners: {
                click: this.onNodeClick,
                beforeClick: this.ignoreFolderNodes,
                beforeCollapseNode: this.ignoreFolderNodes,
                //expandnode: this.sync,
                //collapsenode: this.sync,
                scope: this
            },
            alignTo: function(el, pos) {
                this.setPagePosition(this.el.getAlignToXY(el, pos));
            }
        });
    },

    sync : function(){
        if(this.isExpanded()){
            if(this.list.body.getHeight() > this.maxHeight){
                this.list.body.setHeight(this.maxHeight);
                this.restricted = true;
            }else if(this.restricted && this.list.body.dom.firstChild.offsetHeight < this.maxHeight){
                this.list.body.setHeight('');
                this.restricted = false;
            }
            this.list.syncShadow();
        }
    },

    expand : function() {
        if (!this.list.rendered) {
            this.list.render(document.body);
            this.list.setWidth(this.wrap.getWidth());
            this.innerList = this.list.body;
            this.list.hide();
        }
        this.el.focus();
        Ext.ux.TreeComboBox.superclass.expand.apply(this, arguments);
        this.sync();
    },

    doQuery : function(q, forceAll) {
        this.expand();
    },

    collapseIf : function(e){
        if(!e.within(this.wrap) && !e.within(this.list.el)){
            this.collapse();
        }
    },

    onNodeClick : function(node, e) {
        if(node.attributes.leaf){
            this.setRawValue(node.attributes.text);
            if (this.hiddenField) {
                this.hiddenField.value = node.id;
            }
            this.collapse();
            window.location = node.attributes.path;
        } else {
            //node.toggle();
        }
    },

    ignoreFolderNodes : function(node, e) {
        if(!node.attributes.leaf){
            return false;
        }
    }
});
Ext.reg('treecombo', Ext.ux.TreeComboBox);

/* Field XType - XTimeField */
Ext.ux.XTimeField = Ext.extend(Ext.form.TimeField, {
    submitFormat : 'H:i:s',

    onRender : function() {
        this.altFormats += '|' + this.submitFormat;
        Ext.ux.XTimeField.superclass.onRender.apply(this, arguments);
        var name = this.name || this.el.dom.name;
        this.hiddenField = this.el.insertSibling({
            tag:'input',
            type:'hidden',
            name:name,
            value:this.formatHiddenDate(this.value)
        });
        this.hiddenName = name;
        this.el.dom.removeAttribute('name');
        this.el.on({
            keyup:{scope:this, fn:this.updateHidden},
            blur:{scope:this, fn:this.updateHidden}
        });
        this.setValue = this.setValue.createSequence(this.updateHidden);
    },

    onDisable : function(){
        Ext.ux.XTimeField.superclass.onDisable.apply(this, arguments);
        if(this.hiddenField) {
            this.hiddenField.dom.setAttribute('disabled','disabled');
        }
    },

    onEnable : function(){
        Ext.ux.XTimeField.superclass.onEnable.apply(this, arguments);
        if(this.hiddenField) {
            this.hiddenField.dom.removeAttribute('disabled');
        }
    },

    formatHiddenDate : function(date){
        return Ext.util.Format.date(Ext.isDate(date) ? date : this.parseDate(date, this.format), this.submitFormat);
    },

    updateHidden : function() {
        this.hiddenField.dom.value = this.formatHiddenDate(this.getValue());
    }
});
Ext.reg('xtimefield', Ext.ux.XTimeField);

/* Field XType - XDateField */
Ext.ux.XDateField = Ext.extend(Ext.form.DateField, {
    submitFormat:'Y-m-d'
    ,onRender:function() {
        Ext.ux.XDateField.superclass.onRender.apply(this, arguments);
        var name = this.name || this.el.dom.name;
        this.hiddenField = this.el.insertSibling({
             tag:'input'
            ,type:'hidden'
            ,name:name
            ,value:this.formatHiddenDate(this.value)
        });
        this.hiddenName = name;
        this.el.dom.removeAttribute('name');
        this.el.on({
            keyup:{scope:this, fn:this.updateHidden}
            ,blur:{scope:this, fn:this.updateHidden}
        });
        this.setValue = this.setValue.createSequence(this.updateHidden);
    }
    ,onDisable: function(){
        Ext.ux.XDateField.superclass.onDisable.apply(this, arguments);
        if(this.hiddenField) {
            this.hiddenField.dom.setAttribute('disabled','disabled');
        }
    }
    ,onEnable: function(){
        Ext.ux.XDateField.superclass.onEnable.apply(this, arguments);
        if(this.hiddenField) {
            this.hiddenField.dom.removeAttribute('disabled');
        }
    }
    ,formatHiddenDate : function(date){
        return Ext.util.Format.date(Ext.isDate(date) ? date : this.parseDate(date, this.format), this.submitFormat);
    }
    ,updateHidden:function() {
        this.hiddenField.dom.value = this.formatHiddenDate(this.getValue());
    }
    ,getHiddenValue:function() {
        return this.formatHiddenDate(this.getValue());
    }
});
Ext.reg('xdatefield', Ext.ux.XDateField);

/* Field XType - StaticField */
Ext.ux.StaticField = Ext.extend(Ext.form.Field,  {
    fieldClass : "ux-static-field",
    defaultAutoCreate : { tag: "div" },

    onRender : function(ct, position){
        Ext.ux.StaticField.superclass.onRender.call(this, ct, position);
        if(this.value !== undefined){
            this.el.update(this.value);
        }
    },

    setValue : function(v){
        if (v) {
            this.value = v;
            this.el.update(this.value);
        }
    },

    getValue : function(){
        if (this.value) {
            return this.value;
        } else {
            return '';
        }
    },

    markInvalid : Ext.emptyFn,
    clearInvalid : Ext.emptyFn,
    initValue : Ext.emptyFn
});
Ext.reg('staticfield', Ext.ux.StaticField);

/* Field XType - FileUploadField */
Ext.ux.FileUploadField = Ext.extend(Ext.form.TextField,  {
    buttonText: 'Browse...',
    buttonOnly: false,
    buttonOffset: 3,
    readOnly: true,
   
    autoSize: Ext.emptyFn,
   
    initComponent: function(){
        Ext.ux.FileUploadField.superclass.initComponent.call(this);
       
        this.addEvents(
            'fileselected'
        );
    },
   
    onRender : function(ct, position){
        Ext.ux.FileUploadField.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');
       
        this.fileInput = this.wrap.createChild({
            id: this.getFileInputId(),
            name: this.name||this.getId(),
            cls: 'x-form-file',
            tag: 'input',
            type: 'file',
            size: 1
        });
       
        var btnCfg = Ext.applyIf(this.buttonCfg || {}, {
            text: this.buttonText
        });
        this.button = new Ext.Button(Ext.apply(btnCfg, {
            renderTo: this.wrap,
            cls: 'x-form-file-btn' + (btnCfg.iconCls ? ' x-btn-icon' : '')
        }));
       
        if(this.buttonOnly){
            this.el.hide();
            this.wrap.setWidth(this.button.getEl().getWidth());
        }
       
        this.fileInput.on('change', function(){
            var v = this.fileInput.dom.value;
            this.setValue(v);
            this.fireEvent('fileselected', this, v);
        }, this);
    },
   
    getFileInputId: function(){
        return this.id+'-file';
    },
   
    onResize : function(w, h){
        Ext.ux.FileUploadField.superclass.onResize.call(this, w, h);
       
        this.wrap.setWidth(w);
       
        if(!this.buttonOnly){
            var w = this.wrap.getWidth() - this.button.getEl().getWidth() - this.buttonOffset;
            this.el.setWidth(w);
        }
    },
   
    preFocus : Ext.emptyFn,
   
    getResizeEl : function(){
        return this.wrap;
    },

    getPositionEl : function(){
        return this.wrap;
    },

    alignErrorIcon : function(){
        this.errorIcon.alignTo(this.wrap, 'tl-tr', [2, 0]);
    }
});
Ext.reg('fileuploadfield', Ext.ux.FileUploadField);

/* Panel Plugin - BlindPanel */
Ext.ux.BlindPanel = Ext.extend(Ext.Panel, {
    constructor : function(config) {
        config = Ext.apply({
            autoHeight: true,
            floating: true,
            cls: 'ux-blind-panel',
            bodyStyle: {
                'border-width': '0px'
            }
        }, config);
        Ext.ux.BlindPanel.superclass.constructor.call(this, config);
    },

    init : function(client) {
        this.client = client;
        if (!this.client.blinds) {
            this.client.blinds = new Ext.util.MixedCollection();
        }
        client.blinds.add(this);
        this.client.constructor.prototype.showBlind = this.clientShowBlind;
        this.client.constructor.prototype.hideBlind = this.clientHideBlind;
        this.client.constructor.prototype.renderBlind = this.clientRenderBlind;
        this.client.constructor.prototype.getBlind = this.clientGetBlind;
        this.client.on({
            destroy: this.destroy,
            resize: this.syncSizeWithClient,
            scope: this
        });
    },

    syncSizeWithClient : function() {
        this.setWidth(this.client.body.getSize(true).width);
    },

    clientShowBlind : function(id) {
        var b = this.blinds.get(id);
        if (b) {
            b.show();
        }
    },

    clientHideBlind : function(id) {
        var b = this.blinds.get(id);
        if (b) {
            b.hide();
        }
    },

    clientRenderBlind : function(id) {
        var b = this.blinds.get(id);
        if (b) {
            b.xrender();
        }
    },

    clientGetBlind : function(id) {
        var b = this.blinds.get(id);
        if (b) {
            return b;
        } else {
            return false;
        }
    },

    show : function() {
        var mask = this.client.getEl().mask();
        if (!this.rendered) {
            this.render(this.client.getEl());
        }

       	this.el.setZIndex(Number(mask.getStyle('z-index')) + 1);        	

        this.el.disableShadow();
        this.syncSizeWithClient();
        this.el.alignTo(this.client.body, 'tl-tl');
        this.el.slideIn('t', {
            callback: function() {
                this.el.visible = true;
                this.el.enableShadow(true);
            },
            scope: this
        });
    },

    hide : function() {
        if (this.destroyOnHide) {
            this.destroy();
            delete this.client.blinds[this.id];
        } else {
            this.el.disableShadow();
            this.el.slideOut('t');
            this.client.getEl().unmask();
        }
    },

    xrender : function() {
        if (!this.rendered) {
            this.render(this.client.getEl());
        }
    }
});

/* Panel Plugin - ReconfigFieldset */
Ext.ux.ReconfigFieldset = Ext.extend(Ext.util.Observable, {
    constructor : function() {
        this.cmpList = [];
        Ext.ux.ReconfigFieldset.superclass.constructor.call(this);
    },

    init : function(container){
        this.container = container;
    },

    add : function(config){
        if (typeof config == "string") {
            config = Ext.decode(config);
        }

        var component = this.container.add(config);
        this.container.ownerCt.getForm().add(component);
        this.cmpList.push(component);
        return component;
    },

    removeAll : function(){
        Ext.each(this.cmpList, function(component){
            this.container.remove(component, true);
            this.container.ownerCt.getForm().remove(component);
        }, this);
        this.cmpList = [];
    }
});

/* Grid Plugin - GridCheckboxColumn */
Ext.ux.GridCheckboxColumn = Ext.extend(Ext.util.Observable, {
    constructor : function() {
        Ext.ux.GridCheckboxColumn.superclass.constructor.call(this);
    },

    init : function(grid){
        this.grid = grid;
        this.grid.on('render', function(){
            var view = this.grid.getView();
            view.mainBody.on('mousedown', this.onMouseDown, this);
        }, this);
    },

    onMouseDown : function(e, t){
        if(t.className && t.className.indexOf('x-grid3-check-col') != -1){
            var row = this.grid.view.findRowIndex(t);
            var column = this.grid.view.findCellIndex(t);
            var record = this.grid.store.getAt(row);
            var field = this.grid.colModel.getDataIndex(column);

            if (record.data[field] != -1) {
                var eventObject = {
                    grid: this.grid,
                    record: record,
                    field: field,
                    value: !record.data[field],
                    row: row,
                    column: column,
                    cancel:false
                };

                if(this.grid.fireEvent("beforeedit", eventObject, this.grid) !== false && eventObject.cancel !== true) {
                    e.stopEvent();
                    record.set(field, !record.data[field]);
                    this.grid.fireEvent("afteredit", eventObject, this.grid)
                }
            }
        }
    }
});

/* Grid Extension - AutoEditorGridPanel */
Ext.ux.AutoEditorGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
    renderers : {},

    initComponent : function(){
        Ext.ux.AutoEditorGridPanel.superclass.initComponent.call(this);

        if(this.store){
            this.store.on("metachange", this.onMetaChange, this);
        }

        this.renderers['checkboxColumn'] = function(v, p) { p.css += ' x-grid3-check-col-td'; var cls = ''; if (v == -1) { cls = '-disabled'; } else if (v) {
cls = '-on'; } return '<div class="x-grid3-check-col'+cls+'">&#160;</div>'; };
        				   //function(v, p) { p.css += ' x-grid3-check-col-td'; return '<div class=\"x-grid3-check-col'+(v?'-on':'')+'\">&#160;</div>'; };
    },

    onMetaChange : function(store, meta) {
        var c;
        var config = [];

        for(var i = 0, len = meta.fields.length; i < len; i++)
        {
            c = meta.fields[i];
            if(c.header !== undefined){
                if(typeof c.dataIndex == "undefined"){
                    c.dataIndex = c.name;
                }

                if(this.renderers[c.renderer]) {
                    c.renderer = this.renderers[c.renderer];
                } else if(typeof c.renderer == "string"){
                    c.renderer = Ext.util.Format[c.renderer];
                } else {
                    delete c.renderer;
                }

                if(typeof c.id == "undefined"){
                    c.id = 'c' + i;
                }
                if(c.editor){
                    c.editor = new Ext.grid.GridEditor(Ext.ComponentMgr.create(c.editor));
                }

                delete c.name;

                config[config.length] = c;
            }
        }

        var cm = new Ext.grid.ColumnModel(config);
        this.reconfigure(this.store, cm);
    }
});

/* Grid Extension - GridReorderDropTarget */
Ext.ux.GridReorderDropTarget = Ext.extend(Ext.util.Observable, {
    constructor : function(grid, config) {
        this.target = new Ext.dd.DropTarget(grid.getEl(), {
            ddGroup: grid.ddGroup || 'GridDD',
            grid: grid,
            gridDropTarget: this,
            notifyDrop: function(dd, e, data){
                var t = Ext.lib.Event.getTarget(e);
                var rindex = this.grid.getView().findRowIndex(t);
                if (rindex === false) return false;
                if (rindex == data.rowIndex) return false;
                
                var gg1    = data.grid.store.groupField;            
                var group1 = data.selections[0].data[gg1];
                if(rindex === false){
                    var group2 = -1;
                } else {
                    var gg2    = data.grid.store.data.items[rindex].store.groupField;    
                    var group2 = data.grid.store.data.items[rindex].data[gg2];
                }
            
                if(group1 == group2){            
                    if (this.gridDropTarget.fireEvent('beforerowmove', this.gridDropTarget, data.rowIndex, rindex, data.selections) === false) return false;
    
                    var ds = this.grid.getStore();
                    for(i = 0; i < data.selections.length; i++) {
                        ds.remove(ds.getById(data.selections[i].id));
                    }
                    ds.insert(rindex,data.selections);
    
                    var sm = this.grid.getSelectionModel();
                    if (sm) sm.selectRecords(data.selections);
    
                    this.gridDropTarget.fireEvent('afterrowmove', this.gridDropTarget, data.rowIndex, rindex, data.selections);
                    return true;            
                }
            },
            notifyOver: function(dd, e, data) {
                var t = Ext.lib.Event.getTarget(e);
                var rindex = this.grid.getView().findRowIndex(t);
                
                if (rindex == data.rowIndex) rindex = false;
    
                var gg1    = data.grid.store.groupField;            
                var group1 = data.selections[0].data[gg1];
                if(rindex === false){
                    var group2 = -1;
                } else {
                    var gg2    = data.grid.store.data.items[rindex].store.groupField;    
                    var group2 = data.grid.store.data.items[rindex].data[gg2];
                }
    
                if(group1 == group2){
                    return this.dropAllowed;
                } else {
                    return this.dropNotAllowed;
                }
            }
        });
        if (config) {
            Ext.apply(this.target, config);
            if (config.listeners) Ext.apply(this,{listeners: config.listeners});
        }
    
        this.addEvents({
            "beforerowmove": true,
            "afterrowmove": true
        });
    
        Ext.ux.GridReorderDropTarget.superclass.constructor.call(this);
    }
});

/* Layout Type - CenterLayout*/
Ext.ux.CenterLayout = Ext.extend(Ext.layout.FitLayout, {
    setItemSize : function(item, size){
        this.container.addClass('ux-center-layout');
        item.addClass('ux-center-layout-item');
        if(item && size.height > 0){
            if(item.width){
                size.width = item.width;
            }
            item.setSize(size);
        }
    }
});
Ext.Container.LAYOUTS['ux.center'] = Ext.ux.CenterLayout;
