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;
			TJ.comp.GenericPopupWindow.superclass.initComponent.call(this);
			this.saveBtn = new Ext.Button({
						text: 'Save',
						handler: this.save,
						scope: this
					});
			this.cancelBtn = new Ext.Button({ text: 'Cancel', handler: function(){ this.hide(); }, scope: this });
			this.buttons = [this.saveBtn, this.cancelBtn];

		},		
		validate: function(){
			return true;

		},


		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.fieldName)
				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:{},
	initComponent: function(){
		this.hiddenName = this.name;
        TJ.comp.GenericTriggerField.superclass.initComponent.call(this);

	},
	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){

						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.el.on("keypress", this.relay,  this);

	},
    onTriggerClick : function() {
		if(this.disabled)
			return;

		var popup= this.getPopupWindow();

		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.
		this.setValue(browse.getValue());
		if(this.propertyGrid && this.propertyGrid.selModel.selection)
			this.propertyGrid.selModel.selection.record.set('value',this.value);

		browse.hide();
	},

	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();
	},
	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 'No table selected: ';

	}

});