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();
	},

	setValue: function(v){		// String or Object supported
		if( v && typeof v == "object") {		// isobject
			this.objectValue=v;
			this.value=Ext.util.JSON.encode(v);
		} else {
			try{
				this.objectValue = Ext.util.JSON.decode(v);
			} catch(ex){
				this.objectValue =this.getNullValue();
			}
			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;
		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';

	}

});




// 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;
		}
		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.MicroformatPopupWindow,
	popupTitle  :'Edit ',


	getDisplayValue: function(){

		var disp = TJ.comp.Microformat.superclass.getDisplayValue.call(this);
		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();
					Ext.each(f.fields,function(fi) {
//						console.log(fi);
					params.push(String.format("{0}: {1}",fi.fieldLabel,this.objectValue.values[fi.name] || fi['default']));
					},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);
