/* Override lai buutu minimalais izmers Viewportam! */
Ext.override(Ext.layout.BorderLayout, {
       onLayout : function(ct, target){
        var collapsed, i, c, pos, items = ct.items.items, len = items.length;
        if(!this.rendered){
            collapsed = [];
            for(i = 0; i < len; i++) {
                c = items[i];
                pos = c.region;
                if(c.collapsed){
                    collapsed.push(c); 
                }
                c.collapsed = false;
                if(!c.rendered){
                    c.render(target, i);
                    c.getPositionEl().addClass('x-border-panel');
                }
                this[pos] = pos != 'center' && c.split ?
                    new Ext.layout.BorderLayout.SplitRegion(this, c.initialConfig, pos) :
                    new Ext.layout.BorderLayout.Region(this, c.initialConfig, pos);
                this[pos].render(target, c);
            }
            this.rendered = true;
        }

        var size = this.getLayoutTargetSize();
        // -- to use minWidth! As suggested by Animal!
        if (size.width < this.minWidth) {
            target.setStyle('width', this.minWidth + 'px');
            size.width = this.minWidth;
            target.up('').setStyle('overflow', 'auto');
        } else {
            target.setStyle('width', '');
        }
        //------

        if(size.width < 20 || size.height < 20){ // display none?
            if(collapsed){
                this.restoreCollapsed = collapsed;
            }
            return;
        }else if(this.restoreCollapsed){
            collapsed = this.restoreCollapsed;
            delete this.restoreCollapsed;
        }

        var w = size.width, h = size.height,
            centerW = w, centerH = h, centerY = 0, centerX = 0,
            n = this.north, s = this.south, west = this.west, e = this.east, c = this.center,
            b, m, totalWidth, totalHeight;
        if(!c && Ext.layout.BorderLayout.WARN !== false){
            throw 'No center region defined in BorderLayout ' + ct.id;
        }

        if(n && n.isVisible()){
            b = n.getSize();
            m = n.getMargins();
            b.width = w - (m.left+m.right);
            b.x = m.left;
            b.y = m.top;
            centerY = b.height + b.y + m.bottom;
            centerH -= centerY;
            n.applyLayout(b);
        }
        if(s && s.isVisible()){
            b = s.getSize();
            m = s.getMargins();
            b.width = w - (m.left+m.right);
            b.x = m.left;
            totalHeight = (b.height + m.top + m.bottom);
            b.y = h - totalHeight + m.top;
            centerH -= totalHeight;
            s.applyLayout(b);
        }
        if(west && west.isVisible()){
            b = west.getSize();
            m = west.getMargins();
            b.height = centerH - (m.top+m.bottom);
            b.x = m.left;
            b.y = centerY + m.top;
            totalWidth = (b.width + m.left + m.right);
            centerX += totalWidth;
            centerW -= totalWidth;
            west.applyLayout(b);
        }
        if(e && e.isVisible()){
            b = e.getSize();
            m = e.getMargins();
            b.height = centerH - (m.top+m.bottom);
            totalWidth = (b.width + m.left + m.right);
            b.x = w - totalWidth + m.left;
            b.y = centerY + m.top;
            centerW -= totalWidth;
            e.applyLayout(b);
        }
        if(c){
            m = c.getMargins();
            var centerBox = {
                x: centerX + m.left,
                y: centerY + m.top,
                width: centerW - (m.left+m.right),
                height: centerH - (m.top+m.bottom)
            };
            c.applyLayout(centerBox);
        }
        if(collapsed){
            for(i = 0, len = collapsed.length; i < len; i++){
                collapsed[i].collapse(false);
            }
        }
        if(Ext.isIE && Ext.isStrict){ // workaround IE strict repainting issue
            target.repaint();
        }
        // Putting a border layout into an overflowed container is NOT correct and will make a second layout pass necessary.
        if (i = target.getStyle('overflow') && i != 'hidden' && !this.adjustmentPass) {
            var ts = this.getLayoutTargetSize();
            if (ts.width != size.width || ts.height != size.height){
                this.adjustmentPass = true;
                this.onLayout(ct, target);
            }
        }
        delete this.adjustmentPass;
    }
});

/* Missing change event!! */
Ext.override(Ext.form.SliderField, {
    onChange : function(slider, v){
        this.setValue(v, undefined, true);
        this.fireEvent('change',this);
    }
});

// add type flag to RadioGroup
Ext.override(Ext.form.RadioGroup, {
    //private
    isRadioGroup: true
});

// add type flag to CheckboxGroup
Ext.override(Ext.form.CheckboxGroup, {
    //private
    isCheckboxGroup: true
});

//Override for finding fields in checkboxgroups or radiogroups
Ext.override(Ext.BasicForm, {
  findField: function(id) {
        var field = this.items.get(id);

        if (!Ext.isObject(field)) {
            //searches for the field corresponding to the given id. Used recursively for composite fields
            var findMatchingField = function(f) {
                if (f.isFormField) {
                    if (f.dataIndex == id || f.id == id || f.getName() == id) {
                        field = f;
                        return false;
                    } else if (f.isComposite && f.rendered) {
                        return f.items.each(findMatchingField);
                    } else if (f.isRadioGroup && f.rendered) {
                        // for a radio group we assume
                        // only want to find the 'checked' radio
                        return f.items.each(function(sf){
                            if ((sf.dataIndex == id || sf.id == id || sf.getName() == id) && sf.getValue()) {
                                field = sf;
                                return false;
                            }
                        },this);
                    } else if (f.isCheckboxGroup && f.rendered) {
                        // for checkbox group we want 1st match
                        return f.items.each(findMatchingField);
                    }
                }
            };

            this.items.each(findMatchingField);
        }
        return field || null;
    }
});

//Fixed in r6772, ext-3.3.x
//lai stradatu Radio group
Ext.override( Ext.form.BasicForm, {
    updateRecord : function(record){
        record.beginEdit();
        var fs = record.fields;
        fs.each(function(f){
            var field = this.findField(f.name);
            if(field){
                var value = field.getValue();
                if ( value.getGroupValue ) {
                    value = value.getGroupValue();
                } else if ( field.eachItem ) {
                    value = [];
                    field.eachItem(function(item){ value.push(item.getValue()) });
                }
                record.set(f.name, value);
            }
        }, this);
        record.endEdit();
        return this;
    }
});


// Hack for 01.01.1970  - this wont allow to show this date..
// By the way, who needs it anyway ;)
Ext.override(Ext.form.DateField,{
    setValue : function(date){
        if(date=='01.01.1970' || date=='01-01-1970'){
            return Ext.form.DateField.superclass.setValue.call(this, '');
        }
            else{
            return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
        }
    }
});

// goodies
Ext.namespace('Ext.o3mod');
if('function' !== typeof RegExp.escape) {
    RegExp.escape = function(s) {
        if('string' !== typeof s) {
            return s;
        }
        // Note: if pasting from forum, precede ]/\ with backslash manually
        return s.replace(/([.*+?\^=!:${}()|\[\]\/\\])/g, '\\$1');
    }; // eo function escape
}

Ext.form.VTypes["register_confirmation"]=/[1]/;

// helpText + Required field! By Stju for 3.2.x

Ext.override(Ext.form.Field, {
  required: false,
  reqCfg: "border-left:2px solid orange;",
    onRender : 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.autoEl = cfg;
        }
        Ext.form.Field.superclass.onRender.call(this, ct, position);
        if(this.submitValue === false){
            this.el.dom.removeAttribute('name');
        }
        var type = this.el.dom.type;
        if(type){
            if(type == 'password'){
                type = 'text';
            }
            this.el.addClass('x-form-'+type);
        }
        if(this.readOnly){
            this.setReadOnly(true);
        }
        if(this.tabIndex !== undefined){
            this.el.dom.setAttribute('tabIndex', this.tabIndex);
        }

        this.el.addClass([this.fieldClass, this.cls]);

        /*  Req field Magic here */
        if (this.required) {
          var dh = Ext.DomHelper;
          dh.applyStyles(this.el, this.reqCfg);
        }

        /* Changes here */
        if (this.helpText !== undefined){
            this.wrap = this.el.wrap();
            this.wrap[this.helpPosition == 'top' ? 'insertFirst' : 'createChild']({
            cls: this.iconCls ? 'x-form-helptext-icon '+this.iconCls : 'x-form-helptext' ,
            html: this.helpText
        });
        }
    }
});

/* Additional VTypes */
/* formateetaajs failiem */
Ext.apply(Ext.util.Format, {
    bytesToSi: function(size) {
        if(typeof size == 'number' && size > 0) {
            var s = ['b', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb', 'Yb'];
            var e = Math.floor(Math.log(size) / Math.log(1024));
            var r = size / Math.pow(1024, e);
            if(Math.round(r.toFixed(2)) != r.toFixed(2)) {
                r = r.toFixed(2);
            }
            return r + ' ' + s[e];
        } else {
            return '0 b';
        }
    }
});

Ext.apply(Ext.form.VTypes, {
    filenameVal: /[a-z0-9_\-\.]+\.([a-z0-9]{1,7})$/i,
    filenameMask: /[a-z0-9_\-\.]/i,
    filenameText: 'Filename is invalid or contains illegal characters',
    filename: function(val, field) {
        return Ext.form.VTypes.filenameVal.test(val);
    }
});

/* String ellipse function */
String.prototype.ellipse = function(maxLength){
    if (this.length > maxLength){
        return this.substr(0, maxLength - 3) + '...';
    }
    return this;
};

// --- Variation of ComboBox where first button is clear, instead of second to clear value of the ComboBox

Ext.form.ClearableComboBox = Ext.extend(Ext.form.ComboBox, {
    initComponent: function() {
        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger x-form-clear-trigger"},
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger"}
        ]};
        Ext.form.ClearableComboBox.superclass.initComponent.call(this);
    },
    onTrigger1Click : function()
    {
        this.collapse();
        this.reset();                       // clear contents of combobox
        this.fireEvent('cleared');          // send notification that contents have been cleared
    },

    getTrigger: Ext.form.TwinTriggerField.prototype.getTrigger,
    initTrigger: Ext.form.TwinTriggerField.prototype.initTrigger,
    onTrigger2Click: Ext.form.ComboBox.prototype.onTriggerClick,
    trigger1Class: Ext.form.ComboBox.prototype.triggerClass,
    trigger2Class: Ext.form.ComboBox.prototype.triggerClass
});
Ext.reg('clearcombo', Ext.form.ClearableComboBox);

//Clearable Date field
Ext.form.ClearableDateField = Ext.extend(Ext.form.DateField, {
    initComponent: function() {
        this.triggerConfig = {
            tag:'span', cls:'x-form-twin-triggers', cn:[
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger x-form-clear-trigger"},
            {tag: "img", src: Ext.BLANK_IMAGE_URL, cls: "x-form-trigger x-form-date-trigger"}
        ]};
        Ext.form.ClearableDateField.superclass.initComponent.call(this);
    },
    onTrigger1Click : function()
    {
        this.setValue('');                 // clear content
    },

    getTrigger: Ext.form.TwinTriggerField.prototype.getTrigger,
    initTrigger: Ext.form.TwinTriggerField.prototype.initTrigger,
    onTrigger2Click: Ext.form.ComboBox.prototype.onTriggerClick,
    trigger1Class: Ext.form.ComboBox.prototype.triggerClass,
    trigger2Class: Ext.form.ComboBox.prototype.triggerClass
});
Ext.reg('cleardatefield', Ext.form.ClearableDateField);

/* Edit tree node on double click , single click select! */
Ext.tree.TreeNodeUI.prototype.onDblClick = function(e){
        e.preventDefault();
        if(this.disabled){
            return;
        }
        if(this.checkbox){
            this.toggleCheck();
        }
        this.fireEvent("dblclick", this.node, e);
    };

/* Partaisam Tree editoru, lai tas korekti darbotos uz Dubultklikshkja! */
Ext.override(Ext.tree.TreeEditor, {
    beforeNodeClick : function(){},
    onNodeDblClick : function(node, e){
            this.triggerEdit(node);
    }
});

/* papildinajums, lai varetu dabut rindinjas indeksu! Jaskatas vai nav beidzot papildinats sourcee!  3.2.6478 joprojam nav */
Ext.grid.RowSelectionModel.override ({
    getSelectedIndex : function(){
        return this.grid.store.indexOf( this.selections.itemAt(0) );
    }
});

/* izmanjas Row editoraa lai atvertos korekti uz 2 klikiem! joprojam nav implementets origjinalaja kodaa :( */
/* salabots lai korekti izskatas ievadlauki */
Ext.override(Ext.ux.grid.RowEditor, {
    init: function(grid){
        this.grid = grid;
        this.ownerCt = grid;
        /* te izmainjas kas jaliek ieksha ari nakamajas versijas  */
        if(this.clicksToEdit > 0){  // needed to trigger edit when grid click is not used
           if(this.clicksToEdit === 2){
              grid.on('rowdblclick', this.onRowDblClick, this);
           }
           else{
              grid.on('rowclick', this.onRowClick, this);
              if(Ext.isIE){
                 grid.on('rowdblclick', this.onRowDblClick, this);
              }
           }
        }
         /* ---------end izmainjas ----------- */

        // stopEditing without saving when a record is removed from Store.
        grid.getStore().on('remove', function() {
            this.stopEditing(false);
        },this);

        grid.on({
            scope: this,
            keydown: this.onGridKey,
            columnresize: this.verifyLayout,
            columnmove: this.refreshFields,
            reconfigure: this.refreshFields,
            beforedestroy : this.beforedestroy,
            destroy : this.destroy,
            bodyscroll: {
                buffer: 250,
                fn: this.positionButtons
            }
        });
        grid.getColumnModel().on('hiddenchange', this.verifyLayout, this, {delay:1});
        grid.getView().on('refresh', this.stopEditing.createDelegate(this, []));
    },
    initFields: function(){
        this.removeAll(true);
        //console.log('inits');
        var cm = this.grid.getColumnModel(), pm = Ext.layout.ContainerLayout.prototype.parseMargins;
        for(var i = 0, len = cm.getColumnCount(); i < len; i++){
            var c = cm.getColumnAt(i),
                ed = c.getEditor();
            if(!ed){
                ed = c.displayEditor || new Ext.form.DisplayField();
            }
            if(i == 0){
                ed.margins = pm('0 1 2 1'); //first col
            } else{
                ed.margins = pm('0 1 2'); //other col
            }
            var colWidth = cm.getColumnWidth(i);
            ed.setWidth(colWidth);
            ed.column = c;
            if(ed.ownerCt !== this){
                ed.on('focus', this.ensureVisible, this);
                ed.on('specialkey', this.onKey, this);
            }
            this.insert(i, ed);
        }
        this.initialized = true;
        this.verifyLayout(true);
    },

    onKey: function(f, e){
        if(e.getKey() === e.ENTER){
            this.stopEditing(true);
            e.stopPropagation();
        }
    },
    showTooltip: function(msg){
        var t = this.tooltip;
        if(!t){
            t = this.tooltip = new Ext.ToolTip({
                maxWidth: 600,
                cls: 'errorTip',
                width: 300,
                title: this.errorText,
                autoHide: false,
                anchor: 'top',
                anchorToTarget: true,
                mouseOffset: [0,40]
            });
        }
        var v = this.grid.getView(),
            top = parseInt(this.el.dom.style.top, 10),
            scroll = v.scroller.dom.scrollTop,
            h = this.el.getHeight();

        if(top + h >= scroll){
            t.initTarget(this.items.last().getEl());
            if(!t.rendered){
                t.show();
                t.hide();
            }
            t.body.update(msg);
            t.doAutoWidth(20);
            t.show();
        }else if(t.rendered){
            t.hide();
        }
    },
    positionButtons: function(){
        if(this.btns){
            var h = this.el.dom.clientHeight;
            var view = this.grid.getView();
            var scroll = view.scroller.dom.scrollLeft;
            var width = (this.grid.getWidth() > view.mainBody.getWidth())?view.mainBody.getWidth():this.grid.getWidth();
            var bw = this.btns.getWidth();
            this.btns.el.shift({left: (width/2)-(bw/2)+scroll, top: h - 2, stopFx: true, duration:0.2});
        }
    },
    verifyLayout: function(force){
        //console.log('pazimejam');
        if(this.el && (this.isVisible() || force === true)){
            var row = this.grid.getView().getRow(this.rowIndex);
            this.setSize(Ext.fly(row).getWidth(), Ext.isIE ? Ext.fly(row).getHeight() + 9 : undefined);
            var cm = this.grid.colModel, fields = this.items.items;
            for(var i = 0, len = cm.getColumnCount(); i < len; i++){
                if(!cm.isHidden(i)){
                    var adjust = 0;
                    if(i === (len - 1)){
                        adjust += 3; // outer padding
                    } else{
                        adjust += 2;
                    }
                    fields[i].show();
                    fields[i].setWidth(cm.getColumnWidth(i) - adjust);
                } else{
                    fields[i].hide();
                }
            }
            this.doLayout();
            this.positionButtons();
        }
    },
    startMonitoring : function(){
        if(!this.bound && this.monitorValid){
            this.bound = true;
            Ext.TaskMgr.start({
                run : this.bindHandler,
                interval : this.monitorPoll || 400,
                scope: this
            });
        }
    }
});

/* papildinajums pie RowActions, lai stradatu RowEditor , jo trukst funkcijas getEditor() */
Ext.override(Ext.ux.grid.RowActions, {
    getEditor:function(){
        return false;
    }
});

/* pievienojam funkciju lai varetu uzstadit vertibu.Fak, kapec nevar pabeigt liidz galam.break errr*/
Ext.override(Ext.ux.form.ItemSelector,{
    setValue: function(val) {
        if(!val) {
            return;
        }
        val = val instanceof Array ? val : val.split(',');
        var rec, i, id;
        for(i = 0; i < val.length; i++) {
            id = val[i];
            if(this.toMultiselect.view.store.getById(id)) {
                continue;
            }
            rec = this.fromMultiselect.view.store.getById(id);
            if(rec) {
                this.toMultiselect.view.store.add(rec);
                this.fromMultiselect.view.store.remove(rec);
            }
        }
    this.fromMultiselect.view.refresh();
    this.toMultiselect.view.refresh();
    }
});

/* Helper class to make definition of typical stores for Combobox shorter */
Ext.o3mod.ComboStore = Ext.extend(Ext.data.DirectStore, {
    constructor : function(config){
        var c = Ext.apply({}, {
            paramsAsHash: false,
            root: 'data',
            autoDestroy :true,
            paramOrder: ['table'],
            baseParams: {table : ''}
        }, config);
        Ext.o3mod.ComboStore.superclass.constructor.call(this,Ext.apply(c));
    }
});

/* render components inside listView and dataView */
Ext.ns('Ext.ux');
Ext.ux.ComponentDataView = Ext.extend(Ext.DataView, {
    defaultType: 'textfield',
    initComponent : function(){
        Ext.ux.ComponentDataView.superclass.initComponent.call(this);
        this.components = [];
    },
    refresh : function(){
        Ext.destroy(this.components);
        this.components = [];
        Ext.ux.ComponentDataView.superclass.refresh.call(this);
        this.renderItems(0, this.store.getCount() - 1);
    },
    onUpdate : function(ds, record){
        var index = ds.indexOf(record);
        if(index > -1){
            this.destroyItems(index);
        }
        Ext.ux.ComponentDataView.superclass.onUpdate.apply(this, arguments);
        if(index > -1){
            this.renderItems(index, index);
        }
    },
    onAdd : function(ds, records, index){
        var count = this.all.getCount();
        Ext.ux.ComponentDataView.superclass.onAdd.apply(this, arguments);
        if(count !== 0){
            this.renderItems(index, index + records.length - 1);
        }
    },
    onRemove : function(ds, record, index){
        this.destroyItems(index);
        Ext.ux.ComponentDataView.superclass.onRemove.apply(this, arguments);
    },
    onDestroy : function(){
        Ext.ux.ComponentDataView.onDestroy.call(this);
        Ext.destroy(this.components);
        this.components = [];
    },
    renderItems : function(startIndex, endIndex){
        var ns = this.all.elements;
        var args = [startIndex, 0];
        for(var i = startIndex; i <= endIndex; i++){
            var r = args[args.length] = [];
            for(var items = this.items, j = 0, len = items.length, c; j < len; j++){
                c = items[j].render ?
                    c = items[j].cloneConfig() :
                    Ext.create(items[j], this.defaultType);
                r[j] = c;
                if(c.renderTarget){
                    c.render(Ext.DomQuery.selectNode(c.renderTarget, ns[i]));
                }else if(c.applyTarget){
                    c.applyToMarkup(Ext.DomQuery.selectNode(c.applyTarget, ns[i]));
                }else{
                    c.render(ns[i]);
                }
                if(Ext.isFunction(c.setValue) && c.applyValue){
                    c.setValue(this.store.getAt(i).get(c.applyValue));
                    c.on('blur', function(f){
                    	this.store.getAt(this.index).data[this.dataIndex] = f.getValue();
                    }, {store: this.store, index: i, dataIndex: c.applyValue});
                }
            }
        }
        this.components.splice.apply(this.components, args);
    },
    destroyItems : function(index){
        Ext.destroy(this.components[index]);
        this.components.splice(index, 1);
    }
});
Ext.reg('compdataview', Ext.ux.ComponentDataView);

Ext.ux.ComponentListView = Ext.extend(Ext.ListView, {
    defaultType: 'textfield',
    initComponent : function(){
        Ext.ux.ComponentListView.superclass.initComponent.call(this);
        this.components = [];
    },
    refresh : function(){
        Ext.destroy(this.components);
        this.components = [];
        Ext.ux.ComponentListView.superclass.refresh.apply(this, arguments);
        this.renderItems(0, this.store.getCount() - 1);
    },
    onUpdate : function(ds, record){
        var index = ds.indexOf(record);
        if(index > -1){
            this.destroyItems(index);
        }
        Ext.ux.ComponentListView.superclass.onUpdate.apply(this, arguments);
        if(index > -1){
            this.renderItems(index, index);
        }
    },
    onAdd : function(ds, records, index){
        var count = this.all.getCount();
        Ext.ux.ComponentListView.superclass.onAdd.apply(this, arguments);
        if(count !== 0){
            this.renderItems(index, index + records.length - 1);
        }
    },
    onRemove : function(ds, record, index){
        this.destroyItems(index);
        Ext.ux.ComponentListView.superclass.onRemove.apply(this, arguments);
    },
    onDestroy : function(){
        Ext.ux.ComponentDataView.onDestroy.call(this);
        Ext.destroy(this.components);
        this.components = [];
    },
    renderItems : function(startIndex, endIndex){
        var ns = this.all.elements;
        var args = [startIndex, 0];
        for(var i = startIndex; i <= endIndex; i++){
            var r = args[args.length] = [];
            for(var columns = this.columns, j = 0, len = columns.length, c; j < len; j++){
                var component = columns[j].component;
                c = component.render ?
                    c = component.cloneConfig() :
                    Ext.create(component, this.defaultType);
                r[j] = c;
                var node = ns[i].getElementsByTagName('dt')[j].firstChild;
                if(c.renderTarget){
                    c.render(Ext.DomQuery.selectNode(c.renderTarget, node));
                }else if(c.applyTarget){
                    c.applyToMarkup(Ext.DomQuery.selectNode(c.applyTarget, node));
                }else{
                    c.render(node);
                }
                if(c.applyValue === true){
                	c.applyValue = columns[j].dataIndex;
                }
                if(Ext.isFunction(c.setValue) && c.applyValue){
                    c.setValue(this.store.getAt(i).get(c.applyValue));
                    c.on('blur', function(f){
                    	this.store.getAt(this.index).data[this.dataIndex] = f.getValue();
                    }, {store: this.store, index: i, dataIndex: c.applyValue});
                }
            }
        }
        this.components.splice.apply(this.components, args);
    },
    destroyItems : function(index){
        Ext.destroy(this.components[index]);
        this.components.splice(index, 1);
    }
});
Ext.reg('complistview', Ext.ux.ComponentListView);

/* get URL parameters ! */
Ext.getUrlParam = function(param) {
   var params = Ext.urlDecode(location.search.substring(1));
   return param ? params[param] : params;
};

Ext.data.GroupingDirectStore = Ext.extend(Ext.data.GroupingStore, {
    constructor : function(config){
        var c = Ext.apply({}, {
            batchTransactions: false
        }, config);
        Ext.data.GroupingStore.superclass.constructor.call(this, Ext.apply(c, {
            proxy: Ext.isDefined(c.proxy) ? c.proxy : new Ext.data.DirectProxy(Ext.copyTo({}, c, 'paramOrder,paramsAsHash,directFn,api')),
            reader: (!Ext.isDefined(c.reader) && c.fields) ? new Ext.data.JsonReader(Ext.copyTo({}, c, 'totalProperty,root,idProperty'), c.fields) : c.reader
        }));
    }
});
Ext.reg('groupingdirectstore', Ext.data.GroupingDirectStore);

Ext.override(Ext.Window, {
    fitHeight : function(offset){
        if(offset==undefined || offset==null)offset=0;
        var dimesions = {
                height:0
            };

        if (typeof window.innerWidth != 'undefined'){
          dimesions.height = window.innerHeight
        }

        else if (typeof document.documentElement != 'undefined'
         && typeof document.documentElement.clientWidth !=
         'undefined' && document.documentElement.clientWidth != 0){
           dimesions.height = document.documentElement.clientHeight
        }

        else{
           dimesions.height = document.getElementsByTagName('body')[0].clientHeight
        }
    this.setHeight(dimesions.height+offset);
    }
});

function getViewportDimensions(){
    var dimesions = {
        width:0,
        height:0
    };

 // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
 if (typeof window.innerWidth != 'undefined'){
      dimesions.width = window.innerWidth;
      dimesions.height = window.innerHeight;
 }

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document)
 else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0){
       dimesions.width = document.documentElement.clientWidth;
       dimesions.height = document.documentElement.clientHeight;
 }

 // older versions of IE
 else{
       dimesions.width = document.getElementsByTagName('body')[0].clientWidth;
       dimesions.height = document.getElementsByTagName('body')[0].clientHeight;
 }

    return dimesions;
}

/* set field label dynamically */
Ext.override(Ext.form.Field, {
    setFieldLabel: function(text) {
        if (this.rendered) {
            var labelSeparator = this.labelSeparator;

            if (typeof labelSeparator == 'undefined') {
                if (this.ownerCt && this.ownerCt.layout && typeof this.ownerCt.layout.labelSeparator != 'undefined')
                    labelSeparator = this.ownerCt.layout.labelSeparator;
                else
                    labelSeparator = '';
            }

            var formItem = this.el.up('.x-form-item', 10);

            if (formItem) {
                var label = formItem.child('.x-form-item-label');

                if (label)
                    label.update(text + labelSeparator);
            }
        } else
            this.fieldLabel = text;
    }
});

function fitWindow(height){
    var viewH = Ext.lib.Dom.getViewHeight(true);
    var newH = viewH > height ? height : (viewH -20); //adding 10 px on each side to see the shadow
    //console.log(viewH);
    return newH;
}
