//Overide for radio and checkbox groups.
Ext.override(Ext.form.RadioGroup, {
  getName: function() {
    return this.items.first().getName();
  },

  getValue: function() {
    var v;

    this.items.each(function(item) {
      v = item.getRawValue();
      return !item.getValue();
    });

    return v;
  },

  setValue: function(v) {
    this.items.each(function(item) {
      item.setValue(item.getRawValue() == v);
    });
  }
});

//Overisde for cascading windows
Ext.override(Ext.Window, {
    beforeShow : function(){
        delete this.el.lastXY;
        delete this.el.lastLT;
        if(this.x === undefined || this.y === undefined){
            var xy = this.el.getAlignToXY(this.container, 'c-c');
            var pos = this.el.translatePoints(xy[0], xy[1]);
            this.x = this.x === undefined? pos.left : this.x;
            this.y = this.y === undefined? pos.top : this.y;
            if (this.cascadeOnFirstShow) {
                var prev;
                this.manager.each(function(w) {
                    if (w == this) {
                        if (prev) {
                        	var o = (typeof this.cascadeOnFirstShow == 'number') ? this.cascadeOnFirstShow : 20;
                            var p = prev.getPosition();
                            this.x = p[0] + o;
                            this.y = p[1] + o;
                        }
                        return false;
                    }
                    if (w.isVisible()) prev = w;
                }, this);
            }
        }
        this.el.setLeftTop(this.x, this.y);

        if(this.expandOnShow){
            this.expand(false);
        }

        if(this.modal){
            Ext.getBody().addClass("x-body-masked");
            this.mask.setSize(Ext.lib.Dom.getViewWidth(true), Ext.lib.Dom.getViewHeight(true));
            this.mask.show();
        }
    }
});

//methods to validate htmleditors
Ext.override(Ext.form.HtmlEditor, {
	markInvalid: function(msg){
		if(!this.rendered || this.preventMark){
			return;
		}
		msg = msg || this.invalidText;
		switch(this.msgTarget){
			case 'qtip':
				this.iframe.qtip = msg;
				this.iframe.qclass = 'x-form-invalid-tip';
				Ext.get(this.iframe).addClass(this.invalidClass);
				
				break;
		}
		return Ext.form.TextArea.superclass.markInvalid.call(this, [msg]);
	},
	clearInvalid: function(){
		if(!this.rendered || this.preventMark){
			return;
		}
		switch(this.msgTarget){
			case 'qtip':
				this.iframe.qtip = '';
				Ext.get(this.iframe).removeClass(this.invalidClass);
				break;
		}
		return Ext.form.TextArea.superclass.clearInvalid.call(this);
	},
	validateValue:function(){
		if(this.allowBlank==false){

			var value =this.getRawValue();
			value = value.replace(/&nbsp;/gi,"");
			value = value.replace(/<br>/gi,"");
			value = value.trim();
			if(value != ''){
				this.clearInvalid();
				return true;
			 }
			else{
				this.markInvalid("This field is required.")
				return false;
				}
		}else{
			this.clearInvalid();
			return true;
		}


	}
});
Ext.form.HtmlEditor.prototype.listeners={ sync: function(t,html){t.validateValue();}};

Ext.override(Ext.form.ComboBox, {
    triggerAction : 'all'
});

Ext.override(Ext.grid.GroupingView, {
	//changed method to add capability to disable paging when a grid is grouped 
	onGroupByClick : function(){
		if (this.disablePageOnGroup){
			if (!this.origPageLimit) this.origPageLimit = this.grid.getBottomToolbar().pageSize;
			if (this.grid.store.autoLoad) this.grid.store.autoLoad.params.limit = 99999;
			if (this.grid.store.baseParams.limit) this.grid.store.setBaseParam('limit',99999);
			this.grid.getBottomToolbar().pageSize = 99999;
		}
        this.grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
        this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups
    },
	//changed method to add capability to disable paging when a grid is grouped 
	onShowGroupsClick : function(mi, checked){
        if(checked){
            this.onGroupByClick();
        }else{
			if (this.disablePageOnGroup){
				if (this.grid.store.autoLoad) this.grid.store.autoLoad.params.limit = this.origPageLimit;
				if (this.grid.store.baseParams.limit) this.grid.store.setBaseParam('limit',this.origPageLimit);
				this.grid.getBottomToolbar().pageSize = this.origPageLimit;
			}
            this.grid.store.clearGrouping();
        }
    }
});


Ext.override(Ext.data.GroupingStore, {
    applyGroupField: function() {
        if (this.remoteGroup) {
            if (!this.baseParams) {
                this.baseParams = {};
            }
            this.baseParams.groupBy = this.groupField;
            this.baseParams.groupDir = this.groupDir;
            if (this.lastOptions && this.lastOptions.params) {
                delete this.lastOptions.params.groupBy;
            }
        }
    },//changed method to include a count of the groups
	loadRecords : function(o, options, success){
        if (this.isDestroyed === true) {
            return;
        }
        if(!o || success === false){
            if(success !== false){
                this.fireEvent('load', this, [], options);
            }
            if(options.callback){
                options.callback.call(options.scope || this, [], options, false, o);
            }
            return;
        }
        var r = o.records, t = o.totalRecords || r.length, g = o.totalGroups;
        if(!options || options.add !== true){
            if(this.pruneModifiedRecords){
                this.modified = [];
            }
            for(var i = 0, len = r.length; i < len; i++){
                r[i].join(this);
            }
            if(this.snapshot){
                this.data = this.snapshot;
                delete this.snapshot;
            }
            this.clearData();
            this.data.addAll(r);
            this.totalLength = t;
			this.groupCount = g;
            this.applySort();
            this.fireEvent('datachanged', this);
        }else{
            this.totalLength = Math.max(t, this.data.length+r.length);
			this.groupCount = g;
            this.add(r);
        }
        this.fireEvent('load', this, r, options);
        if(options.callback){
            options.callback.call(options.scope || this, r, options, true);
        }
    }
});

Ext.override(Ext.data.JsonReader, {
	//changed method to include a count of the groups
	readRecords : function(o){
	    this.jsonData = o;
	    if(o.metaData){
	        this.onMetaChange(o.metaData);
	    }
	    var s = this.meta, Record = this.recordType,
	        f = Record.prototype.fields, fi = f.items, fl = f.length, v;
	
	    var root = this.getRoot(o), c = root.length, totalRecords = c, success = true, totalGroups = "";
	    if(s.totalProperty){
	        v = parseInt(this.getTotal(o), 10);
	        if(!isNaN(v)){
	            totalRecords = v;
	        }
	    }
		
		if(s.totalGroupProperty){
			totalGroups = o.groupcount || 0;
		}

	    if(s.successProperty){
	        v = this.getSuccess(o);
	        if(v === false || v === 'false'){
	            success = false;
	        }
	    }
	
	    return {
	        success : success,
	        records : this.extractData(root, true), // <-- true to return [Ext.data.Record]
	        totalRecords : totalRecords,
			totalGroups : totalGroups
	    };
	}
});

Ext.override(Ext.PagingToolbar, {
	//changed method to use the group count as the page count (ie. Displaying 1-"10" of 20). the 10 is the page count.
	updateInfo : function(){
        if(this.displayItem){
            var count = this.pageByGroup ? this.store.groupCount : this.store.getCount();
            var msg = count == 0 ?
                this.emptyMsg :
                String.format(
                    this.displayMsg,
                    this.cursor+1, this.cursor+count, this.store.getTotalCount()
                );
            this.displayItem.setText(msg);
        }
    }
});

//Renderers////////////////////////////////
function percentRenderer(value){
	return value ? String.format("{0}%",Math.round(value*100)):'';
}
