/**
 * Ext.grid.GridFilters plugin
 * Add a method.
 */
if (!Ext.isEmpty(Ext.grid.GridFilters)) {
	Ext.override(Ext.grid.GridFilters, {
		/**
		 * Check if at least one of the plugin's filters is active.
		 * @return boolean
		 */
		hasActiveFilters: function() {
			var activeFilters = false;
			this.filters.each(function(filter) { filter.active ? activeFilters = true : ''; });
			return activeFilters;
		}
	});
}

/**
 * Ext.form.Field & Ext.form.Label
 * Add a qtip on the field and the label.
 */
Ext.override(Ext.form.Field, {
	afterRender : Ext.form.Field.prototype.afterRender.createSequence(function() {
		if (this.qtip) {
			Ext.QuickTips.register(Ext.applyIf(this.qtip, {
				target: this
			}));
		}
	})
});
Ext.override(Ext.form.Label, {
	afterRender : Ext.form.Label.prototype.afterRender.createSequence(function() {
		if (this.qtip) {
			Ext.QuickTips.register(Ext.applyIf(this.qtip, {
				target: this.getEl()
			}));
		}
	})
});

/**
 * Ext.layout.Accordion
 * Fix bugs.
 */
Ext.override(Ext.layout.Accordion, {

	renderItem : function(c) {
		if (this.animate === false) {
			c.animCollapse = false;
		}
	  /**
	   * Bug Fix
	   * "" >> "if (this.collapsible) {"
	   */
		if (this.collapsible) {
			c.collapsible = true;
		}
		if (this.autoWidth) {
			c.autoWidth = true;
		}
		if (this.titleCollapse) {
			c.titleCollapse = true;
		}
		if (this.hideCollapseTool) {
			c.hideCollapseTool = true;
		}
		if (this.collapseFirst !== undefined) {
			c.collapseFirst = this.collapseFirst;
		}
		if (!this.activeItem && !c.collapsed) {
			this.activeItem = c;
		} else if (this.activeItem && this.activeItem != c) {
			c.collapsed = true;
		}
		Ext.layout.Accordion.superclass.renderItem.apply(this, arguments);
		c.header.addClass('x-accordion-hd');
		c.on('beforeexpand', this.beforeExpand, this);
	},
	
	/**
	* Sets the active (visible) item in the layout.
	* @param {String/Number} item The string component id or numeric index of the item to activate
	*/
	setActiveItem : function(item) {
		item = this.container.getComponent(item);
		if (this.activeItem != item) {
			this.activeItem = item;
		}
	}
});

/**
 * Ext.Editor
 * Fix bugs.
 */
Ext.override(Ext.Editor, {
	doAutoSize : function(){
		if(this.autoSize){
			var sz = this.boundEl.getSize(), fs = this.field.getSize();
			switch(this.autoSize){
				case "width":
					this.setSize(sz.width, fs.height);
					break;
				case "height":
					this.setSize(fs.width, sz.height);
					break;
				case "none":
					this.setSize(fs.width, fs.height);
					break;
				default:
					this.setSize(sz.width,  sz.height);
			}
		}
	}
});

/**
 * Ext.PagingToolbar
 * Add the possibility to settle a text param for the refresh button.
 */
Ext.override(Ext.PagingToolbar, {
	refreshBtnText : "Refresh",
	onRender : function(ct, position) {
		Ext.PagingToolbar.superclass.onRender.call(this, ct, position);
		this.first = this.addButton({
				tooltip: this.firstText,
				iconCls: "x-tbar-page-first",
				disabled: true,
				handler: this.onClick.createDelegate(this, ["first"])
		});
		this.prev = this.addButton({
				tooltip: this.prevText,
				iconCls: "x-tbar-page-prev",
				disabled: true,
				handler: this.onClick.createDelegate(this, ["prev"])
		});
		this.addSeparator();
		this.add(this.beforePageText);
		this.field = Ext.get(this.addDom({
			 tag: "input",
			 type: "text",
			 size: "3",
			 value: "1",
			 cls: "x-tbar-page-number"
		}).el);
		this.field.on("keydown", this.onPagingKeydown, this);
		this.field.on("focus", function(){this.dom.select();});
		this.afterTextEl = this.addText(String.format(this.afterPageText, 1));
		this.field.setHeight(18);
		this.addSeparator();
		this.next = this.addButton({
				tooltip: this.nextText,
				iconCls: "x-tbar-page-next",
				disabled: true,
				handler: this.onClick.createDelegate(this, ["next"])
		});
		this.last = this.addButton({
				tooltip: this.lastText,
				iconCls: "x-tbar-page-last",
				disabled: true,
				handler: this.onClick.createDelegate(this, ["last"])
		});
		this.addSeparator();
		this.loading = this.addButton({
				text: !Ext.isEmpty(this.refreshBtnText) ? this.refreshBtnText : '',
				tooltip: this.refreshText,
				iconCls: "x-tbar-loading",
				handler: this.onClick.createDelegate(this, ["refresh"])
		});

		if(this.displayInfo){
				this.displayEl = Ext.fly(this.el.dom).createChild({cls:'x-paging-info'});
		}
		if(this.dsLoaded){
				this.onLoad.apply(this, this.dsLoaded);
		}
	}
});

/**
 * Ext.ux.menu.DateTimeMenu
 * http://extjs.com/forum/showthread.php?p=332918
 */
Ext.namespace("Ext.ux.menu");
Ext.ux.menu.DateTimeItem = function(config) {
	this.picker = new Ext.DatePicker(config);
	this.timefield = new Ext.form.TimeField(Ext.apply({
		listClass: 'x-menu',	/* required */
		increment: 5,
		forceSelection: true,
		selectOnFocus: true,
		editable: true,
		lazyInit: false,
		width: 175,
		maxHeight: 187,
		listAlign: 'bl-tl',
		//maxHeight: 150,
		//listAlign: 't-b',
		listeners: {expand: function(combo) { combo.list.setZIndex(16000); }}
	}, config.cfg_timepicker || {}));
	
	var okButton = new Ext.Button(Ext.apply({
		text: Ext.MessageBox.buttonText.ok,
		minWidth: 175,
		style: 'text-align: center; margin: 0 auto;',
		onClick: function(ev) {
			ev ? ev.preventDefault() : '';
			if (ev.button != 0) { return false; }
			if (!this.disabled) {
				this.fireEvent('click', this, ev);
				this.menuItem.parentMenu.hide(true);
				this.menuItem.onSelect(this);
				this.handler ? this.handler.call(this.scope || this, this, ev) : '';
			}
		}
	}, config.cfg_okButton || {}));
	okButton.menuItem = this;
	
	this.panel = new Ext.Panel({
		border: false,
		bodyBorder: false,
		items: [this.picker, this.timefield, okButton]
	});
	
	Ext.ux.menu.DateTimeItem.superclass.constructor.call(this, this.panel, config);
	this.addEvents('select');
	
	this.picker.on('render', function(picker) {
		picker.getEl().swallowEvent('click', true);
		picker.container.addClass('x-menu-date-item');
	});
};
Ext.extend(Ext.ux.menu.DateTimeItem, Ext.menu.Adapter, {
	hideOnClick: false,
	onSelect : function(picker, date) {
		this.fireEvent('select', this, date, picker);
		Ext.menu.DateItem.superclass.handleClick.call(this);
	},
	isValid: function(dateMenuItem) {
		var time = dateMenuItem.timefield.getValue();
		time = time.replace(/\s+/g, '');
		if (!(/^[0-2]?[0-9]:[0-9][0-9]([aApP][mM])?$/.test(time))) { return false; }
		return true;
	}
});
Ext.ux.menu.DateTimeMenu = function(config) {
  Ext.menu.DateMenu.superclass.constructor.call(this, config);
  this.plain = true;
  var di = new Ext.ux.menu.DateTimeItem(config);
  this.add(di);
  this.picker = di.picker;
  this.timefield = di.timefield;
  this.relayEvents(di, ['select']);
  this.on('beforeshow', function() {
		this.picker ? this.picker.hideMonthPicker(true) : '';
  }, this);
};
Ext.extend(Ext.ux.menu.DateTimeMenu, Ext.menu.DateMenu, {});


/**
 * Ext.grid.GridView
 * Override methods to allow "iconCls" in grid headers.
 *//*
Ext.override(Ext.grid.GridView, {
	// override this method
	renderHeaders : function() {
		var cm = this.cm, ts = this.templates;
		var ct = ts.hcell;
		
		var cb = [], sb = [], p = {};
		
		for(var i = 0, len = cm.getColumnCount(); i < len; i++){
			p.id = cm.getColumnId(i);
			p.value = cm.getColumnHeader(i) || "";
			p.style = this.getColumnStyle(i, true);
			p.tooltip = this.getColumnTooltip(i);
			p.headerIconCls = cm.config[i].headerIconCls;
			if(cm.config[i].align == 'right'){
				p.istyle = 'padding-right:16px';
			} else {
				delete p.istyle;
			}
			cb[cb.length] = ct.apply(p);
		}
		return ts.header.apply({cells: cb.join(""), tstyle:'width:'+this.getTotalWidth()+';'});
	},
	
	// private
	initTemplates : function() {
		var ts = this.templates || {};
		if (!ts.master) {
			ts.master = new Ext.Template(
				'<div class="x-grid3" hidefocus="true">',
					'<div class="x-grid3-viewport">',
						'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset">{header}</div></div><div class="x-clear"></div></div>',
						'<div class="x-grid3-scroller"><div class="x-grid3-body">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
					"</div>",
					'<div class="x-grid3-resize-marker">*</div>',
					'<div class="x-grid3-resize-proxy">*</div>',
				"</div>"
			);
		}
		if (!ts.header) {
		    ts.header = new Ext.Template(
		            '<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
		            '<thead><tr class="x-grid3-hd-row">{cells}</tr></thead>',
		            "</table>"
		            );
		}
		if (!ts.hcell) {
		    ts.hcell = new Ext.Template(
		            '<td class="x-grid3-hd x-grid3-cell x-grid3-td-{id}" style="{style}"><div {tooltip} {attr} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}"><img class="{headerIconCls}" src="', Ext.BLANK_IMAGE_URL, '"></img>', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '',
		            '{value}<img class="x-grid3-sort-icon" src="', Ext.BLANK_IMAGE_URL, '" />',
		            "</div></td>"
		            );
		}
		if (!ts.body) {
		    ts.body = new Ext.Template('{rows}');
		}
		if (!ts.row) {
		    ts.row = new Ext.Template(
		            '<div class="x-grid3-row {alt}" style="{tstyle}"><table class="x-grid3-row-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
		            '<tbody><tr>{cells}</tr>',
		            (this.enableRowBody ? '<tr class="x-grid3-row-body-tr" style="{bodyStyle}"><td colspan="{cols}" class="x-grid3-body-cell" tabIndex="0" hidefocus="on"><div class="x-grid3-row-body">{body}</div></td></tr>' : ''),
		            '</tbody></table></div>'
		            );
		}
		if (!ts.cell) {
		    ts.cell = new Ext.Template(
		            '<td class="x-grid3-col x-grid3-cell x-grid3-td-{id} {css}" style="{style}" tabIndex="0" {cellAttr}>',
		            '<div class="x-grid3-cell-inner x-grid3-col-{id}" unselectable="on" {attr}>{value}</div>',
		            "</td>"
		            );
		}
		
		for(var k in ts){
		    var t = ts[k];
		    if(t && typeof t.compile == 'function' && !t.compiled){
		        t.disableFormats = true;
		        t.compile();
		    }
		}
		
		this.templates = ts;
		
		this.tdClass = 'x-grid3-cell';
		this.cellSelector = 'td.x-grid3-cell';
		this.hdCls = 'x-grid3-hd';
		this.rowSelector = 'div.x-grid3-row';
		this.colRe = new RegExp("x-grid3-td-([^\\s]+)", "");
	}
});
*/
/**
 * Ext.grid.ColumnModel
 * Override methods to allow "iconCls" in grid headers.
 *//*
Ext.override(Ext.grid.ColumnModel, {
	/**
	 * Override and set custom css values
	 * Reconfigures this column model
	 * @param {Array} config Array of Column configs
	 *//*
	headerIconCls: '',
	setConfig: function(config, initial) {
	  if (!initial) {
			delete this.totalWidth;
			for (var i = 0, len = this.config.length; i < len; i++) {
				var c = this.config[i];
				if (c.editor){
					c.editor.destroy();
				}
			}
	  }
		this.config = config;
		this.lookup = {};
		
		for (var i = 0, len = config.length; i < len; i++) {
			var c = config[i];
			if (typeof c.renderer == "string") {
				c.renderer = Ext.util.Format[c.renderer];
			}
			if (typeof c.id == "undefined") {
				c.id = i;
			}
			if (c.editor && c.editor.isFormField) {
				c.editor = new Ext.grid.GridEditor(c.editor);
				//Use pointer cursor for editable fields
				var cursorString = "cursor:pointer !important;";
				if (c.css)
				{
					// append the cursor string
					c.css += ";" + cursorString;
				}
				else
				{
					c.css = cursorString;
				}
				if (!c.tooltip)
				{
					c.tooltip = "You can edit fields in this column by clicking left mouse button";
				}
			}
			this.lookup[c.id] = c;
		}
		if (!initial) {
			this.fireEvent('configchange', this);
		}
	}
});
*/