Ext.namespace('TJ.comp');
 
TJ.comp.GetPopupInstance= function(cls){
	if(! cls.instance){
		cls.instance =new cls();
	}
	return cls.instance;
};


TJ.comp.GenericPopupWindow = Ext.extend(Ext.Window,{
		stateful: true,
		constrainHeader:true,				
		width: 600,
		height: 400,
		modal: true,
		layout: 'fit',
		closeAction: 'hide',
		showParams: null,
		title: 'Generic Popup Window',
		initialTitle: '',
		initComponent: function() {
			this.initialTitle=this.title;

			this.saveBtn = new Ext.Button({
						text: 'Save',
						handler: this.save,
						scope: this
					});
			this.cancelBtn = new Ext.Button({ text: 'Cancel', handler: this.hideMe, scope: this });
			this.buttons = [this.saveBtn, this.cancelBtn];
			this.onEsc=this.hideMe;
			TJ.comp.GenericPopupWindow.superclass.initComponent.call(this);
		},		
		validate: function(){
			return true;

		},

		hideMe: function(){
			if(this.showParams.callback)
				this.showParams.callback.call(this.showParams.scope,false);
			this.hide();
		},
		save: function() {
			if(! this.validate())
				return false;
			if(this.showParams.callback)
				this.showParams.callback.call(this.showParams.scope,this);
			else
				alert('callback not defined');
			return true;
		},
		show:function(obj){

			this.showParams=obj;

			if(this.showParams.field.fieldLabel || this.showParams.field.name)
				this.setTitle(this.initialTitle + ' "' + (this.showParams.field.fieldLabel || this.showParams.field.name) + '"');
			else
				this.setTitle(this.initialTitle);
			TJ.comp.GenericPopupWindow.superclass.show.call(this);
			this.setValue(obj.value);
		},
		setValue:function(value){
			alert('must override setValue');
			console.log('setvalue',value);
		},
		getValue:function(){
			return 'Must override getValue';

		}

});

// TJ.comp.GenericTriggerField
// has hidden field.
// Can generate popup 



TJ.comp.GenericTriggerField = Ext.extend(Ext.form.TriggerField,{
	width:  400,
	value: '',
	objectValue:{},
	triggerClass:'x-form-elipsis-trigger',
	initComponent: function(){
		this.hiddenName = this.name;
        TJ.comp.GenericTriggerField.superclass.initComponent.call(this);

	},
	enableKeyEvents: true,
	render: function(ct,p){
		TJ.comp.GenericTriggerField.superclass.render.call(this,ct,p);

         this.hiddenField = this.el.insertSibling({tag:'input', type:'hidden', name: this.hiddenName,
          id: (this.hiddenId||this.hiddenName)}, 'before', true);

//		 this.el.insertSibling({tag:'br'});

		 this.hiddenField.value=this.value;
          this.el.dom.removeAttribute('name');

		  this.el.dom.setAttribute('readOnly', true);

		  this.el.on("dblclick",
				function(e){
//						console.log('GetValue',this.getValue());
						if(e.shiftKey) {
						Ext.Msg.prompt(this.fieldLabel,'Enter the raw JSON value',
								function(btn,txt){
									if(btn=='ok') {
										this.setValue(txt);
									}
								},this,true,this.value);
						
							}
					  }
		  ,this);
		  this.on('keydown', function(field,e){
			  if(e.getKey()==e.DOWN)
				  this.onTriggerClick();
		  },this);
	},
    onTriggerClick : function() {
		if(this.disabled)
			return;
		this.selectText();
		var popup= this.getPopupWindow();
//		console.log('pop',this.objectValue,this.value);

		popup.show( {		value: this.objectValue,
							field: this,
							fieldName:  this.getName(),
							callback: this.callback,
							scope:    this});
	},
	callback: function(browse){
		// extra handling to support setting value within property grid.
		if(browse) {
			this.setValue(browse.getValue());
			if(this.propertyGrid && this.propertyGrid.selModel.selection)
				this.propertyGrid.selModel.selection.record.set('value',this.value);
			browse.hide();
			this.fireEvent('change',this);
		}
		this.selectText();
	},
	convertValue: function(v) {
		return v;
	},
	setValue: function(v){		// String or Object supported
		if( v && typeof v == "object") {		// isobject
			this.objectValue=v;

		} else {
			try{
				this.objectValue = Ext.util.JSON.decode(v);
			} catch(ex){

				this.objectValue =this.getNullValue();
			}

		}
		this.objectValue=this.convertValue(this.objectValue);
		this.value=Ext.util.JSON.encode(this.objectValue);

        if(this.hiddenField){
            this.hiddenField.value = this.value;
        }
		this.displayValueGetInfo();

        if(this.rendered){
            this.validate();
        }
	},
	getNullValue:function(){
		return {};
	},
	getPopupWindow: function(){
		return TJ.comp.GetPopupInstance(this.popupClass);
	},
	popupClass: TJ.comp.GenericPopupWindow,
	getValue: function(){
		return this.value;
	},
	displayValueGetInfo: function(){
		this.displayValueCallback();
	},
	displayValueCallback: function(){
		if(this.rendered) {
			this.el.dom.value=this.getDisplayValue();
			this.el.dom.setAttribute('title',this.el.dom.value);
		}
	},
	getDisplayValue: function(){
		return this.value ;
	}

});


// Table Dependant Items
//

//  class TJ.comp.TableDependantPopupWindow
//  Not likely to sub class.
//  Allows for table choosing and selecting of custom editor



TJ.comp.TableDependantPopupWindow = Ext.extend(TJ.comp.GenericPopupWindow,{
//	table: null,		// Allow choosing of table
	title: 'Table Dependant Popup',
	layout: 'fit',

	editor:null,
	initComponent: function(){


		this.tableCombo= new TJ.comp.Type();
		this.setBtn=new Ext.Toolbar.Button({
				text:'Set Table',
				iconCls: 'icon_table_go',
				disabled: true,
				handler: function(b){
					this.setTable(this.tableCombo.getValue());
					b.setDisabled(true);
				},
				scope:this
		});
		this.tbar=['Table ',this.tableCombo,this.setBtn];
		this.tableCombo.on('select',function(f){
			this.setBtn.setDisabled(false);
		},this);

		TJ.comp.TableDependantPopupWindow.superclass.initComponent.call(this);

	},
	show: function(obj){
		this.initialTitle=obj.field.popupTitle;
		TJ.comp.TableDependantPopupWindow.superclass.show.call(this,obj);
	},
	setTable: function (table){
		TJ.Admin.ClearPanel(this);
		this.saveBtn.setDisabled(true);

		if(table===null || table==='')
			return;
		TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + table + ':gettableinfo2', 
														callback: function(val){
															this.tableinfo=val;
															this.tableChanged();
														},
									scope: this});

	},
	initValue: null,
	tableChanged: function(){
		TJ.Admin.ClearPanel(this);
		this.editor=new this.showParams.field.popupEditor({tableinfo: this.tableinfo, value: this.initValue});
		this.items.add(this.editor);
		this.initValue=this.showParams.field.getNullValue();
		this.doLayout();
		this.saveBtn.setDisabled(false);
	},

	setValue: function(value){
		this.initValue=value;
		if(this.showParams.field.table){
			this.tableCombo.setValue(this.showParams.field.table);
			this.tableCombo.setDisabled(true);
			this.setTable(this.showParams.field.table);
		}
		else {
			this.tableCombo.setDisabled(false);
			this.tableCombo.setValue(value.table);
			this.setTable(this.tableCombo.getValue());
		}
	},
	getValue: function(){
		value= this.editor.getValue();
		if(this.showParams.field.table===null)
			value.table=this.tableinfo['class'];
		console.log('getvalue',value);
		return value;
	}


});

// TJ.comp.TableDependantEditor
// Subclass this and list in TableDependantPopup
// Override getValue.  Also allow for setting value in config file


TJ.comp.TableDependantEditor = Ext.extend(Ext.Panel,{
	initComponent: function(){
			this.title=this.title || this.tableinfo.lang.plural ;
			this.html="Create Editor subclassed on TableDependantEditor";

			TJ.comp.TableDependantEditor.superclass.initComponent.call(this);
	},
	getValue: function(){
		return {value:'Not Defined'};


	}

});

// TJ.comp.TableDependantTriggerField
// Fields to Override
// popupEditor
// getDisplayValue
//		both objectValue and this.tableinfo SHOULD be set.


TJ.comp.TableDependantTriggerField = Ext.extend(TJ.comp.GenericTriggerField,{
	table: null,		// set this to a table class to restrict types.
	popupClass	:TJ.comp.TableDependantPopupWindow,
	popupTitle  :'Edit ',

	popupEditor	:TJ.comp.TableDependantEditor,		// override this with custom Editor.  
													// will initialize with value in initComponent.	
													// has getValue
													// subclass of Panel.

	
	getNullValue: function(){
		if(this.table){
			return {};
		}
		return { table: null};
	},

	displayValueGetInfo: function(){
		// fixed table
		if(this.table){
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + this.table + ':gettableinfo2', 
										callback: function(val){this.tableinfo=val; this.displayValueCallback();},
										scope: this});


		}else	// generic table
		if(this.objectValue.table) {
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + this.objectValue.table + ':gettableinfo2', 
										callback: function(val){this.tableinfo=val; this.displayValueCallback();},
										scope: this});

		}
		else
			this.displayValueCallback();
	}
	,
	getDisplayValue: function(){

		if(this.tableinfo && this.tableinfo.lang){
			return String.format('{0}: ',this.tableinfo.lang.plural);
		}
		return 'Please select table';

	}

});




/* New Table Trigger Field */

TJ.comp.TablePopupWindow = Ext.extend(TJ.comp.GenericPopupWindow,{
	show: function(obj){
		this.initialTitle=obj.field.popupTitle;
		this.tableinfo=obj.field.tableinfo;
		console.log('tablepopupwindow',obj.field.tableinfo);

		TJ.comp.TablePopupWindow.superclass.show.call(this,obj);
	}

});


TJ.comp.TableTriggerField = Ext.extend(TJ.comp.GenericTriggerField,{
				
	popupClass	:TJ.comp.TablePopupWindow,
	popupTitle  :'Edit ',
	disabled: true,
	generic: false,
	tableField:'table',
	tableinfo: null,
	setEmpty: function(status) {
		if(status)
			this.el.addClass('x-form-empty-field');
		else
			this.el.removeClass('x-form-empty-field');

	},

	render: function(ct,pos){

			TJ.comp.TableTriggerField.superclass.render.call(this,ct,pos);
			if(this.generic) {
				this.setTable();
			}
			else if (this.table) { 
//				console.log('autotable');
				this.setTable(this.table);

			} else {
				if(this.propertyGrid)
					this.propertyGrid.on('afteredit',this.setTable,this);
				if(this.formValues && this.formValues[this.tableField]){
					this.setTable(this.formValues[this.tableField]);
				}
			} 
	
		},
	siblingChange: function(f){
//		console.log('siblingchange',f);
		if(f.name == this.tableField)
			this.setTable(f.getValue());
	},
	setTable: function(table){
//		var table;

		if(this.generic) {
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + 'generic' + ':gettableinfo2', 
														callback: function(val){
															this.tableChanged(val);
													},
								scope: this});


		}

		if(! table) {
			if(this.propertyGrid)
				table=this.propertyGrid.getSource()[this.tableField];
	
			if(this.form){
				table=this.form.getValues()[this.tableField];
			}
		}
		

		if(!table)
			return;
		this.setDisabled(true);
		
		if(table===null || table==='')
			return;

		TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + table + ':gettableinfo2', 
														callback: function(val){
															this.tableChanged(val);
													},
								scope: this});
	},
	tableChanged: function(val){
		this.tableinfo=val;
		console.log('val',val);
		if(val) {
			this.setDisabled(false);
			this.displayValueGetInfo();
//			this.setValue(this.getNullValue());		// do not reset the vvalue.
		}

	},



	
	getNullValue: function(){
		return {};
	},

	displayValueGetInfo: function(){
		this.displayValueCallback();
		return;
			// this is possible as the data is always in the system.
		// fixed table
		if(this.table){
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + this.table + ':gettableinfo2', 
										callback: function(val){this.tableinfo=val; this.displayValueCallback();},
										scope: this});


		}else	// generic table
		if(this.objectValue.table) {
			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + this.objectValue.table + ':gettableinfo2', 
										callback: function(val){this.tableinfo=val; this.displayValueCallback();},
										scope: this});

		}
		else
			this.displayValueCallback();
	}
	,
	getDisplayValue: function(){
		if(this.tableinfo && this.tableinfo.lang){
			return this.tableinfo.lang.plural;
		}
		return 'Please select table';

	}

});

TJ.comp.MicroformatPopupWindow2= Ext.extend(TJ.comp.TablePopupWindow,{
	stateId: 'TJ_comp_MicroformatPopupWindow',
	layout: 'border',
	microformat: null,
	initialValues: null,
	ready:false,
	setValue : function(val) {
		console.log('setvalue',this.tableinfo);
		this.ready=true;
		this.tp.getLoader().baseParams.table=this.tableinfo['class'];
		this.tp.getLoader().load(this.tp.getRootNode(), function() {
			if(val.name) {
				this.tp.selectPath('/root/' + val.microformat + '/' + val.microformat + ':' + val.name)
			} else if(val.microformat) {
				this.initialValues=val.values;
				this.tp.selectPath('/root/' + val.microformat)
			}
			else
				this.tp.selectPath('/root/summary');
		},this);

	},
	initComponent: function() {

		this.templateName = new Ext.form.TextField({width: 100,enableKeyEvents:true,  maxLength: 16,	maskRe: /[_a-z0-9]/i, disabled:true});
		this.saveNamed = 	new Ext.Toolbar.Button({iconCls: 'icon_drive',text:'Save',handler: this.saveTemplate,scope: this, disabled:true});
		this.deleteNamed = 	new Ext.Toolbar.Button({iconCls: 'icon_drive_delete',text:'Delete',handler: this.deleteTemplate,scope: this, disabled:true});

		this.templateName.on('keyup',function(f){ this.saveNamed.setDisabled(!f.isValid() || (f.getValue().length===0));},this);

		this.main=new Ext.Panel({
			title: 'Parameters',
			region: 'center',
			layout: 'card',
			border: false,
			tbar: [ 'Named ', this.templateName,this.saveNamed,'-',this.deleteNamed]
		});

		this.tp= new Ext.tree.TreePanel({
			title: 'Microformats',
			border: false,
			autoScroll: true,
			enableDD: false,
			containerScroll: true,
			rootVisible: false,
			region: 'west',
			split: true,
			minSize: 120,
			singleExpand: true,
			width: 160,
			root : new Ext.tree.AsyncTreeNode({
					id: 'root',
					text: this.rootTitle || 'Home'
				}),
			loader: new Ext.tree.TreeLoader({
					dataUrl: TJ.LANGUAGESS + 'admin/pagemanager:getmicroformats',
					listeners: {
						beforeload:   { fn: function() {
											if(! this.ready)
												return false;
										},
										scope: this
						}
						}
				})
		});
		this.tp.getSelectionModel().on('selectionchange',this.nodeSelect,this);

		this.items=[this.main,this.tp];
		TJ.comp.MicroformatPopupWindow2.superclass.initComponent.call(this);

	},

	nodeSelect: function(sm,node) {
		if(node && node.attributes) {
			this.createForm(node);
			this.templateName.setDisabled(false);



			if(node.attributes.leaf) {
				this.templateName.setValue(node.attributes.text);
				this.templateName.setDisabled(true);
				this.deleteNamed.setDisabled(false);
				this.saveNamed.setDisabled(false);

			} else {
				this.templateName.setDisabled(false);
				this.templateName.setValue('');
				this.saveNamed.setDisabled(true);
				this.deleteNamed.setDisabled(true);
				if(this.initialValues) {
					this.form.getForm().setValues(this.initialValues);
					this.initialValues=null;
				}
			}
		} else {
			// we should clear the panel here.  
				// clear me.

		}
	},
	forms: {},
	createForm: function(node,values) {
		console.log('create',node, this.initialValues);
		if (! this.forms[node.attributes.mf.code])	{
			this.forms[node.attributes.mf.code]=
				this.main.add(new Ext.form.FormPanel({
					frame: true,
					autoScroll: true,
					labelAlign: 'right',
					border: false,
					layout: 'tjadminform',
					monitorValid: true,
					defaults: { anchor: '-40',
								msgTarget: 'side',
								listeners: { change: { fn:function(f){  
											if(tinyMCE) tinyMCE.triggerSave();
											this.fieldChange(f);
											},scope:this}
								}
								},
					labelWidth: 160,
					items: node.attributes.mf.fields
				}));
			this.forms[node.attributes.mf.code].on('clientvalidation',this.validate,this);
		}

		this.form = this.forms[node.attributes.mf.code];


		if(node.attributes.values) {
			this.form.getForm().setValues(Ext.decode(node.attributes.values));
		} 
		
		
		this.main.layout.setActiveItem(this.form);
		if(node.attributes.leaf)
			this.main.setTitle(String.format('Settings: {0} [{1}]',node.attributes.mf.text,node.attributes.text));
		else
			this.main.setTitle(String.format('Settings: {0}',node.attributes.mf.text));


		this.microformat=node.attributes.mf.code;

	},
	getFormValues: function() {
		var values = {};
		if(this.form)
			this.form.items.each(function(i){
				values[i.getName()]=i.getValue();
			});
		return values;
		// We need to construct all the values because the form getValues field doesn't.
//		console.log('values',this.form.getForm().getValues(), values);
		
	},
	getValue:function(){
		var node = this.tp.getSelectionModel().getSelectedNode();

		if(node.isLeaf()) {
			return {	microformat:this.microformat,
						table: node.attributes.mf.table,
						name: node.attributes.text}; ///this.form.getForm().getValues()};
		}

		return {	microformat:this.microformat,
					values: this.getFormValues()   }; ///this.form.getForm().getValues()};

		},
	validate: function(){
			this.saveBtn.setDisabled(! this.form.getForm().isValid());
			return this.form.getForm().isValid();
	},
	fieldChange: function(f){
		this.form.items.each(function(i){
			if(i.siblingChange)
				i.siblingChange(f);
			if(i.disableField == f.name){
				i.setDisabled(! f.getValue());
			}
		});
	},
	deleteTemplate: function() {
		var node = this.tp.getSelectionModel().getSelectedNode();
		TJ.CallbackManager.Execute({
		url: TJ.LANGUAGESS + 'admin/pagemanager:deletemicroformat',
		params: { name: this.templateName.getValue(),
				  microformat: this.microformat,
				  table: node.attributes.mf.table
		},
		callback: this.delCB,
		scope:this});
	},
	delCB: function() {
		var node = this.tp.getSelectionModel().getSelectedNode();
		node.parentNode.select();
		node.remove(true);

	},
	saveTemplate: function() {
		var node = this.tp.getSelectionModel().getSelectedNode();
		TJ.CallbackManager.Execute({
		url: TJ.LANGUAGESS + 'admin/pagemanager:savemicroformat',
		params: { name: this.templateName.getValue(),
				  microformat: this.microformat,
				  table: node.attributes.mf.table,
				  values: Ext.encode(this.getFormValues())
		},
		callback: this.saveCB,
		scope:this});
	},
	saveCB: function() {
//		var val=this.templateName.getValue();
		var node = this.tp.getSelectionModel().getSelectedNode();
		var newpath ='/root/' + this.microformat + '/' + this.microformat + ':'+ this.templateName.getValue();
		if(node.isLeaf()){
			node.attributes.values = Ext.encode(this.getFormValues());		// save only.
		} else {
			node.parentNode.reload( function() {
				this.tp.selectPath(newpath);
			} , this);

		}
	}

});



// Microformat implementation!!!!
TJ.comp.MicroformatPopupWindow = Ext.extend(TJ.comp.TablePopupWindow,{
	stateId: 'TJ_comp_MicroformatPopupWindow',
	layout: 'fit',
	microformat: null,
	values: {},
	setValue: function(val) {

		// clear existing Panel
		if(this.main){
			this.remove(this.main);
			this.main.destroy();
		}

		// Add microformat buttons
		var buttons=[];
		var selected=-1;
		for (i=0;i<this.tableinfo.microformats.length ;i++ )
		{
//			console.log('mf',this.tableinfo.microformats[i]);
			buttons.push(
				new Ext.Toolbar.Button ({
						text: 			this.tableinfo.microformats[i].text ,
						microformat :	this.tableinfo.microformats[i],
						handler:	this.selectFormat,
						pressed: val.microformat==this.tableinfo.microformats[i].code,		// set the pressed button if set.
						toggleGroup: 'formats',
						iconCls: 'icon_page_green',
						scope: this
				}));
				if(val.microformat==this.tableinfo.microformats[i].code)
					selected = i;
				buttons.push('|');
				buttons.push( new Ext.CycleButton ( {
					showText: true,
					prependText: this.tableinfo.microformats[i].text +': ',
					microformat: this.tableinfo.microformats[i],
					defaults: {iconCls: 'icon_page_green'},
					items: [ { value: 'custom', text: 'Custom'},
							 { value: 'saved1', text: 'saved1'},
						     { value: 'saved2', text: 'saved2'}]


				}));



		}
		this.setTitle(this.title + ' for ' + this.tableinfo.lang.plural);
		// create panel
		this.main= new Ext.Panel ({
			frame: false,
			border: false,
			layout: 'card',
			tbar: buttons
		});

		this.add(this.main);
		this.doLayout();
		if(selected >=0) {
			this.selectFormat(buttons[selected]);			// this will create the form.
			this.form.getForm().setValues(val.values);		// this will add the values as nescessary.
		}
		else if(buttons[0]) {
			buttons[0].toggle(true);
			this.selectFormat(buttons[0]);					// default to the first format.
		}


	},
	fieldChange: function(f){
		this.form.items.each(function(i){
			if(i.siblingChange)
				i.siblingChange(f);
			if(i.disableField == f.name){
				i.setDisabled(! f.getValue());
			}
		});


	},
	selectFormat: function(b) {
		console.log('select format', b);
		this.microformat=b.microformat.code;
		if(! b.form) {
			b.form = this.main.add(new Ext.form.FormPanel({
				frame: true,
				autoScroll: true,
				labelAlign: 'right',
				border: false,
				layout: 'tjadminform',
				monitorValid: true,
				defaults: { anchor: '-40',
				            msgTarget: 'side',
							listeners: { change: { fn:function(f){  
										if(tinyMCE) tinyMCE.triggerSave();
										this.fieldChange(f);
										},scope:this}
							}
							},
				labelWidth: 160,
				items: b.microformat.fields
			}));
			b.form.on('clientvalidation',this.validate,this);
		}

		this.main.layout.setActiveItem(this.form=b.form);

	},
	getValue:function(){


		var values = {};
		this.form.items.each(function(i){
			values[i.getName()]=i.getValue();
		});
		// We need to construct all the values because the form getValues field doesn't.
//		console.log('values',this.form.getForm().getValues(), values);



			return {	microformat:this.microformat,
						values: values    }; ///this.form.getForm().getValues()};

		},
		validate: function(){
			this.saveBtn.setDisabled(! this.form.getForm().isValid());
			return this.form.getForm().isValid();
		}
});

TJ.comp.Microformat = Ext.extend(TJ.comp.TableTriggerField,{
	popupClass	:TJ.comp.MicroformatPopupWindow2,
	popupTitle  :'Edit ',


	getDisplayValue: function(){

		var disp = TJ.comp.Microformat.superclass.getDisplayValue.call(this);
		console.log(this.objectValue);
		if(this.objectValue.microformat) {
			disp='';
			if(this.tableinfo)
			Ext.each(this.tableinfo.microformats,function(f) {
//				console.log('s',f);
				if(f.code == this.objectValue.microformat){
					disp=f.text;
					var params=Array();
					if(this.objectValue.name) {
						disp = String.format("{0} [{1}]",disp,this.objectValue.name);
					} else {
						Ext.each(f.fields,function(fi) {
	//						console.log(fi);
						params.push(String.format("{0}: {1}",fi.fieldLabel,this.objectValue.values[fi.name] ));
						},this);

						disp = String.format("{0}. {1}",disp,params.join(', '));
					}
	
					return false;
				}

			},this);

			return disp || this.objectValue.microformat;



		}

		if(this.tableinfo && this.tableinfo.lang){

			return String.format('Select {0} microformat...',this.tableinfo.lang.plural);
		}
		return 'Please select table';
	}
});


Ext.reg('tjmicroformat',TJ.comp.Microformat);

TJ.comp.MicroformatGeneric = Ext.extend(TJ.comp.Microformat,{
	tableField:'----nofield----',
	generic: true
});

Ext.reg('tjmicroformatgeneric',TJ.comp.MicroformatGeneric);

/// User or Group


TJ.comp.UserOrGroupPopup = Ext.extend(TJ.comp.GenericPopupWindow,{
	width: 400,
	height: 140,
	title: 'Select a Username or Usergroup',
	setValue: function(val) {

		this.form.user.reset();
		this.form.usergroup.reset();
		if(val <0) {
			this.form.usergroup.setValue(-val);
		} 
		else if (val>0)
		{
			this.form.user.setValue(val);
		}
	},
	initComponent: function() {
		this.items =  this.form = new TJ.Admin.Form ({
					labelWidth: 80,
					defaults: {anchor: '-20',selectOnFocus: true, msgTarget: 'side' },
					buttons:  [],
					items: 
						[ 
										{ xtype: 'tjuser',
										name: 'user',
										ref:'user',
										listeners: {
											change: {  fn: function(f) {
												if(f.getValue() >0) {
													f.ownerCt.getForm().findField('usergroup').reset();
												}
											},
											scope: this
										}},
										fieldLabel: 'Username' },
									  { xtype: 'tjusergroup',
										name: 'usergroup',
										ref:'usergroup',
										listeners: {
											change: {  fn: function(f) {
												if(f.getValue() >0)
													f.ownerCt.getForm().findField('user').reset();
											},
											scope: this
										}},
										fieldLabel: 'Usergroup' }					
						]
		});
		TJ.comp.UserOrGroupPopup.superclass.initComponent.call(this);
	},
	getValue: function() {
		if(this.form.user.getValue())
			return  this.form.user.getValue();
		if(this.form.usergroup.getValue())
			return - this.form.usergroup.getValue();
		return 0;
	}


});



TJ.comp.UserOrGroup = Ext.extend(TJ.comp.GenericTriggerField,{

	popupClass: TJ.comp.UserOrGroupPopup,

	getNullValue: function(){
		return 0;


	},
	displayValueGetInfo: function(){
		if(this.value >0) {
			var options = {
							url: '/en/form-' + ':fieldobject',
							scope: this,
							params: {id: this.value ,table: 'cl_user_account_table'},
							callback:  this.displayValueCallback
			};
			Ext.Ajax.request(options);
		} else
		if(this.value < 0) {
			var options = {
							url: '/en/form-' + ':fieldobject',
							scope: this,
							params: {id: - this.value,table: 'cl_user_group_table'},
							callback:  this.displayValueCallback
			};
			Ext.Ajax.request(options);
		}
		else
			this.displayValueCallback();
	},
	record: null,
	displayValueCallback: function(info,success,res) {
		if(success) {
			var record = Ext.util.JSON.decode(res.responseText);
			console.log('a',record, record.rows);
			this.record = record.rows[0];
			console.log(this.record);
		} else
		this.record=null;
		TJ.comp.UserOrGroup.superclass.displayValueCallback.call(this);
	},


	getDisplayValue: function(){
		console.log('value',this.value,this.objectValue);
		if(this.value > 0) {
			if(this.record)
				return String.format('User: {0} ({1})',this.record._summary, this.record._id);
			else
				return String.format('User: {0} Not found',this.value);
		} else
		if(this.value < 0) {
			if(this.record)
				return String.format('Usergroup: {0} ({1})',this.record._summary, this.record._id);
			else
				return String.format('Usergroup: {0} Not found',this.value);

		}
		return 'Please select a user or group';
	}
});


Ext.reg('tjuserorgroup',TJ.comp.UserOrGroup);

