/**
 * @package		LQM Component
 * @subpackage	Assets
 * @version		$Id: default.js 786 2009-07-23 13:04:12Z tcp $
 * @copyright	Copyright (C) 2006 - 2007 Green Mountain Information Technology and Consulting. All rights reserved.
 * @author		tcp@gmitc.biz
 */

LQM={version:"4.0"}

LQM.OpenDiv = function (url, target)
{
	var div = Ext.get(target);
	if ( div )
	{
		div.load({
			url: url,
			scripts: true,
			text: 'Updating...'
		});
	}
	
	return false;
}

LQM.OpenWindow = function ( url, from, width, height )
{

	var cfg = {
			animateTarget:	from,
			border:			false,
			plain:			true,
			autoLoad:		url
		};
	
	if ( width > 0 && height > 0 ) {
		cfg.width = width*1;
		cfg.height = height*1;
		cfg.autoHeight = false;
	} else {
		//cfg.autoHeight = true;
		// Problem with IE and autoHeight in Ext.window
		cfg.width = 400;
		cfg.height = 400;
		cfg.autoScroll = true;
	}
	
	var win = new Ext.Window(cfg);

	win.show();
	
	return false;
}

LQM.clone = function (obj){
	if(obj == null || typeof(obj) != 'object')
		return obj;

	var temp = new obj.constructor(); // changed (twice)
	for(var key in obj)
		temp[key] = LQM.clone(obj[key]);

	return temp;
}

Ext.apply(Ext,{BLANK_IMAGE_URL: '../../../../plugins/gmitc/extjs/resources/images/default/s.gif'});

Ext.form.FieldSet.prototype.onRender = function(ct, position){
		if(!this.el){
			this.el = document.createElement('fieldset');
			this.el.id = this.id;
			if (this.title || this.header || this.checkboxToggle) {
				this.el.appendChild(document.createElement('legend')).className = 'x-fieldset-header';
			}
		}
		
		if (this.desc) {
			var div = document.createElement('div');
			div.className = 'x-fieldset-description x-form-element';
			div.innerHTML = this.desc;
			this.el.appendChild(div) ;
		}
 
		Ext.form.FieldSet.superclass.onRender.call(this, ct, position);

		if(this.checkboxToggle){
			var o = typeof this.checkboxToggle == 'object' ?
					this.checkboxToggle :
					{tag: 'input', type: 'checkbox', name: this.checkboxName || this.id+'-checkbox'};
			this.checkbox = this.header.insertFirst(o);
			this.checkbox.dom.checked = !this.collapsed;
			this.checkbox.on('click', this.onCheckClick, this);
		}

};

Ext.apply(Ext.layout.FormLayout.prototype, {
	renderItem: function(c, position, target){

		if(c && !c.rendered && c.isFormField && c.inputType != 'hidden'){
			 
			if ( c.desc && ! c.descCls ) { c.descCls = 'x-form-item-desc'; }

			if( c.allowBlank==false){
				c.fieldLabel = '<span class="x-form-label-required"></span>'+c.fieldLabel;
			}
			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',
					c.desc||'',
					c.descCls||'',
					c.help||''
			];
			if(typeof position == 'number'){
				position = target.dom.childNodes[position] || null;
			}
			if(position){
					this.fieldTpl.insertBefore(position, args);
			}else{
					this.fieldTpl.append(target, args);
			}
	
			c.render('x-form-el-'+c.id);
		}else {
			Ext.layout.FormLayout.superclass.renderItem.apply(this, arguments);
		}
	}
});

var t = new Ext.Template(
		'<div class="x-form-item {5}" tabIndex="-1" span="background: red;" >',
			'<label for="{0}" style="{2}" class="x-form-item-label" >',
				'{1}{4}<span class="{8}" ext:qtip="{7}"></span>',
			'</label>',
			'<div class="x-form-element" id="x-form-el-{0}" style="{3}" title="{9}">',
			
			'</div><div class="{6}"></div>',
			
		'</div>'
);
t.disableFormats = true;
t.compile();
Ext.layout.FormLayout.prototype.fieldTpl = t;


Ext.apply(Ext.form.VTypes, {
	confirm : function(val, field) {
		if (field.matchField) {
			var pwd = Ext.getCmp(field.matchField);
			return (val == pwd.getValue());
		}
		return true;
	},
	
	confirmText : 'The values that you provided do not match'
});

// Our paging store
LQM.PagingStore = function(args) {
	LQM.PagingStore.superclass.constructor.call(this, args);
};
Ext.extend(LQM.PagingStore, Ext.data.GroupingStore, {
	
	previousResults : undefined,
	
	params : {},
		
	load : function(options) {
	
		if ( typeof options == 'undefined' ) { 
			options = {
					params : { start: 0, limit: 100000 }
			};
		} else {
			if ( ! options.params.start ) {
				options.params.start = 0; 
			}
			
			if ( ! options.params.limit ) {
				options.params.limit = 100000; 
			}
		}
		
		this.params = options.params;

		if ( this.previousResults && typeof this.params.reload == "undefined") { 
			var prev = this.previousResults;
			var o = { 
					success: true,
					totalRecords: prev.o.totalRecords,
					records: prev.o.records
					//records: prev.o.records.slice(this.params.start, this.params.start + this.params.limit)
			};
			return LQM.PagingStore.superclass.loadRecords.call(this, o, options, prev.success);
		}
		return LQM.PagingStore.superclass.load.call(this, options);
	},
	
	loadRecords : function(o, options, success){
		var reload = (typeof options.params.reload !== "undefined");
		if ( success && ( ! this.previousResults || reload ) ) { 
			this.previousResults	= { o: o, options: options, success: success };
		}
		
		return LQM.PagingStore.superclass.loadRecords.call(this, o, options, success);
	},
	
	applySort : function(){
		Ext.data.GroupingStore.superclass.applySort.call(this);
		if(!this.groupOnSort && !this.remoteGroup){
			
			var gs = this.getGroupState();
			
			if ( gs && ! this.sortInfo ) {
				this.sortInfo = { field: gs, direction: 'ASC' };
			}
			if( gs && this.sortInfo && ( gs != this.sortInfo.field || this.groupDir != this.sortInfo.direction)){
				this.sortData(this.groupField, this.groupDir);
			}
		}
	},
	
	getParams : function(){
		return this.params;
	}
	
});
Ext.reg('pagingstore', LQM.PagingStore);

// Our grid view
LQM.PagingGridView = function(args) {
	LQM.PagingGridView.superclass.constructor.call(this, args);
};

Ext.extend(LQM.PagingGridView, Ext.grid.GroupingView, {
	
	renderBody : function(){
		var params	= this.ds.getParams();
		var start	= params.start, end = start + params.limit -1;
		var markup	= LQM.PagingGridView.superclass.renderRows.call(this, start, end) || '&nbsp;';
		return this.templates.body.apply({rows: markup});
	}
});
Ext.reg('paginggridview', LQM.PagingGridView);

LQM.PagingToolbar = function(args) {
	LQM.PagingToolbar.superclass.constructor.call(this, args);
};

Ext.extend(LQM.PagingToolbar, Ext.PagingToolbar, {

	refresh : function() {
        var o = {}, pn = this.getParams();
        o[pn.start] = this.cursor;
        o[pn.limit] = this.pageSize;
        o['reload'] = true;
        if(this.fireEvent('beforechange', this, o) !== false){
            this.store.load({params:o});
        }
	},
	
	updateInfo : function(){
		if(this.displayItem){
			var count = this.store.getCount();
			var total = this.store.getTotalCount();
			var display = this.cursor + this.pageSize;
			
			if (display > total) { 
				display = total;
			}
			
			var msg = count == 0 ?
				this.emptyMsg :
				String.format(
					this.displayMsg,
					this.cursor+1, display, total
				);
			this.displayItem.setText(msg);
		}
	}
});

Ext.form.TextField.prototype.validateValue = 
function(value){

	if(value.length < 1 || value === this.emptyText){ // if it's blank
		if(this.allowBlank){
			this.clearInvalid();
			return true;
		}else{
			this.markInvalid(this.blankText);
			return false;
		}
   }
	if(Ext.isFunction(this.validator)){
		var msg = this.validator(value);
		if(msg !== true){
			this.markInvalid(msg);
			return false;
		}
	}
	if(this.vtype){
		var vt = Ext.form.VTypes;
		if(!vt[this.vtype](value, this)){
			this.markInvalid(this.vtypeText || vt[this.vtype +'Text']);
			return false;
		}
	}
	if(this.regex && !this.regex.test(value)){
		this.markInvalid(this.regexText);
		return false;
	}
	
	if(value.length < this.minLength){
		this.markInvalid(String.format(this.minLengthText, this.minLength));
		return false;
	}
	if(value.length > this.maxLength){
		this.markInvalid(String.format(this.maxLengthText, this.maxLength));
		return false;
	}
	return true;
};


//Hack to get ExtJS to load json correctly in IE
Ext.decode = function(json)
{
	if ( json == '' ) return false;
	
	if ( Ext.isIE ) {
		json = json.replace(/(\r\n|\n|\r)/g, " ");
	}
    return eval("(" + json + ')');    
}
