TJ.comp.ObjectTreeEditor = Ext.extend(Ext.Panel,{
	layout: 'border',
	frame: false,
	border: false,
	nodeTypes : {},  // defined in prototype code below.
	nodes: [ 'file','image_link','image_directory','video'],

	initComponent: function(){

		// this is a one off for this Component.  Should likely put into prototype.

		if(! TJ.comp.ObjectTreeEditor.prototype.multiDone) {
			for(var i in this.nodeTypes){
					this.nodeTypes[i].fields=TJ.Admin.MakeFieldListMultilingual(this.nodeTypes[i].fields);
			}
			TJ.comp.ObjectTreeEditor.prototype.multiDone=true;
		}

		this.menu =  new Ext.menu.Menu({items: Array(),defaults:{handler:function(item) {
			this.addNode(item.key);
		}
		,scope:this}});

		this.addBtn = new Ext.Toolbar.Button({
			text: 'Add Item',
			iconCls: 'icon_add',
			menu: this.menu
		});

		this.copyBtn = new Ext.Toolbar.Button({
			text: 'Copy',
			iconCls: 'icon_add',
			disabled:true,
			handler: function(){
				var node=this.tp.getSelectionModel().getSelectedNode();
				if(node)
					this.addNode(node.attributes.key,node.attributes.values);

			},
			scope: this


		});

		this.delBtn = new Ext.Toolbar.Button({
			text: 'Delete',
			iconCls: 'icon_delete',
			disabled:true,
			handler: function(){
				this.tp.getSelectionModel().getSelectedNode().remove(true);
				this.fireEvent('change',this);
			},
			scope: this

		});

		this.tp = new Ext.tree.TreePanel({
			region: 'west',
			width:  240,
			split:  true,
			frame: false,
			border: false,
			tbar: [this.addBtn,this.copyBtn,this.delBtn],
			autoScroll: true,
			enableDD: true,
			containerScroll: true,
			root: new Ext.tree.TreeNode({
				expanded: true
			}),
			listeners: { dragdrop: { fn: function(tp,tn,dd,e) {
										tp.getSelectionModel().select(tn);


										},
									scope: this}},
			rootVisible: false
		});


		this.te = new Ext.tree.TreeEditor(this.tp,{});

		this.te.on ('complete',function(te,value) {
			this.fp.setTitle( String.format('{0}: {1}',te.editNode.attributes.keyText, value));
		},this);
		this.tp.getSelectionModel().on('selectionchange',function(sm,node){
			this.delBtn.setDisabled(node===null);
			this.copyBtn.setDisabled(node===null);
			this.setForm(node);
		},this);

		this.fp = new Ext.Panel({
				region: 'center',
				layout: 'fit',
				title: 'Select item',
				iconCls:  'icon_page_white',
				frame: false,
				border: false
		});

		this.items = [   this.tp,
						this.fp];
		TJ.comp.ObjectTreeEditor.superclass.initComponent.call(this);
		this.setupMenu();
	},
	setupMenu: function(nodes){
		nodes= nodes || this.nodes;
		this.menu.removeAll(true);

		for (var i =0; i< nodes.length; i++){
				if(this.nodeTypes[nodes[i]]) {
					this.nodeTypes[nodes[i]].index=0;
					this.menu.add({	iconCls		: this.nodeTypes[nodes[i]].iconCls,
										text	: this.nodeTypes[nodes[i]].text,
										key		: nodes[i]
					});
				} else {
					alert("Node not defined exist: " + nodes[i]);
				}
		}
	},
	nodeIndex:{},
	addNode: function(key,values){

		var node=this.getNodeTypeFromKey(key);
		this.nodeIndex[key] = (this.nodeIndex[key] || 0) + 1;

		this.tp.getRootNode().appendChild( {	key: key,
												text: node.text + ' ' + this.nodeIndex[key],
												keyText: node.text,
												fields: node.fields,
												iconCls:node.iconCls,
												values: TJ.clone(values) || {},
												leaf: true}).select();
		this.fireEvent('change',this);


	},
	getNodeTypeFromKey: function(key){
		return TJ.clone(this.nodeTypes[key]);
	},

	setForm: function(node){
//		console.log('setform ' , node.attributes);

		TJ.Admin.ClearPanel(this.fp);
		if(node) {
			this.fp.setTitle( String.format('{0}: {1}',node.attributes.keyText, node.attributes.text),node.attributes.iconCls);
			if(this.form)
				this.form.destroy();

			var form = 	new Ext.FormPanel ({
				frame: true,
				border: false,
				autoScroll: true,
				plugins: [new TJ.Admin.FormPlugin()] ,
				defaults: { 	anchor:'-35',
					            msgTarget: 'side',
								node: node,
					listeners: { change: { fn:function(f){  
								if(tinyMCE) tinyMCE.triggerSave();
								f.node.attributes.values[f.getName()]=f.getValue();
								this.fireEvent('change',this);
					},scope:this}}},
				items: node.attributes.fields,
				targetNode:node
				});
			this.fp.items.add(form);

			this.fp.doLayout();
			form.getForm().setValues(node.attributes.values);
		}
		else {
			this.fp.setTitle('Select item','icon_page_white');
		}
	},
	setValue: function(value){
		console.log(value);
		while(this.tp.getRootNode().lastChild) {
			this.tp.getRootNode().removeChild(this.tp.getRootNode().lastChild);
		}
		this.setForm();
		var val;
		while(val = value.shift()){
			node=this.getNodeTypeFromKey(val.key);
			if(node) {
				this.nodeIndex[val.key] = (this.nodeIndex[val.key] || 0) + 1;
				this.tp.getRootNode().appendChild (	{	key: val.key,
														text: val.text,
														keyText: node.text,
														fields: node.fields,
														iconCls: node.iconCls,
														values: val.values,
														leaf:true});
			}
		}
	},
	getValue: function(){
		ret=Array();
		this.tp.getRootNode().eachChild(function(node){
			ret.push(this.getValueFromNode(node));
		},this);
		return ret;
	},

	getValueFromNode: function(node){
		return {	key:	node.attributes.key,
					text:   node.attributes.text,
					values:	node.attributes.values
				};



	}


});




TJ.comp.ObjectTreePopup = Ext.extend(TJ.comp.GenericPopupWindow,{
	title: 'List Selector',
	initComponent: function(){
		this.editor = new TJ.comp.ObjectTreeEditor();
		this.items = this.editor;
		TJ.comp.ObjectTreePopup.superclass.initComponent.call(this);
	},
	show: function(obj){
		this.editor.setupMenu(obj.field.nodes);

		TJ.comp.ObjectTreePopup.superclass.show.call(this,obj);
	},
	setValue: function(v){
		console.log('value',v);
		this.editor.setValue(v);
	},
	getValue: function(){
		return this.editor.getValue();
	}
});



TJ.comp.ObjectTree = Ext.extend(TJ.comp.GenericTriggerField, {
	width: 400,
	popupClass:TJ.comp.ObjectTreePopup,
	getNullValue: function(){
		return [];
	},
	nodes: [ 'video','image_link'],
	getDisplayValue: function(){
	var ret=[String.format('{0} item(s)', this.objectValue.length)];
	Ext.each(this.objectValue,function(f){
		ret.push(f.text);

	});
	console.log(this.objectValue,ret);

		return ret.join(', ');//String.format('{0} item(s) {1}', this.objectValue.length,ret.join(', '));
	}
});

Ext.reg('tjobjecttree',TJ.comp.ObjectTree);

TJ.comp.RSSRecords = Ext.extend(TJ.comp.ObjectTree, {
	nodes: ['recordSource']
});

Ext.reg('tjrssrecords',TJ.comp.RSSRecords);


// Field Definitions

//Ext.namespace('TJ.fields');

TJ.ListFields = {	
					directory:  
							{ fieldLabel:	'Directory',
							  name:			'directory',
							  xtype:		'tjdirectory',
							  multi:		false,
							  allowBlank:	false,
							  desc:			'Please select the directory'
							},
					image:  
							{ fieldLabel:	'Image',
							  name:			'image',
							  xtype:		'tjfile',
							  multi:		true,
							  allowBlank:	false
							},
					caption:
							{ fieldLabel:	'Caption',
							  name:			'caption',
							  xtype:		'tjtext',
							  multi:		true
							},
					credit:
							{ fieldLabel:	'Credit',
							  name:			'credit',
							  xtype:		'tjtext',
							  multi:		true
							},
					thumbnail:  
							{ fieldLabel:	'Thumbnail',
							  name:			'thumbnail',
							  xtype:		'tjfile',
							  multi:		true
							},
					link:  
							{ fieldLabel:	'Link',
							  name:			'link',
							  xtype:		'tjtext',
							  multi:		true
							},
					target:  
							{ fieldLabel:	'Target',
							  name:			'target',
							  xtype:		'tjselect',
							  store:		[['_self','Same (_self)'],['_blank','New (_blank)']],
							  value:		'_self'
							},
					html:  
							{ fieldLabel:	'HTML',
							  name:			'html',
							  multi:		true,
							  xtype:		'tjhtmlpopup'
							},
					file:  
							{ fieldLabel:	'File',
							  name:			'filename',
							  xtype:		'tjfile',
							  multi:		true
							},
					title:  
							{ fieldLabel:	'Title',
							  name:			'title',
							  xtype:		'tjtext',
							  multi:		true
							},
					summary:  
							{ fieldLabel:	'Summary',
							  name:			'summary',
							  xtype:		'tjtext',
							  multi:		true
							},
					table:  
							{ fieldLabel:	'Table',
							  name:			'table',
							  xtype:		'tjtype'
							},
				    recordfilter: {
								fieldLabel: 'Filters',
								name:		'filters',
								xtype:		'tjrecordfilter'

					}
};

TJ.comp.ObjectTreeEditor.prototype.multiDone=false;


TJ.comp.ObjectTreeEditor.prototype.nodeTypes.image_thumbnail_link =
									{ iconCls: 'icon_image_link', text: 'Image (thumbnail, link)',
									fields: [	
										TJ.ListFields.image,
										TJ.ListFields.thumbnail,
										TJ.ListFields.link,
										TJ.ListFields.target,
										TJ.ListFields.title,
										TJ.ListFields.caption
										]
									};

TJ.comp.ObjectTreeEditor.prototype.nodeTypes.image_autothumbnail_link =
									{ iconCls: 'icon_image_link', text: 'Image (auto thumbnail, link)',
									fields: [	
										TJ.ListFields.image,
										TJ.ListFields.link,
										TJ.ListFields.target,
										TJ.ListFields.title,
										TJ.ListFields.caption
										]
									};

TJ.comp.ObjectTreeEditor.prototype.nodeTypes.html_thumbnail =
									{ iconCls: 'icon_html', text: 'HTML (thumbnail)',
									fields: [	
										TJ.ListFields.html,
										TJ.ListFields.thumbnail
										]
									};


TJ.comp.ObjectTreeEditor.prototype.nodeTypes.image_link = 
									{ iconCls: 'icon_image_link', text: 'Image with link',
									fields: [	TJ.ListFields.image,
//												TJ.ListFields.caption,
//												TJ.ListFields.credit,
												TJ.ListFields.link,
												TJ.ListFields.target
											]
									};


TJ.comp.ObjectTreeEditor.prototype.nodeTypes.image_directory = 
									{ iconCls: 'icon_image', text: 'Image Gallery from directory',
									fields: [	TJ.ListFields.directory,
												{ fieldLabel:	'Recursive',
												  name:			'recurse',
												  xtype:		'tjcheckbox',
												  desc:			'Check to recurse into this directory'
												},
												{ fieldLabel:	'Autocaption',
												  name:			'autocaption',
												  xtype:		'tjcheckbox',
												  desc:			'Check to display an automatic caption'
												}
											]
									};

TJ.comp.ObjectTreeEditor.prototype.nodeTypes.video = 
									{ iconCls: 'icon_monitor', text: 'Video Clip',
									fields: [	{ fieldLabel:	'Source',
												  name:			'source',
												  xtype:		'tjselect',
												  store:		['YouTube'],
												  desc:			'Select the source of the video'
												},
												{ fieldLabel:	'Video ID',
												  name:			'videoid',
												  xtype:		'tjtext',
												  desc:			'Enter the code for the video.<BR>For YouTube it\'s the code after the /v/ in the You Tube url for the video.'
												},
												TJ.ListFields.title,
												TJ.ListFields.summary

											]
									};


TJ.comp.ObjectTreeEditor.prototype.nodeTypes.file = 
									{ iconCls: 'icon_report', text: 'File',
									fields: [	TJ.ListFields.file,
												TJ.ListFields.target,
												TJ.ListFields.title,
												TJ.ListFields.summary
											]
									};

TJ.comp.ObjectTreeEditor.prototype.nodeTypes.recordSource = 
									{ iconCls: 'icon_table_lightning', text: 'Record Source',
									fields: [	TJ.ListFields.table,
												TJ.ListFields.recordfilter
											]
									};


