// Thought Junction Javascript Startup Engine.
// TJ Admin Record management components

/* Management for Table_ID */

// Record Viewing!!!
	TJ.Admin.RecordPublishPanel = Ext.extend(Ext.form.FormPanel, {
		defaults:  {
			anchor: '-20'
		},
		labelAlign: 'right',
		labelWidth: 60,

//		frame: true,
		border: false,
		bodyStyle: { padding: "6px", backgroundColor: '#DFE8F6'},
//		style: "padding: 6px;	background-color:#DFE8F6;",
		initComponent: function(){
			this.tbar=[String.format('Publishing information for this {0}',this.tableinfo.lang.label)];
			this.items= [
					this.status  = new TJ.comp.Select( { listWidth: 100, fieldLabel: 'Status',name:'status', store: ['Draft','For Translation','For Review','For Publishing','Published','Archived']}),
					this.pubDate = new TJ.comp.DateTimeField( { fieldLabel: 'Published On',name:'pubDate'})


				];
			this.saveBtn = new Ext.Toolbar.Button({
					text: 'Save',
					disabled: true,
					iconCls: 'icon_accept',
					handler: function() {
						this.saveChanges();
					},
					scope: this
			});
			
			this.setAllBtn = new Ext.Toolbar.Button({
					text: 'Set All',
					disabled: false,
					iconCls: 'icon_lightning',
					handler: this.setAll,
					qtip: 'Set all published dates to their creation date',
					scope: this


			});

				this.bbar=[this.setAllBtn,'->',this.saveBtn];
				this.status.on('select',function(){ this.saveBtn.setDisabled(false);},this);
				this.pubDate.on('change',function(){ this.saveBtn.setDisabled(false);},this);

			TJ.Admin.RecordPublishPanel.superclass.initComponent.call(this);
		},
		setAll: function() {
			TJ.CallbackManager.Direct({ cls: 'AdminTable',
										method: 'SetPublishingForAll',	
										callback: Ext.emptyFn,
										params:	{
											  table:		this.tableinfo['class']
										},
									scope: this });


		},
		saveChanges: function() {
			this.record.set('_status',this.status.getValue());
			this.record.set('_published',this.pubDate.getValue());
			this.saveBtn.setDisabled(true);				
			TJ.CallbackManager.Direct({ cls: 'AdminTable',
										method: 'SetPublishing',	
										params:	{
											  table:		this.tableinfo['class'],
											  recordid:		this.record.data._id,
											  status:		this.status.getValue(),
											  pubDate:		this.pubDate.getValue()
										},
									callback: this.saveCallback,
									scope: this });



		},
		saveCallback: function (val,res,opt) {	
			if(res.success) {
				this.record.set('_status',this.status.getValue());
				this.record.set('_published',this.pubDate.getValue());
				this.record.commit();
			} else
				this.saveBtn.setDisabled(false);
		},
		setRecord:function(record){
			this.record=record;
			this.status.setValue(record.data._status);
			this.pubDate.setValue(record.data._published);
			this.saveBtn.setDisabled(true);
//			console.log('setme',record);
		}

	});

	TJ.Admin.RecordPreviewPanel=Ext.extend(Ext.grid.PropertyGrid,{
		title: 'Preview',
		propertyNames:{},
		source: {},
		startEditing: Ext.emptyFn,
		initComponent: function(){
//			this.tbar=['Status', new TJ.comp.DateTimeField({})];
			this.propertyNames={};
			this.customRenderers={};
			this.source={};
			for(var i=0;i<this.tableinfo.columns.length;i++){
//				console.log(this.tableinfo.columns[i]);
				this.propertyNames[this.tableinfo.columns[i].dataIndex]=
					this.tableinfo.columns[i].header;
//				this.customRenderers[this.tableinfo.columns[i].dataIndex]= this.renderer;

			}

			TJ.Admin.RecordPreviewPanel.superclass.initComponent.call(this);
			this.store.sortInfo = null; 
			this.getColumnModel().renderCellDelegate=this.valueRenderer;
			if(this.recordid)
				this.setRecordByID(this.recordid);

		},
		valueRenderer: function(value,metadata,record,row,col,store){
			if(store.fullRecord.data['__' + record.id]){
				return String.format('{0} ({1})',store.fullRecord.data['__' + record.id],value);
			}
			return value;
		},
		setRecord:function(record){

			this.store.fullRecord=record;

			var source={};
			for(name in record.data){
				if(this.propertyNames[name])
					source[name]=record.data[name];
			}
			this.setSource(source);
		},
		setRecordByID: function(recordid){
			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + recordid + ':getrecord',
								params: {id: recordid},
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
											this.setRecord({data:res.record});
											console.log('record!!',{data:res.record});

										},
										scope:this
										});
			
		}

	});

	Ext.reg('tjadminrecordview',TJ.Admin.RecordPreviewPanel);

TJ.Admin.RecordEditForm = Ext.extend(TJ.Admin.StatusPanelForm,{
	initComponent: function (){
		this.title='Edit ' + this.tableinfo.lang.label;
		this.formconfig.url=this.rooturl + ':doedit';
		TJ.Admin.RecordEditForm.superclass.initComponent.call(this);
	}
});

Ext.reg('tjadminrecordedit',TJ.Admin.RecordEditForm);

TJ.Admin.RecordCopyForm = Ext.extend(TJ.Admin.StatusPanelForm,{
//	disabled: true,
	initComponent: function (){
		this.title='Copy ' + this.tableinfo.lang.label;
		this.formconfig.url=this.rooturl + ':docopy';
		TJ.Admin.RecordEditForm.superclass.initComponent.call(this);
	}
});

Ext.reg('tjadminrecordcopy',TJ.Admin.RecordCopyForm);

	TJ.Admin.RecordHistoryPanel = Ext.extend(Ext.grid.GridPanel, {
        stripeRows: true,
		initComponent: function(){
			this.initialTitle = this.title='Viewing history of this ' + this.tableinfo.lang.label;
	        this.columns = [
					{header: "Timestamp", width: 125, sortable: true, renderer: Ext.util.Format.dateRenderer('Y/m/d H:i:s'), dataIndex: 'timestamp'},
					{header: "Action", width: 100, sortable: true, dataIndex: 'action', renderer: this.renderAction},
					{header: "Username (ID)", width: 150, sortable: true, dataIndex: 'username', renderer: this.renderUsername},
					{header: "Description", dataIndex: 'desc'}
				];


				this.store = new Ext.data.Store( {
					remoteSort: true,
					proxy: new Ext.data.HttpProxy({
						url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + this.recordid + ':gethistory' }),
					reader: new Ext.data.JsonReader({
						root: 'rows',
						idProperty: null,
						totalProperty: 'numrows'
						},
						[	{name:'timestamp', type:'date', dateFormat:"Y-m-d H:i:s"},
							{name:'action'},
							{name:'username'},
							{name:'desc'},
							{name:'userid'}
							])
					});
				this.store.on('load',function(){this.setTitle(this.initialTitle);},this);
				this.bbar =  new Ext.PagingToolbar({
					pageSize: 20,
					store: this.store,
					displayInfo: true,
					displayMsg: 'Displaying history  {0} - {1} of {2}',
					emptyMsg: 'No history to display'
				});

				this.store.load({params: {start: 0, limit: 20}});
				TJ.Admin.RecordHistoryPanel.superclass.initComponent.call(this);
				TJ.Admin.TableManager.on('tabledatachange',this.tableDataChange,this);
			},
			tableDataChange: function(table,operation,recordid){
				if( (table==this.tableinfo.table) && (recordid==this.recordid)) {
					this.setTitle(this.initialTitle +'*');
				}
			},
			renderUsername:function(value,p,record){
				return String.format('{0} ({1})',record.data.username, record.data.userid);
			},
			renderAction:function(value,p,record){
				return value ;
			}
	});

Ext.reg('tjadminrecordhistory',TJ.Admin.RecordHistoryPanel);




/* Management for Table_Type */


/* Secure Handling */


TJ.Admin.RecordSecurePanel = Ext.extend(Ext.TabPanel,{
	activeTab: 0,
	defaults : {
					autoScroll: true,
					layout: 'fit',
					loaded: false},

	initComponent: function(){
		this.title='Secure access for this ' + this.tableinfo.lang.plural;
		this.items = [ {title: 'Users',
						func: 'users'
						},
						{title: 'Usergroups',
						 func: 'groups'
						 }
						 ];
		this.on('tabchange',this.tabChange);
		TJ.Admin.RecordSecurePanel.superclass.initComponent.call(this);
	},
	tabChange: function(mainpanel,tab) {
		if(tab.func) {
			if(! tab.loaded) {
				var panel;
				if(tab.func=='users') {
					TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-cl_user_account_table:gettableinfo2', 
												callback: function(val){ 
					panel = new TJ.Admin.TableRelatedGridPanel({title: 'Users with access to this content',
																tableinfo: val, 
																relation: {table: this.tableinfo['class'], 
																id: this.recordid}});
							tab.add(panel);
							tab.doLayout();
							tab.loaded=true;						
												},
												scope: this});


				} else
				if(tab.func=='groups') {
					TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-cl_user_group_table:gettableinfo2', 
												callback: function(val){ 

					panel = new TJ.Admin.TableRelatedGridPanel({title: 'Usergroups with access to this content',
																		tableinfo: val, relation: {table: this.tableinfo['class'], id: this.recordid}});
					tab.add(panel);
					tab.doLayout();
					tab.loaded=true;
												},
												scope: this});

				} else
				console.log(tab.func);
			}
		}
	}
});

Ext.reg('tjadminrecordsecure',TJ.Admin.RecordSecurePanel);


// Related
TJ.Admin.RecordRelatedGridPanel = Ext.extend(TJ.Admin.TableAddRemoveGridPanel,{
	initComponent: function(){
		this.baseParams = this.relation;
//		this.tableinfo = TJ.Admin.TableInfo[this.table];
//		Done in the card config.
		TJ.Admin.TableRelatedGridPanel.superclass.initComponent.call(this);
	},
	addRecord: function(record){
		Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + ':relatedadd',
							params: {reltab: this.relation.table, relid: this.relation.id, relname: this.relation.relname, id: record._id},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									this.store.reload();
								}},
							scope: this	});

	},
	removeRecords: function(records,ids){
		Ext.Ajax.request ({ url:  TJ.LANGUAGESS +  this.tableinfo.baseurl + ':relatedrem',
							params: {reltab: this.relation.table, relid: this.relation.id, relname: this.relation.relname, ids:  ids.join(',')},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									for(var i=0; i < records.length; i++) {
										this.store.remove(records[i]);
										ids[i]=records[i].data['_id'];
									}
								}},
							scope: this	});
	}

});

Ext.reg('tjadminrecordrelated',TJ.Admin.RecordRelatedGridPanel);

TJ.Admin.RecordTaggingPanel = Ext.extend(Ext.grid.GridPanel,{
	stripeRows: true,
	border: false,
	maskDisabled: false,
	initComponent: function () {

		this.saveBtn = new Ext.Toolbar.Button({
				text: 'Save',
				disabled: true,
				iconCls: 'icon_accept',
				handler: function() {
					this.saveChanges();
				},
				scope: this
		});
		this.refreshBtn = new Ext.Toolbar.Button ({
				text: 'Refresh',
				disabled: false,
				iconCls: 'icon-refresh',
				handler: function() {
					this.getAllTags();						
				},
				scope: this
			

		});

		this.tbar = [ this.refreshBtn];
		this.bbar = [ '->',this.saveBtn];

		this.sm = new Ext.grid.CheckboxSelectionModel();
		 this.store = new Ext.data.SimpleStore({
			fields: ['_id','text','__group']
		 });
		this.columns = [	
							this.sm,
							{ header:'ID',	align:'right',sortable: true, width:40,dataIndex:'_id'},
							{ header:'Tag',sortable: true, width:80,dataIndex:'text'},
							{ header:'Group',sortable: true, width:80,dataIndex:'__group'} ];
		this.getAllTags();
		TJ.Admin.RecordTaggingPanel.superclass.initComponent.call(this);

		this.getSelectionModel().on('selectionchange',this.selChange,this);
//		this.getSelectionModel().on('selectionchange',this.saveChanges,this,{buffer:1000});
	},
	getAllTags: function() {
		TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content:getalltags', 
										callback: this.tagsCallback,refresh:true,
										scope: this});
	},
	selChange: function(){
		if(this.loading)
			return;
		console.log('change');
		this.saveBtn.setDisabled(false);

	},
	saveChanges: function(){
		if(this.loading)
			return;
		var arr=Array();
		this.getSelectionModel().each(function(i){
			arr.push(i.data._id * 1);
		});

		Ext.Ajax.request ({ url:  TJ.LANGUAGESS +  this.tableinfo.baseurl + ':updatetags',// relatedrem
							params: {id: this.record.data._id, tags:  arr.join(',')},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									console.log(res);
								}},
							scope: this	});


		this.saveBtn.setDisabled(true);

	},

	tagsCallback: function(val){
		this.store.removeAll();
		for(var i=0;i<val.length;i++){
			this.store.loadData([[val[i]._id,val[i].text,val[i].__group] || '[No Group]'],true);
		}
		this.getTags();
	},
	render: function(ct,pos){
		TJ.Admin.RecordTaggingPanel.superclass.render.call(this,ct,pos);
		this.getTags();
	},
	record: {},
	setRecord:function(record){
//		console.log('SetRecord',record);		
		this.record=record;
		this.getTags();

	},
	loading: false,
	getTags: function(){
		if(this.rendered) {

			this.setDisabled(true);
			this.loading=true;

			this.getSelectionModel().clearSelections();

			if(this.record.data) {
				Ext.Ajax.request ({url: TJ.LANGUAGESS + this.tableinfo.baseurl + ':gettags',
								params: {id: this.record.data._id},
								callback: function(options,success,response) {
									var res=TJ.Admin.ProcessJSONResponse(options,success,response);
									console.log(res);
									if(res.data){
										this.store.each(function(r){
											for(var i = 0; i < res.data.length;i++){
												if(r.data._id == res.data[i]){
													this.getSelectionModel().selectRecords([r],true);

												}

											}

											console.log('record',r.data._id);


										},this);
										this.setDisabled(false);
										this.loading=false;
									}
								},
								scope: this});
			} else {
				this.loading=false;
			}

		}

	}

});




	TJ.Admin.RecordMediaPanel = Ext.extend( TJ.comp.ObjectTreeEditor, {
		title:'Media Panel',
		initComponent: function(){

//			console.log('initialize',this);
			this.title='Media for this ' + this.tableinfo.lang.label;
			this.saveBtn= new Ext.Toolbar.Button({
				text: 'Save',
				tooltip: 'Save Changes',
				iconCls: 'icon_accept',
				handler: this.saveChanges,
//				disabled: true,
				scope: this
			});
			this.bbar=['->',this.saveBtn];
			TJ.Admin.RecordMediaPanel.superclass.initComponent.call(this);
			this.on('change', function(){
//				this.saveBtn.setDisabled(false);
			},this);
			if(this.recordid)
				this.getData(this.recordid);
		},
		getData: function(recordid){
			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + recordid + ':getextramedia',
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
											if(res.data && res.data.media)
												this.setValue(Ext.util.JSON.decode(res.data.media));
										},
										scope:this
										});
			
		},
		saveChanges: function(){
			Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + this.recordid + ':saveextramedia',
										params: {media: Ext.util.JSON.encode(this.getValue())},
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
//											this.saveBtn.setDisabled(res.success);
										},
										scope:this
										});
	
		}

	});

Ext.reg('tjadminrecordmedia',TJ.Admin.RecordMediaPanel);

TJ.Admin.RecordCommentsPanel = Ext.extend(Ext.Panel, {
	title:'Record Comments Panel',
	layout: 'border',

	initComponent: function () {

//		console.log('ini', this.record.data,this.record.data._info.comments.status);

		this.title=String.format('User comments for this {0}',this.tableinfo.lang.label);

		this.statusBtn = new Ext.CycleButton({
			showText: true,
			disabled: true,
			prependText: 'Status: ',
			itemIndex:0,
			defaults: {iconCls:'icon_table'},
			items: [	
					{ value: 'open',	text:	'Open', iconCls:'icon_page_green'},
					{ value: 'closed',	text: 'Closed', iconCls: 'icon_page_key'}
			]
		});
	
		this.daysOpen = new TJ.comp.IntegerField ({
			minValue: 0,
			maxValue: 360,
			width: 40
		});

		this.expiryTime = new Ext.Toolbar.TextItem ({
			text: ''
		});

		this.saveBtn = new Ext.Toolbar.Button({
				text: 'Save' ,
				iconCls: 'icon_accept',
				handler: this.saveChanges,
				disabled: true,
				scope: this
			});

		this.grid = new TJ.Admin.TableGridPanel({tableinfo: this.commenttableinfo, region:'center'});	
		this.grid.store.baseParams['comments_recordid']= this.recordid;
		this.grid.store.baseParams['comments_table']= this.tableinfo.table;
		
		this.items = [this.grid];

		this.tbar=['Thread Settings:',this.statusBtn,'Days Open', this.daysOpen, this.saveBtn, this.expiryTime];

		
		TJ.Admin.RecordCommentsPanel.superclass.initComponent.call(this);
		this.grid.store.baseParams['comments_recordid']= this.recordid;
		this.grid.store.baseParams['comments_table']= this.tableinfo.table;
		this.getSettings();
	},
	getSettings: function() {
		TJ.CallbackManager.Direct( { cls: 'Comments',method: 'GetCommentSettings',
								params:	{
											  recordid: this.recordid,
											  table:  this.tableinfo['class']
										},
								callback: this.getSettingsCallback,
								scope:    this });
	},
	getSettingsCallback: function(val,res,opt) {

/*
		if(val.endDate)
			this.endDate.setValue(new Date(val.endDate*1000));
		else
			this.endDate.setValue('');
		this.endDate.setDisabled(false);
*/			
		this.daysOpen.setValue(val.daysOpen);
		this.settings=val;

		this.setExpiryText();




		Ext.each(this.statusBtn.menu.items.items, function(i){
			if(val.status==i.value){
				this.statusBtn.setActiveItem(i,true);
				return false;
			}
		},this);

		this.statusBtn.setDisabled(false);

		this.statusBtn.on('change',this.change,this);
//		this.endDate.on('change',this.change,this);
		this.daysOpen.on('change',this.change,this);
	},
	setExpiryText: function () {

		var days = this.daysOpen.getValue() ;

		var pubDate = new Date(this.settings.pubDate*1000);

		var expiry = pubDate.add(Date.DAY,days * 1 +1 ).add(Date.MINUTE,-1);

		if(days  > 0) {
			this.expiryTime.setText(String.format('Published on <b>{0}</b>.  Comments close on <b>{1}</b>',
					pubDate.format('j-M-Y'), 
					expiry.format('j-M-Y g:i a')));
		} else {
			this.expiryTime.setText(String.format('Published on <b>{0}</b>.  Comments do not close automatically', pubDate.format('j-M-Y')));
		}






	},
	change: function() {
		this.setExpiryText(this.daysOpen.getValue());
		this.saveBtn.setDisabled(false);
	},
	saveChanges: function() {
		TJ.CallbackManager.Direct( {	cls:		'Comments',
										method :	'SetCommentSettings',
								params:	{
						 					  status: this.statusBtn.getActiveItem().value,
											  daysOpen: this.daysOpen.getValue(),
											  recordid: this.recordid,
											  table:  this.tableinfo['class']
										},
								callback: this.saveCallback,
								scope:    this });



	},
	saveCallback: function(val,res,opt) {

		this.saveBtn.setDisabled(true);

	}

});

Ext.reg('tjadminrecordcomments',TJ.Admin.RecordCommentsPanel);
/*
TJ.Admin.RecordCommentsReviewPanel =Ext.extend( Ext.Panel,{
	layout: border,

	initComponent: function() {
		
		this.items=[
//			region: 'center',

			
		
		
		
		];

		TJ.Admin.RecordCommentsReviewPanel.superclass.initComponent.call(this);
	}
	title: "stuff"


});
Ext.reg('tjadmincommentsreview',TJ.Admin.RecordCommentsReviewPanel);
*/


TJ.Admin.RecordQuickRelatedPanel = Ext.extend(Ext.grid.GridPanel,{
	stateId: 'TJ_Admin_RecordQuickRelatedPanel',
	title: 'Related',
	stripeRows: true,
	border: false,
	maskDisabled: false,
	initComponent: function () {

		this.saveBtn = new Ext.Toolbar.Button({
				text: 'Save',
				disabled: true,
				iconCls: 'icon_accept',
				handler: function() {
					this.saveChanges();
				},
				scope: this
		});
		this.refreshBtn = new Ext.Toolbar.Button({
				text: 'Refresh',
				disabled: true,
				iconCls: 'icon-refresh',
				handler: function() {
					this.setRecord(this.record);
				},
				scope: this
		});

		this.countBtn = new Ext.CycleButton({
			showText: true,
			prependText: 'Records: ',
			itemIndex:0,
			defaults: {iconCls:'icon_table'},
			items: [	
					{ text: '10', iconCls:'icon_table', checked:true},
					{ text: '20', iconCls:'icon_table'},
					{ text: '50', iconCls:'icon_table'}
			]
		});

		this.countBtn.on('change',function(b,i){
			this.setRecord(this.record);
		},this);

		this.tbar = [this.refreshBtn,this.countBtn];

		this.bbar = [ '->',this.saveBtn];


		this.sm = new Ext.grid.CheckboxSelectionModel({checkOnly: true,header:''});
		
		this.store = new Ext.data.GroupingStore( {
			remoteSort: false,
			groupField:'relation',
			sortInfo:{field: '_id', direction: "DESC"},
			url:  TJ.LANGUAGESS +this.tableinfo.baseurl + '-' + ':getquickrelations'			,
			reader: new Ext.data.JsonReader({
				root: 'rows',
				totalProperty: 'numrows'
				},
				[	{name:'relation'},
					{name:'_classname'},
					{name:'_id', type:'int'},
					{name:'text'},
					{name:'_related'},
					{name:'name'}
					])
			});

		this.view = new Ext.grid.GroupingView({
			startCollapsed: true,
			hideGroupedColumn: true,
			emptyText: 'No relations defined',
			enableGroupingMenu: false,
			autoFill: true,
			forceFit: true

		});



		this.columns = [	
							this.sm,
							{ header:'Relation'	,sortable: true, width:120,dataIndex:'relation'},
							{ header:'ID'		,sortable: true, width:40,dataIndex:'_id'},
							{ header:'Summary'		,sortable: true,dataIndex:'text'}



		];

	


		TJ.Admin.RecordQuickRelatedPanel.superclass.initComponent.call(this);
		this.getSelectionModel().on('selectionchange',this.selChange,this);
	},
	saveChanges: function(){
		val=Array();
		this.store.each(function(rec){
			if(this.getSelectionModel().isSelected(rec)) {
				val.push({	reltab: rec.data._classname,
							relid : rec.data._id,
							name  : rec.data.name,
							action: true
							});
				
			}
			else {

					val.push({	reltab: rec.data._classname,
								relid : rec.data._id,
								name  : rec.data.name,
								action: false
								});

			}

			



		},this);


		if(this.body)
			this.body.mask('Saving...');


		Ext.Ajax.request ({ url:  TJ.LANGUAGESS +  this.tableinfo.baseurl + '-' + this.record.data._id + ':savequickrelations',// relatedrem
							params: {actions: Ext.util.JSON.encode(val)},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									if(this.body)
										this.body.unmask();

									this.saveBtn.setDisabled(true);
									this.refreshBtn.setDisabled(true);

								}},
							scope: this	});






	},
	loadCallback: function(recs,opt,success) {

		this.store.each(function(r){	
			if(r.data._related) {
				this.getSelectionModel().selectRecords([r],true);
			}
		},this);
		this.saveBtn.setDisabled(true);
		this.refreshBtn.setDisabled(true);
		if(this.body)
			this.body.unmask();


	},
	loadRecord: null,
	record: null,
	setRecord: function(record) {

		if(this.rendered) {
			if(this.body)
				this.body.mask('Loading...');
				this.record=record;
				var counter=this.countBtn.getActiveItem();
				if(counter) {
					this.store.baseParams['limit']=counter.text;
				}
				else {
					this.store.baseParams['limit']=10;
				}
				this.store.proxy.conn.url= TJ.LANGUAGESS +this.tableinfo.baseurl + '-' + record.data._id + ':getquickrelations';
				this.store.reload({callback: this.loadCallback,scope: this});
		} else {
			this.loadRecord=record;

		}
	},

	render: function(ct,pos){
		TJ.Admin.RecordQuickRelatedPanel.superclass.render.call(this,ct,pos);
		if(this.loadRecord){
			this.setRecord(this.loadRecord);
			this.loadRecord=null;
		}


	},
	selChange: function(record) {
		this.saveBtn.setDisabled(false);
		this.refreshBtn.setDisabled(false);
	}

});

