// Thought Junction Javascript Startup Engine.
// TJ Admin javascript functions


// Administrative Help

	Ext.namespace('TJ.Admin');

// Admin startup


TJ.Admin.HomePanel = Ext.extend(Ext.TabPanel,{
		activeTab: 0,
		border: false,
		initComponent: function(){
			this.items=	[	{	title: 'Altius',
								html: '<BR><BR><table width="100%"><tr><TD align=center style="color: #929596; font-family:arial,tahoma,helvetica,sans-serif;"><A HREF="http://www.altiussoftware.com" target=_blank><IMG SRC="/lib/external/altius/logo_195x45.png" WIDTH="195" HEIGHT="45" BORDER="0" ALT=""></A><BR><BR><A HREF="http://www.altiussoftware.com" target=_blank>Altius Software</A><br/>Powering Online Experiences</TD></tr></TABLE>'
							},{	
								title: 'Content Summary',
								autoScroll: true,
								autoLoad: {url: '/'+TJ.LANGUAGE +'/admin/home:summary'}
							}
		];
		TJ.Admin.HomePanel.superclass.initComponent.call(this);
		}
});





// 
	TJ.Admin.LoadMainTabFromNode=function(node){
//		console.log('id' ,node.id);
		var tab = TJ.Admin.MainTabPanel.getComponent(node.id);
		if(tab) {
				TJ.Admin.MainTabPanel.setActiveTab(tab);
		} else
		if(node.attributes.table){


		tab = TJ.Admin.MainTabPanel.add({
			title: node.text,
			id: node.id,
			border: false,
			layout: 'fit',
			iconCls: node.attributes.iconCls,
			autoScroll: true,
			closable: true
//								items: tp
		}).show();		
		tab.body.mask('Loading...','x-mask-loading');

			TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/apps/content-' + node.attributes.table + ':gettableinfo2', 
										callback: function(val){ 

							tab.body.unmask();
							var tp = new TJ.Admin.TableManagerTabPanel({
									parentFilterID: node.attributes.parentid,
									tableinfo: val
								});
							tab.add(tp);
							
							tab.doLayout();
					},scope: this});


		}
		else {
			if(node.attributes.nopage) {
				if(! node.leaf){
					node.expand();
				}
				return;
			}
			if(node.attributes.cardconfig){
				console.log(node.attributes.cardconfig);
				TJ.Admin.MainTabPanel.add({
					title: node.text,
					id   : node.id,
					border: false,
					layout: 'fit',
					iconCls: node.attributes.iconCls,
					autoScroll: true,
					closable: true,
					items: [node.attributes.cardconfig]
				}).show();
			}
			else {
				if(! node.leaf){
					node.expand();
				}
			}
		}
	};
	
	
	
/*	TJ.Admin.NewLoadMainTab=function(params){

		var tab = TJ.Admin.MainTabPanel.getComponent(params.id);
		if(tab) {
				TJ.Admin.MainTabPanel.setActiveTab(tab);
		}
		else {
			var url = TJ.LANGUAGESS +  params.id;
			tab = TJ.Admin.MainTabPanel.add({
				title: params.text,
				id   : params.id,
				border: false,
				layout: 'fit',
				iconCls: params.iconCls,
				autoScroll: true,
				closable: true
			}).show();
			TJ.Admin.GetRemoteComponent({url: url, container: tab});
		}
	};
*/

	TJ.Admin.MainTabChange = function (panel,tab) {
		if(TJ.Admin.MainTreePanel.rendered) {
			var node = TJ.Admin.MainTreePanel.getNodeById(tab.id);
			if(node) {
				if (node.getDepth()>0) {
					node.ensureVisible();			
					node.parentNode.expand();
				}
				node.select();
			}
		}
	};


	TJ.Admin.Request = function(conn,response,options){
		alert(conn.responseText);
	};

	TJ.MergeObject= function (dest,source) {
		for(var name in source) {
			dest[name] = source[name];
		}
		return dest;

	};

	Ext.namespace('TJ.Comp');

/* Nav Tree Card Panel Code */











/* End NavTreeCardPanel Code */


TJ.Comp.SearchField = Ext.extend(Ext.form.TwinTriggerField, {
    initComponent : function(){
        if(!this.store.baseParams){
			this.store.baseParams = {};
		}
		TJ.Comp.SearchField.superclass.initComponent.call(this);
		this.on('specialkey', function(f, e){
            if(e.getKey() == e.ENTER){
                this.onTrigger2Click();
            }
        }, this);
    },

    validationEvent:false,
    validateOnBlur:false,
    trigger1Class:'x-form-clear-trigger',
    trigger2Class:'x-form-search-trigger',
    hideTrigger1:true,
    width:180,
    hasSearch : false,
    paramName : 'query',

    onTrigger1Click : function(){
        if(this.hasSearch){
            this.store.baseParams[this.paramName] = '';
			if (this.store.lastOptions.params)
					this.store.lastOptions.params.start=0;
			this.store.reload();//removeAll();
			this.el.dom.value = '';
            this.triggers[0].hide();
            this.hasSearch = false;
			this.focus();
        }
    },

    onTrigger2Click : function(){
        var v = this.getRawValue();
        if(v.length < 1){
            this.onTrigger1Click();
            return;
        }
		if(v.length < 2){
			Ext.Msg.alert('Invalid Search', 'You must enter a minimum of 2 characters to search');
			return;
		}
		this.store.baseParams[this.paramName] = v;
		if (this.store.lastOptions.params)
			this.store.lastOptions.params.start=0;
        this.store.reload();
        this.hasSearch = true;
        this.triggers[0].show();
		this.focus();
    }
});


// Content Browser Tab Change
TJ.Admin.TableBrowserTabChange = function(panel,tab) {

	var url = (tab.recordid) ?  TJ.LANGUAGESS + tab.ownerCt.initialConfig.tableinfo.baseurl + '-' + tab.recordid + ':' + tab.func :
    							TJ.LANGUAGESS + tab.ownerCt.initialConfig.tableinfo.baseurl + ':' + tab.func;
	if(! tab.loaded) {
		TJ.Admin.GetRemoteComponent({url: url, container: tab});
	}


};

	TJ.Admin.ListManagerTabPanel = Ext.extend(Ext.TabPanel,{
		border: false,
		activeTab: 0,
		defaults : { layout: 'fit', autoScroll: true},

		initComponent: function() {
			this.items=[];
			for(var i=0; i < this.tableinfo.listdefs.length; i++){
				this.items.push( {  title: this.tableinfo.listdefs[i][0],
									qtip: this.tableinfo.listdefs[i][1]
								});
				}
				this.on('tabchange',this.tabChange,this);
				TJ.Admin.ListManagerTabPanel.superclass.initComponent.call(this);
		},
		tabChange: function(tp,tab){
			if(! tab.loaded) {
				tab.add(new TJ.Admin.TableListGridPanel({tableinfo: this.tableinfo, listname: tab.title}));
				tab.doLayout();
				tab.loaded=true;
			}
		}
	});


// Base browser.
// Configs
// tableinfo:  table information.


TJ.Admin.TableGridPanel = Ext.extend(Ext.grid.GridPanel,{
	stripeRows: true,
	border: false,
	scopeRender: function(val,p,record){
		return String.format('{0} ({1})',TJ.TableScopes[val-1],val);
	},
	secureRender: function(val,p,record){
//		return val;
		return val>0 ? 'Yes':'No';

	},
	defaultRender: function(val){
		return Ext.util.Format.ellipsis(Ext.util.Format.stripTags(val),40);

	},

	initComponent: function () {
		TJ.TableScopes = this.tableinfo.scopes;
		for (var i=0; i < this.tableinfo.columns.length ; i++) {
			if(this.tableinfo.columns[i].dataIndex=='_scope')
				this.tableinfo.columns[i].renderer = this.scopeRender;
			else
				if(this.tableinfo.columns[i].dataIndex=='_secure')
					this.tableinfo.columns[i].renderer = this.secureRender;
			else
				if(this.tableinfo.columns[i].evalrenderer) 
					this.tableinfo.columns[i].renderer = eval(this.tableinfo.columns[i].evalrenderer);
			else
				this.tableinfo.columns[i].renderer = this.defaultRender;

		}

		this.columns = this.tableinfo.columns;
		this.store = new Ext.data.Store({
			remoteSort: true,
			proxy:		new Ext.data.HttpProxy ({
									url:  TJ.LANGUAGESS + this.tableinfo.baseurl + ':getdata' }),
			reader:		new Ext.data.JsonReader({
										root: 'rows',
										totalProperty: 'numrows',
										id: '_id'}, this.tableinfo.record)});
		this.view = new Ext.grid.GridView({forceFit: true});
		this.sm = new Ext.grid.RowSelectionModel({
				singleSelect: this.singleSelect });
		this.bbar = new Ext.PagingToolbar({
			pageSize: 20,
			store: this.store,
			displayInfo: true,
			displayMsg: 'Displaying ' + this.tableinfo.lang.plural + ' {0} - {1} of {2}',
			emptyMsg: 'No ' + this.tableinfo.lang.plural + ' to display',
				items: ['-','Search: ', ' ',
                new TJ.Comp.SearchField({
	                width:160,
					store: this.store,
					paramName: 'search'
	            })]
		});
		if (!this.noTitle)
		{
			this.title = this.title || 'Browse ' + this.tableinfo.lang.plural;
		}
		this.initialTitle = this.title;

		TJ.Admin.TableGridPanel.superclass.initComponent.call(this);

		TJ.Admin.TableManager.on('tabledatachange',this.tableDataChange,this);
		this.store.on('load',function(){ this.setTitle(this.initialTitle);},this);

		
	},
    onRender : function(ct, position){
		TJ.Admin.TableGridPanel.superclass.onRender.call(this,ct,position);
		this.store.load();
	},
	tableDataChange: function(table,operation,recordid){
		if(table == this.tableinfo.table) {
			this.setTitle(this.initialTitle + '*');
		}
	}
});


TJ.Admin.TableBrowseGridPanel = Ext.extend(TJ.Admin.TableGridPanel,{
	stateful: true,
	parentFilterID:0,
	viewHandler: function(item){
		var records = this.getSelectionModel().getSelections();
		for(var i=0; i < records.length; i++) {
//			console.log(item);
			this.fireEvent('recordview',{grid: this, record: records[i], activeNode: item.node});
		}
	},
	childHandler: function(item){
//		console.log('CHild clicked',item);		console.log(this.getSelectionModel().getSelected());		console.log('id',this.getSelectionModel().getSelected().id);
		if(item.table) {
			var node = {	id: item.baseurl,
					text: item.text,
					attributes: {table: item.table, iconCls: item.iconCls, parentid: this.getSelectionModel().getSelected().id}
			};
//			console.log(node);
			TJ.Admin.LoadMainTabFromNode(node);
		}
	},
	initComponent: function() {
		this.stateId=  'TJ_Admin_TableBrowseGridPanel_' + this.tableinfo.table;

		this.tbar=[];


	var i;
	var viewItems=[];

	for(i=0;i<this.tableinfo.recordnodes.length; i++){
		viewItems.push( {text:	this.tableinfo.recordnodes[i].text,
						 qtip:  this.tableinfo.recordnodes[i].qtip,
						 iconCls: this.tableinfo.recordnodes[i].iconCls,
						 node: this.tableinfo.recordnodes[i].id,
						 handler: this.viewHandler,
						scope: this
		});

	}

	this.rowMenu=new Ext.menu.Menu({items: viewItems});


	this.viewBtn = new  Ext.SplitButton({
			text: this.tableinfo.recordnodes[0].text,
			disabled: true,
			qtip: this.tableinfo.recordnodes[0].qtip,
			node: this.tableinfo.recordnodes[0].id,
			iconCls: this.tableinfo.recordnodes[0].iconCls,
			handler: this.viewHandler,
			menu: this.rowMenu,
			scope: this
	});
	



	this.tbar.push(this.viewBtn);



		this.on('rowdblclick',function(grid, rowIndex) {
				this.getSelectionModel().getSelected();
				this.fireEvent('recordview',{grid: this, record:  this.getSelectionModel().getSelected(),activeNode:'view'
					});
			},this);

		this.on('rowcontextmenu',function(grid,index,e){
			var xy = e.getXY();
			this.getSelectionModel().selectRow(index);
			this.rowMenu.showAt(xy);
            e.preventDefault();
		},this);

	
		this.deleteBtn= new Ext.Toolbar.Button({
			text: 'Delete',
			disabled: true,
			tooltip: 'Delete the selected ' + this.tableinfo.lang.plural,
			iconCls: 'icon_table_delete',
			scope: this,
			handler: function() {
				var records = this.getSelectionModel().getSelections();

				if(records.length) {
					var msg='<TABLE>';
					var ids = [];
					for(var i=0; i < records.length; i++) {
						msg=msg +'<TR><TD>' + records[i].data['_id'] + '</TD><TD>' + records[i].data[this.tableinfo.summary]+'</TD></TR>';
						ids[i]=records[i].data['_id'];
					}
					msg=msg+'</TABLE>';


					Ext.Msg.show({
					   title:'Please confirm',
					   width: 300,
					   msg: 'Are you sure you want to delete the following records?<BR> ' + msg,
					   buttons: Ext.Msg.YESNO,
					   records: records,
					   scope: this,
					   fn: function(btn){ if(btn=='yes') {
				   				Ext.Ajax.request ({ url:	TJ.LANGUAGESS + this.tableinfo.baseurl + ':delete?ids=' + ids.join(','), ids: ids,
									scope: this,
									callback: function(options, success, response)  {
										var res=TJ.Admin.ProcessJSONResponse(options,success,response);
										for(i=0;i < options.ids.length;i++)
											TJ.Admin.TableManager.tableDataChange(this.tableinfo.table,'delete',options.ids[i]);
											this.store.reload();
									}
								});
							}
					   },
						 
					   animEl: this.deleteBtn,
					   icon: Ext.MessageBox.QUESTION
					});
				}
			}

		});
		if(!this.tableinfo.readonly)
			this.tbar.push(this.deleteBtn);
	
	this.tbar.push('-');

	this.refreshBtn= new Ext.Toolbar.Button({
		text: 'Refresh',
			tooltip: 'Refresh this table',
			iconCls: 'icon-refresh',
			handler: function() {
					this.store.reload();
			},
			scope: this
		});
	this.tbar.push(this.refreshBtn);


		this.exportBtn= new Ext.Toolbar.Button({
			text: 'Export',
			disabled: true,
			tooltip: 'Export the data to csv format',
			iconCls: 'icon_table_save',
			handler: function() {
				this.doExport();
//				alert('Export to be implemented');
			},
			scope: this
		});
		this.tbar.push(this.exportBtn);
//		console.log('children',this.tableinfo.children);

/*
		if(this.tableinfo.children.length) {
			var childItems=[];
			for(i=0;i<this.tableinfo.children.length; i++){
//				console.log('Info for' , this.tableinfo.children[i], TJ.Admin.TableInfo[this.tableinfo.children[i]]);
				childItems.push( {text:	TJ.Admin.TableInfo[this.tableinfo.children[i]].lang.plural,
								 handler: this.childHandler,
								table: this.tableinfo.children[i],
								index: i,
								scope: this,
								baseurl: TJ.Admin.TableInfo[this.tableinfo.children[i]].baseurl,
								iconCls:TJ.Admin.TableInfo[this.tableinfo.children[i]].iconCls});
			}
			this.childBtn = new  Ext.SplitButton({
					text: 'Children',
					disabled: true,
					iconCls: 'icon_table_link',
					handler: this.childHandler,
					index: 0,
					menu: new Ext.menu.Menu({items: childItems}),
					scope: this
			});
			
			this.tbar.push('-');
			this.tbar.push(this.childBtn);
		}
		else
*/
			this.childBtn=null;


		this.parentFilterID = this.parentFilterID || 0;
		if (this.tableinfo.parentClass){

//			this.parentinfo = TJ.Admin.TableInfo[this.tableinfo.parentClass];
			if(this.tableinfo.parentClass){
				this.tbar.push('->');	

				this.tbar.push('Parent Filter:');//this.parentinfo.lang.label +': ' );
				this.tbar.push(' ');
				this.tbar.push({	xtype:'tjparentfilter', 
									value:this.parentFilterID,
									table: this.tableinfo.parentClass,
									listeners: {

										change: { fn: function(field,value){
	//												console.log('new parent ' , value, this);
													this.parentFilterID=value;
													this.store.baseParams['parentid'] = value;
													var o = {start: 0};
													this.store.reload({params:o});
												 },
												scope: this
												}
									}
				});
			}
		}


		
		TJ.Admin.TableBrowseGridPanel.superclass.initComponent.call(this);
		this.store.baseParams['parentid'] = this.parentFilterID;
		this.store.on('load',function(){ this.exportBtn.setDisabled(  this.store.getTotalCount() ===0);},this);




		this.getSelectionModel().on('selectionchange',function(sm){
			this.viewBtn.setDisabled(sm.getCount()===0);
			this.deleteBtn.setDisabled(sm.getCount()===0);
			if(this.childBtn)
				this.childBtn.setDisabled(sm.getCount()!=1);
		},this);
	},
	doExport: function(){
		url = TJ.LANGUAGESS+ this.tableinfo.baseurl + ':doexport?'+Ext.urlEncode(this.store.baseParams);
		location.href=url;
//		window.open(url);
		TJ.Admin.statusGrid.addMessage({message:this.tableinfo.lang.label + ' records exported.'});



	}
});



// Standard Request
	TJ.Admin.ReturnRemoteComponent=function(config) {
		if(config.container)
			config.container.body.mask('Loading...','x-mask-loading');
		Ext.Ajax.request({  url: config.url,
							config: config,
							callback: function(options,success,response){
								var ret = eval(response.responseText);
								if(options.config.container){
									TJ.Admin.ClearPanel(options.config.container);
									options.config.container.add(ret);
									options.config.container.doLayout();
									options.config.container.body.unmask();
								}
								if(options.config.callback)
									options.config.callback.call(options.config.scope || this, ret);
							}
		});

	};

	TJ.Admin.GetRemoteComponent=function(config) {
		config.container.body.mask('Loading...','x-mask-loading');
		Ext.Ajax.request ({ url:  config.url,
							config: config,
//							container: config.container,
							callback: function (options,success, response) {
									var TJInfo = {container : options.config.container};



									eval(response.responseText);
									options.config.container.body.unmask();
									options.config.container.loaded=true;
									if(options.config.callback) 
										options.config.callback.call(options.config.scope || this);
									}
								});
	};

	TJ.Admin.ClearPanel=function(panel) {
		var f;
		if(panel && panel.items) {
			while( (f = panel.items.first())){
			  panel.remove(f, true);
			  Ext.destroy(f);
			}
		}

	};

	TJ.Admin.ValidateRequest = function (config) {
		Ext.Ajax.request ({ url:	config.url,
							params:	config.params,
							callback: function(options, success, response)  {
								var res=TJ.Admin.ProcessJSONResponse(options,success,response);
							}
		});
	};


	TJ.Admin.ProcessJSONResponse = function(options,success, response){
		var res = Ext.util.JSON.decode(response.responseText);
		TJ.Admin.ProcessStandardResponse(res);
		return res;
	};

	TJ.Admin.ProcessStandardResponse = function(res) {
		var i;
		if(! res)
			return;
		if(res.status){
			for ( i=0; i < res.status.length; i++) {
				TJ.Admin.statusGrid.addMessage(res.status[i]);
			}
		}

		if(res.alert){
			 Ext.MessageBox.show({
				   title: res.alert.title,
				   msg: res.alert.message,
				   buttons: Ext.MessageBox.OK,
				   icon: Ext.MessageBox.INFO
			   });
		}
		if(res.redirect) {
//			alert('redirect' + res.redirect);
			Ext.getBody().mask(res.redirect.message || 'Loading...','x-mask-loading');
			window.location=res.redirect.url;
		}
		if(res.console){
			if(console){

				for ( i=0; i < res.console.length; i++) {
					console.log(res.console[i]);

				}
			}

		}
	};

// Content Sequencing
	TJ.Admin.GetSequencePanel = function(info){
		if( (info.parent) && (info.parent.table != info.table))
			return TJ.Admin.GetSimpleSequencePanel(info, info.parent);
		return TJ.Admin.GetSimpleSequencePanel(info);

	};

	TJ.Admin.GetSimpleSequencePanel = function (info, parentinfo) {


		 var preview = new TJ.Admin.TablePreviewGridPanel({tableinfo: info});

		var previewParent = 
			(parentinfo) ? new TJ.Admin.TablePreviewGridPanel({tableinfo: parentinfo}) 
						 : null;



		var tree = new Ext.tree.TreePanel({
						title: 'Sequencing',

						autoScroll:true,
						animate:true,
						enableDD:true,
						rootVisible : false,
						containerScroll: true ,
						loader : new Ext.tree.TreeLoader( {
								dataUrl: TJ.LANGUAGESS + info.baseurl + ':sequencenodes'  }),
						root:  new Ext.tree.AsyncTreeNode({
							text: 'Sequence ' + info.lang.plural,
							draggable: false,
							id: '0'
								}),
						tbar:
						[
							{
								text:'Refresh',
							   iconCls: 'icon-refresh',
					            handler: function() {
										tree.getLoader().load(tree.getRootNode());
										tree.getRootNode().expand();
								},
								scope: this
							},
							{
								text: 'Expand All',
								iconCls: 'icon-expand-all',
								handler: function(){
									var node = tree.getSelectionModel().getSelectedNode();
									if(node)
										node.expand(true);
//									tree.getRootNode().expand(true);
								},
								scope: this
							},
							{
								text: 'Collapse All',
								iconCls: 'icon-collapse-all',
								handler: function(){
									tree.getRootNode().collapse(true);
								},
								scope: this
							}

						],

/*

			this.expandBtn = new Ext.Toolbar.Button({
							toolTip: 'Expand All',
							iconCls: 'icon-expand-all',
							cmd: 'expand',
		                    disabled:true,
							handler: this.doCommand,
							scope: this
						});
			this.collapseBtn = new Ext.Toolbar.Button({
							toolTip: 'Collapse All',
							iconCls: 'icon-collapse-all',
							cmd: 'collapse',
		                    disabled:true,
							handler: this.doCommand,
							scope: this
						});

*/

						listeners: {
									nodedrop: function (obj) {
										Ext.Ajax.request ({ url:  TJ.LANGUAGESS + info.baseurl + ':sequencedo',
															params: {drop:obj.dropNode.attributes._id, point: obj.point, target:obj.target.attributes._id},
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
										}
										});

										},
									nodedragover: function(obj) {
//											if (!obj.target.draggable && obj.point!='append')	return false;
											return true;
									},
									click: function(node,e) {
										var url;
										if(parentinfo) {
											if(node.isLeaf()) {	// this is a child node
												preview.ownerCt.activate(preview);

												preview.setRecordByID(node.attributes['_id']);
											}
											else {
//												console.log(previewParent);

												previewParent.ownerCt.activate(previewParent);
												previewParent.setRecordByID(node.attributes['_id']);
											}
										}
										else {
											preview.setRecordByID(node.attributes['_id']);
										}
									},
									render: function(tree) { tree.getRootNode().expand();}
								}
						});


		var border = new Ext.Panel({
				layout:'border',
				frame: false,
				items: [
						{
							region:'center',
							layout: 'fit',
							items : tree
						},	
				{
					region: 'east',
					width: 400,
					minSize:100 ,
					collapsible: true,
					split: true,
					autoScroll : true,
					layout:'border',
					items: [ {region: 'center',
	 						  xtype:'tabpanel',
				   			  autoScroll: true,
							  activeTab: 0,
							  items: previewParent ? [previewParent, preview] : [preview]
							}]
				}]
		});
		border.doLayout();
		return border;

	};


	TJ.Admin.TableSelectWindow = Ext.extend(Ext.Window,{
                layout:'fit',
				modal: true,
                width:800,
                height:550,
				title: 'Select Content',
                closeAction:'hide',
                plain: true,
		initComponent: function(){
			this.selBtn = new Ext.Button({
						text: 'Select',
	                    disabled:true,
						handler: function(){
							this.doSelect();
						},
						scope: this
					});

			this.closeBtn = new Ext.Button({ text: 'Close', handler: function(){ this.hide(); }, scope: this });
			this.buttons=[this.selBtn,this.closeBtn];
			this.setTitle('Select ' + this.tableinfo.lang.label);
			this.grid = new TJ.Admin.TableSelectGridPanel({tableinfo: this.tableinfo, noTitle: true});

			this.grid.on('rowdblclick',function(grid) {
					this.doSelect();
			},this);

			



			this.items=[this.grid];
	
			TJ.Admin.TableSelectWindow.superclass.initComponent.call(this);
			this.grid.getSelectionModel().on('selectionchange',function(sm){
				this.selBtn.setDisabled(sm.getCount()===0);},this);
		},
		doSelect: function(){
			this.fireEvent('recordselected',this.grid.getSelectionModel().getSelected().json);
//			this.setSelectedId(this.grid.getSelectionModel().getSelected().json._id);
		},

	    show : function(animateTarget, cb, scope){
			TJ.Admin.TableSelectWindow.superclass.show.call(this,animateTarget, cb, scope);
		},
		setSelectedId: function(id){
			this.grid.setSelectedId(id);
		}

	});


// config:
// tableinfo
// selectedid:

TJ.Admin.TableSelectGridPanel = Ext.extend(TJ.Admin.TableGridPanel,{
	singleSelect: true,
	selectedid: 0,
	initComponent: function() {
		TJ.Admin.TableSelectGridPanel.superclass.initComponent.call(this);
		for (var i=0; i < this.getColumnModel().getColumnCount() ;i++ )
		this.getColumnModel().setRenderer(i,function(value,metaData, record, rowIndex, colIndex, store) {

			if(record.id==store.selectedid) {
				metaData.attr='style="background-color:aqua;"';

			}
			return value ;
		});
	},
	setSelectedId: function(id){
		this.store.selectedid=id;
		if(this.rendered)
			this.getView().refresh();
	}
});

	
	




// Status Grid Module


TJ.Admin.statusGrid = function () {
	var grid;
    var store = new Ext.data.SimpleStore({
        fields: [
           {name: 'timestamp'},
           {name: 'message'},
           {name: 'description'},
		   {name: 'code'}
        ]
    });
//    store.loadData(data);	


	var msgRender = function(val,p,record){
//		console.log(record);
		if(record.data.code == 2) // error
			return '<span style="color:red;">' + val + '</span>';
		if(record.data.code == 1) // warning
			return '<span style="background-color:yellow;">' + val + '</span>';
		return val;
	};

	return {
			init: function (config) { 
									grid  = new Ext.grid.GridPanel(
										Ext.apply(
											{ title: 'Status',
												border: false,
											  store: store,
											  columns:  [
												{header: "Timestamp", width: 125, sortable: true, renderer: Ext.util.Format.dateRenderer('Y/m/d H:i:s'), dataIndex: 'timestamp'},
												{header: "Message", width: 500, sortable: true, dataIndex: 'message',renderer: msgRender}
												],
									        stripeRows: true
											},config)
									);

									return grid; }
									,
		  addMessage: function(info) {
										if(grid) {
											store.insert(0,new Ext.data.Record({timestamp: new Date(),message: info.message, description: info.description, code:info.code}));
											Ext.get(grid.getView().getRow(0)).highlight("ffff9c", {duration: 2 });
										}
											else {
												 Ext.MessageBox.show({
													   title: info.title||'Altius',
													   msg: info.message,
													   buttons: Ext.MessageBox.OK,
													   icon: Ext.MessageBox.INFO
												   });
											}
									}
	};

}();



// Related content panel
TJ.Admin.relatedContentPanel = function(reltabs,record) {
	var panel = new Ext.TabPanel( {
			title: 'Related Content',
			items: reltabs,
			defaults : { layout: 'fit', autoScroll: true},
			listeners: {
				tabchange: function(panel,tab) {
					if(! tab.loaded){
						Ext.Ajax.request ({ url:  TJ.LANGUAGESS + '/admin/apps/content-' + tab.initialConfig.related.table + ':gettableinfo',
							callback: function (options,success, response) {
								tableinfo = Ext.util.JSON.decode(response.responseText);
								tab.add(new TJ.Admin.TableRelatedGridPanel({tableinfo: tableinfo, relation : {table: record.table, id: record.id, relname: tab.related.name}}));
								tab.doLayout();
						}
						});
						tab.loaded=true;
					}

				}
		}
	});

	return panel;
};

TJ.Admin.TableAddRemoveGridPanel = Ext.extend(TJ.Admin.TableGridPanel,{
	addText: 'Add {0}',
	addTooltip: 'Add {0}',
	addIconCls: 'icon_user_add',
	remText: 'Remove selected {0}',
	remTooltip: 'Remove selected {0}',
	remIconCls: 'icon_delete',

	initComponent: function() {
		this.window= null;
		this.addBtn= new Ext.Toolbar.Button({
			text: String.format(this.addText, this.tableinfo.lang.plural),
			tooltip: String.format(this.addTooltip, this.tableinfo.lang.plural),
			iconCls: this.addIconCls,
			handler: function() {
				if(this.window === null){
					this.window = new TJ.Admin.TableSelectWindow({tableinfo: this.tableinfo});
					this.window.on('recordselected',this.addRecord,this);
				}
				this.window.show();
			},
			scope: this
		});

		this.remBtn= new Ext.Toolbar.Button({
			text: String.format(this.remText, this.tableinfo.lang.plural),
			tooltip: String.format(this.remTooltip, this.tableinfo.lang.plural),
			iconCls: this.remIconCls,
			disabled: true,
			handler: function() {
				var records = this.getSelectionModel().getSelections();
				var ids=[];
				for(var i=0; i < records.length; i++) {
					ids[i]=records[i].data['_id'];
				}
				this.removeRecords(records,ids);
			},
			scope: this
		});
		

		this.tbar = [this.addBtn,this.remBtn];
	
		TJ.Admin.TableAddRemoveGridPanel.superclass.initComponent.call(this);
		this.store.baseParams = this.baseParams;
		this.getSelectionModel().on('selectionchange',function(sm){
			this.remBtn.setDisabled(sm.getCount()===0);
		},this);
	},
	addRecord: function(record){
//		console.log('Add Record',record);

	},
	removeRecords: function(records,ids) {
//		console.log('Remove Records',records, ids);
	}
});


TJ.Admin.TableListGridPanel = Ext.extend(TJ.Admin.TableAddRemoveGridPanel,{
	enableDragDrop: true,
	initComponent: function(){
		this.baseParams = {listname: this.listname};
		this.noTitle=true;
//		console.log('info',this.tableinfo);
//		this.tableinfo.columns.unshift({header:'Sequence',sortable: true, dataIndex: '_listseq'});
//		this.tableinfo.record.unshift({name:'_listseq',type:'int'});
		TJ.Admin.TableListGridPanel.superclass.initComponent.call(this);
//		console.log('columns',this);
		//hk

	},
	listeners: {
		render: function(g){
		  // Best to create the drop target after render, so we don't need to worry about whether grid.el is null
		
		  // constructor parameters:
		  //    grid (required): GridPanel or EditorGridPanel (with enableDragDrop set to true and optionally a value specified for ddGroup, which defaults to 'GridDD')
		  //    config (optional): config object
		  // valid config params:
		  //    anything accepted by DropTarget
		  //    listeners: listeners object. There are 4 valid listeners, all listed in the example below
		  //    copy: boolean. Determines whether to move (false) or copy (true) the row(s) (defaults to false for move)
		  var ddrow = new Ext.ux.dd.GridReorderDropTarget(g, {
			copy: false
			,listeners: {
			  beforerowmove: function(objThis, oldIndex, newIndex, records){
				 if(records.length==1) {
					var grid = objThis.getGrid();
 					var dest = grid.store.getAt(newIndex);

										Ext.Ajax.request ({ url:  TJ.LANGUAGESS + grid.tableinfo.baseurl + ':listsequence',
															params: {source:records[0].data._id, dest: dest.data._id, listname: grid.listname},
										callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
										}
										});
					
					return true;
//					console.log('Moved ' , records[0].data._id, ' To ' , dest.data._id);
				 }
				 else
					 return false;
				// return false to cancel the move
			  }
			}
		  });
		  // if you need scrolling, register the grid view's scroller with the scroll manager
		  Ext.dd.ScrollManager.register(g.getView().getEditorParent());
		}
		,beforedestroy: function(g){
		  // if you previously registered with the scroll manager, unregister it (if you don't it will lead to problems in IE)
		  Ext.dd.ScrollManager.unregister(g.getView().getEditorParent());
		}
	},
	addRecord: function(record){
		Ext.Ajax.request ({ url:  TJ.LANGUAGESS + this.tableinfo.baseurl + ':listadd',
							params: {listname: this.listname, 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 + ':listrem',
							params: {listname: this.listname, ids:  ids.join(',')},
							callback: function (options,success, response) {
								var res=TJ.Admin.ProcessJSONResponse(options,success, response);
								if(res.success) {
									this.store.reload();
//									return;		// below removes the records manually without update with server.
//									for(var i=0; i < records.length; i++) {
//										this.store.remove(records[i]);
//										ids[i]=records[i].data['_id'];
//									}
								}},
							scope: this	});
	}
});


TJ.Admin.TableRelatedGridPanel = Ext.extend(TJ.Admin.TableAddRemoveGridPanel,{
	initComponent: function(){
		this.baseParams = this.relation;
//				console.log('related',this.relation);
		this.noTitle=true;
		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	});
	}

});





TJ.Admin.RelatedContentGrid = function (info,related,relname) {
	var previewID;
// Do evals on the renderer portions of the column modules
	for (var i=0; i < info.columns.length ; i++) {
		if(info.columns[i].evalrenderer) 
			info.columns[i].renderer = eval(info.columns[i].evalrenderer);
	}
	related['relname']=relname;
//	console.log(related);
    var store = new Ext.data.Store({
        remoteSort: true,
		proxy: new Ext.data.HttpProxy ({
				url:  TJ.LANGUAGESS + info.baseurl + ':getdata'
		}),
		baseParams: related,
		reader: new Ext.data.JsonReader({
            root: 'rows',
            totalProperty: 'numrows',
            id: '_id'}, info.record	)});

    store.load({params: { start: 0, limit: 20}});

    // create the Grid
    var grid = new Ext.grid.GridPanel({
        store: store,
        view: new Ext.grid.GridView({
            forceFit:true
        }),

        columns: info.columns,
        sm: new Ext.grid.RowSelectionModel({
            singleSelect:true,
			listeners: {
				selectionchange: function(sm) {  
							if(sm.getCount()>0)
								grid.getTopToolbar().items.items[1].enable();
							else
								grid.getTopToolbar().items.items[1].disable();
				}
			}
        }),
        stripeRows: true,
		tbar:[ 		{
            text:'Add ' + info.lang.label,
            tooltip:'Add a related ' + info.lang.label,
			iconCls: 'icon_user_add',
            handler : function () {
				TJ.Admin.SelectContent.display(info['class'], {callback: function(record){ 
					Ext.Ajax.request ({ url:  TJ.LANGUAGESS + info.baseurl + ':relatedadd',
										params: {reltab: related.table, relid: related.id, relname: relname, id: record._id},
									callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
											if(res.success) {
												store.reload();
											}
										}
										});
					}});
			}


        }, 		{
            text:'Remove selected ' +info.lang.label,
			iconCls: 'adminuser',
			disabled: true,
            handler : function () {
					var record=grid.getSelectionModel().getSelected();
					Ext.Ajax.request ({ url:  TJ.LANGUAGESS + info.baseurl + ':relatedrem',
										params: {reltab: related.table, relid: related.id, relname: relname, id: record.id},
									callback: function (options,success, response) {
											var res=TJ.Admin.ProcessJSONResponse(options,success, response);
											if(res.success) {
												store.reload();
											}
										}
										});
					}
			}


         ],
		bbar: new Ext.PagingToolbar({
            pageSize: 20,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying ' + info.lang.plural + ' {0} - {1} of {2}',
            emptyMsg: 'No ' + info.lang.plural + ' to display',
				items: [
						'-',			'Search: ', ' ',
                new TJ.Comp.SearchField({
	                width:160,
					store: store,
					paramName: 'search'
	            })]

        })
    });

	return grid;
		
	};


/*
TJ.Admin.CreatePreviewGrid = function (data){
//	console.log('Preview Grid',data);
	if(typeof(data)=='object') {
		var newdata=[];
		for(var key in data)
			newdata.push([key,data[key]]);
		data=newdata;
	}


    var store = new Ext.data.SimpleStore({
        fields: [
           {name: 'field'},
           {name: 'value'}
        ]
    });

    store.loadData(data);

	// create the Grid
    var grid = new Ext.grid.GridPanel({
        store: store,
		autoExpandColumn : 1,
        columns: [
            {header: "Field", dataIndex: 'field'},
            {header: "Value", dataIndex: 'value'}
        ],
        stripeRows: true
    });
	return grid;


};
*/

// Table Manager Tab Panel.
// use tableinfo as configuration.

TJ.Admin.TableManagerTabPanel = Ext.extend(Ext.TabPanel,{
	parentFilterID:0,
	activeTab: 0,
	defaults : {
					autoScroll: true,
					layout: 'fit',
					loaded: false},
//	listeners: {tabchange: tabChange},

	initComponent:function() {
		if(this.tableinfo)
			 this.items = this.tableinfo.tabletabs;
		this.on('tabchange',this.tabChange,this);
        TJ.Admin.TableManagerTabPanel.superclass.initComponent.call(this);
		TJ.Admin.TableManager.on('tabledatachange',this.tableDataChange,this);
    },
	

	tabChange: function(mainpanel,tab) {
		if(tab.func) {		
			if(! tab.loaded) {
				var url;
				if(tab.func == 'browse') {
					this.browsetab=tab;
					this.browsepanel = new TJ.Admin.BrowsePreviewPanel({tableinfo: this.tableinfo, parentFilterID: this.parentFilterID});
					this.browsepanel.grid.on('recordview',function(params) {this.RecordView(params);},this);
					tab.add(this.browsepanel);
					tab.doLayout();
					tab.loaded=true;
				} else
				if(tab.func=='insert'){
//					console.log(this);
					var parent=0;
					if(this.tableinfo.parent){
						parent=this.browsepanel.grid.parentFilterID;

					}

					url = TJ.LANGUAGESS + tab.ownerCt.initialConfig.tableinfo.baseurl + ':' + tab.func + '?parent='+escape(parent);
					TJ.Admin.GetRemoteComponent({url: url, container: tab});


				} else
				if(tab.func=='lists')
				{
					tab.add ( new TJ.Admin.ListManagerTabPanel({
							tableinfo: this.tableinfo
						}));
					tab.doLayout();
					tab.loaded=true;
				} else
				if(tab.func=='sequence')
				{
					tab.add (TJ.Admin.GetSequencePanel(this.tableinfo));
					tab.doLayout();
					tab.loaded=true;
				}

				else if(tab.func) {
					url = (tab.recordid) ?  TJ.LANGUAGESS + tab.ownerCt.initialConfig.tableinfo.baseurl + '-' + tab.recordid + ':' + tab.func :
							TJ.LANGUAGESS + tab.ownerCt.initialConfig.tableinfo.baseurl + ':' + tab.func;
					TJ.Admin.GetRemoteComponent({url: url, container: tab});
				}
			}
		}
	},
	showBrowse: function() {
		this.setActiveTab(this.browsetab);

	},
	tableDataChange: function(table,operation,recordid){
		if(table == this.tableinfo.table) {
			if(operation=='delete'){
				this.recordClose({record: {id: recordid}});
			}
		}

	},

	RecordView: function(params) {
//		console.log('Record View: ' ,params);
		var id = 'RecordView_' + this.tableinfo.table + params.record.id;
		var tab = this.getComponent(id);
		if(tab) {
				this.setActiveTab(tab);
//				tab.recordPanel.setActiveTab(params.activeTab);
		}else{
//				console.log('Should Open' ,params.activeNode);
			var recordpanel = 
				 new TJ.Admin.NavTreeCardPanel ({
				activeNode: params.activeNode,
				rooturl: TJ.LANGUAGESS + this.tableinfo.baseurl + '-' + params.record.id,//'/en/admin/system/test',
//						title:'This is the title of the NavTreeCardPanel', 
				cardDefaults: {	tableinfo: this.tableinfo,
								recordid: params.record.id
								}
				});
//			console.log(recordpanel);

			tab = this.add({	title: this.tableinfo.lang.label +' '+ ( params.record.summary || params.record.data['_summary'] || params.record.data[this.tableinfo.summary] ), 
						recordid: params.record.id, 
						closable: true,
						id : 'RecordView_' + this.tableinfo.table + params.record.id,
						items : recordpanel
					});

			tab.recordpanel= recordpanel;
			tab.show();
		}

	},
	recordClose: function(params) {
		var id = 'RecordView_' + this.tableinfo.table + params.record.id;
		var tab = this.getComponent(id);
		if(tab){
			this.remove(tab);
		}


	}

});


TJ.Admin.BrowsePreviewPanel = Ext.extend(Ext.Panel, {
	layout: 'border',
	frame: false,
	initComponent:function() {


		this.grid = new TJ.Admin.TableBrowseGridPanel({tableinfo: this.tableinfo, parentFilterID: this.parentFilterID});
		this.preview = new TJ.Admin.TablePreviewGridPanel({tableinfo: this.tableinfo,
															region: 'east',
				width: 300,
				minSize: 75,
				collapsible: true,
				collapsed: false,
				split: true,
				autoScroll : true,
				title: 'Preview ' + this.tableinfo.lang.label
		});
		Ext.apply(this, {
            items : [{
						region: 'center',
						layout: 'fit',
						items: this.grid
						}
			,
				this.preview
		]
		});
		TJ.Admin.BrowsePreviewPanel.superclass.initComponent.call(this);
		this.grid.getSelectionModel().on('rowselect',function(sm,ind,record) {
			this.preview.setRecord(record);

		},this);


	}


});

TJ.EventManager = new Ext.util.Observable({});
TJ.EventManager.events={};
//TJ.EventManager.fire = function(verb,opt){
//	this.fireEvent(verb,opt);
//}

TJ.Admin.TableManager = new Ext.util.Observable ({});

TJ.Admin.TableManager.addEvents({'tabledatachange': true});

TJ.Admin.TableManager.tableDataChange = function(table,operation,recordid) {
		this.fireEvent('tabledatachange', table, operation,recordid);
	};


TJ.Admin.TableManager.addEvents({'loginsucces': true});

TJ.Admin.TableManager.loginSuccess = function(usersummary){
	this.fireEvent('loginsuccess',usersummary);
};





// Translation


	TJ.Admin.TranslationGridPanel = Ext.extend(Ext.grid.EditorGridPanel, {
		title:'Template Translations',
        stripeRows: true,
		border: false,
		initComponent: function(){


	        this.columns = [
					{header: "Code", width: 150, sortable: true, dataIndex: 'code'}];

			for(lang in TJ.LANGUAGEDESC){
				this.columns.push(
					{header: TJ.LANGUAGEDESC[lang], width: 150, sortable: true, dataIndex: 'trans_' + lang,editor: new Ext.form.TextArea({ })}
				);
			}
//			this.columns.push(	{header: "Usage", width: 50, sortable: true, dataIndex: 'usage'});
			this.columns.push(  {header: "Count", width: 50, sortable: true, dataIndex: 'count'} );

			for(lang in TJ.LANGUAGEDESC){
				this.columns.push(
					{header: 'Default (' + lang + ')' , width: 100, sortable: true, dataIndex: 'default_' + lang}
				);
			}
			this.columns.push(  {header: "Description", width: 200, sortable: false, dataIndex: 'help'} );

				this.store = new Ext.data.Store( {
					remoteSort: true,
					proxy: new Ext.data.HttpProxy({
						url:  TJ.LANGUAGESS + 'admin/utilities/translation:getdata' }),
					reader: new Ext.data.JsonReader({
						root: 'rows',
						totalProperty: 'numrows',
						id: 'code'
						},
						[	{name:'code'},
							{name:'trans_en'},
							{name:'trans_fr'},
							{name:'count'},
							{name:'help'},
							{name:'default_en'},
							{name:'default_fr'}
							])
					});
					this.store.on({
							update: {scope: this, fn: this.recordUpdate},
							beforeload:{scope: this, fn: this.beforeLoad}
							});

					this.scanBtn = new Ext.Toolbar.Button({
							text: 'Scan Templates',
							tooltip: 'Scan Templates',
							iconCls: 'icon_style_go',
							handler: this.doScan,
							scope: this
						});

					this.saveBtn = new Ext.Toolbar.Button({
							text: 'Save Changes',
							tooltip: 'Save Changes',
							iconCls: 'icon_accept',
							handler: this.saveChanges,
							disabled: true,
							scope: this
						});
					this.writeBtn = new Ext.Toolbar.Button({
							text: 'Write Translation File',
							tooltip: 'Write File',
//							iconCls: 'icon_accept',
							handler: this.writeFile,
							scope: this
						});

					this.cancelBtn = new Ext.Toolbar.Button({
							text: 'Cancel Changes',
							tooltip: 'Cancel Changes',
							iconCls: 'icon_cancel',
							handler: this.cancelChanges,
							disabled: true,
							scope: this
						});

				this.tbar=[this.saveBtn, this.cancelBtn,'-',this.writeBtn,this.scanBtn];

				this.bbar =  new Ext.PagingToolbar({
					pageSize: 20,
					store: this.store,
					displayInfo: true,
					displayMsg: 'Displaying Translations  {0} - {1} of {2}',
					emptyMsg: 'No Translations to display',
				items: ['-','Search: ', ' ',
                new TJ.Comp.SearchField({
	                width:160,
					store: this.store,
					value: this.code,
					paramName: 'search'
	            })]

				});

				this.store.load({params: {start: 0, limit: 20, search: this.code }});
				TJ.Admin.TranslationGridPanel.superclass.initComponent.call(this);

			},
			recordUpdate: function(store, record, operation){
				this.saveBtn.setDisabled(false);
				this.cancelBtn.setDisabled(false);
				this.scanBtn.setDisabled(true);

			},
			beforeLoad: function(store, options){
				if(this.store.getModifiedRecords().length >0) {
					Ext.Msg.show({
					   title:'Updates not saved',
					   width: 300,
					   msg: 'Please save or cancel your changes before loading new data.',
					   buttons: Ext.Msg.OK,
					   icon: Ext.MessageBox.INFO
					});

					return false;
				}
				this.store.rejectChanges();
				this.saveBtn.setDisabled(true);
				this.cancelBtn.setDisabled(true);
				this.scanBtn.setDisabled(false);
				return true;

			},
			doScan: function() {
						var options = {
							 url: TJ.LANGUAGESS + 'admin/utilities/translation:scan',
							 scope: this,
							 callback: TJ.Admin.ProcessJSONResponse
							};
						Ext.Ajax.request(options);
			},
			writeFile: function(){

						var options = {
							 url: TJ.LANGUAGESS + 'admin/utilities/translation:write',
							 scope: this,
							 callback: function(o,s,r) {  TJ.Admin.ProcessJSONResponse(o,s,r);}
							};
						Ext.Ajax.request(options);
			},

			saveChanges: function() {
				var recs= this.store.getModifiedRecords();
				for(var i=0; i < recs.length;i++){

						var options = {
							 url: TJ.LANGUAGESS + 'admin/utilities/translation:save',
							 record: recs[i],
							 scope: this,
							 params:recs[i].data,
							 callback: this.saveCallback
							};
						Ext.Ajax.request(options);

					}
			},
			saveCallback:function(options, success, response) {
				TJ.Admin.ProcessJSONResponse(options,success,response);

				// process Ajax success
				if(true === success) {
					options.record.commit();
				}
				if(this.store.getModifiedRecords().length===0) {
						this.saveBtn.setDisabled(true);
						this.cancelBtn.setDisabled(true);
						this.scanBtn.setDisabled(false);
				}
				return;
			},
			cancelChanges: function() {
				Ext.Msg.show({
				   title:'Please confirm',
				   width: 300,
				   msg: 'Are you sure you want to cancel these changes?',
				   buttons: Ext.Msg.YESNO,
				   scope: this,
				   fn: function(btn){ if(btn=='yes') {
						this.store.rejectChanges();
						this.saveBtn.setDisabled(true);
						this.cancelBtn.setDisabled(true);
						this.scanBtn.setDisabled(false);
					 }
				   },
				   icon: Ext.MessageBox.QUESTION
				});


			}

	});
Ext.reg('tjadmin_translationgridpanel',TJ.Admin.TranslationGridPanel);

Ext.reg('tjtranslationgridpanel',TJ.Admin.TranslationGridPanel);

/* NavTreeCardPanel */

TJ.Admin.NavTreeCardPanel = Ext.extend(Ext.Panel,{
	layout: 'border',
	border: false,
	treeWidth: 160,
	
	initComponent: function() {
		this.tp = this.getTreePanel();
		if(this.activeNode) {
			this.tp.on('load',function(node){ 
					var activenode = this.tp.getNodeById(this.activeNode); 
					if(activenode) {
						activenode.select();
						this.setActiveCard(activenode);			
						if(this.activeNodeExpand)
							activenode.expand();
					} },
					this,
					{single:true,delay:10});
		}

		this.cp = this.getCardPanel();
		this.items=[ {
						region: 'west',
						layout: 'fit',
						items:	this.tp,
						split: true,
						width: this.treeWidth,
						frame: false,
						title: 'Options',
			tools: [ { id: 'refresh',
					   handler: function(e){ //console.log('hello'); 									
								this.tp.getLoader().load(this.tp.getRootNode());
								TJ.Admin.ClearPanel(this.cp);
							},
						scope: this
				}],

						collapsible: true
					},{
						region: 'center',
						layout: 'fit',
						frame: false,
						items:  this.cp,
						frame:  false
						}
				];
		TJ.Admin.NavTreeCardPanel.superclass.initComponent.call(this);
		this.tp.getSelectionModel().on('selectionchange',function(sm,node){
				if(node)
					this.setActiveCard(node);
			},this);

//		this.tp.on('click',this.setActiveCard,this);
	},
	setActiveCard: function(node) {

		for(var i = 0; i < this.cp.items.length; i++){
			if(this.cp.items.itemAt(i).path==node.getPath()) {
				this.cp.layout.setActiveItem(this.cp.items.itemAt(i));
				return;
			}
		}
		this.addCard(node);
	},
	addCard: function(node){
//		console.log('addcard', node.getPath());
		var config={iconCls: node.attributes.iconCls,
					tree: node.getOwnerTree() ,
					path: node.getPath()};
		if(node.attributes.cardconfig){
			Ext.apply(config,node.attributes.cardconfig);
		}
		else if(node.attributes.xtype) {
			Ext.apply(config,{xtype: node.attributes.xtype});
		} else {

				if(node.leaf){
						Ext.apply(config,{xtype:'panel',title:'Page not Defined: ' + node.getPath() });
				} else {
					if(this.cp.layout.activeItem)
						this.cp.layout.activeItem.hide();
					node.toggle();
					return;

				}


		
		}
		this.cp.layout.setActiveItem(this.cp.add(config));

	},

	getTreePanel: function(){
		return new Ext.tree.TreePanel({
//			title: 'Tree Panel',
			border: false,
			autoScroll: true,
			enableDD: false,
			containerScroll: true,
			rootVisible: false,

			root : new Ext.tree.AsyncTreeNode({
					id: 'root',
					text: this.rootTitle || 'Home'
				}),
			loader: new Ext.tree.TreeLoader({
					dataUrl:this.rooturl + ':getnodes'
				})
		});
	},
	getCardPanel: function(){
		return new Ext.Panel ({
			layout: 'card',
			activeItem: 0,
			border: false,
			frame: false,
			defaults: Ext.apply({
								tools: [ { id: 'close',
										   handler: function(e,t,p){ 
											this.cp.remove(p,true);
											this.tp.getSelectionModel().clearSelections();
										},
											scope: this
									}],
								border: false,
								frame: false,
								rooturl: this.rooturl

								},this.cardDefaults),
			html: '<div class="x-panel-header"><span class="x-panel-header-text">Please Choose an option</span></div>'
		});
	}
});

Ext.reg('tjnavtreecardpanel',TJ.Admin.NavTreeCardPanel);
// Base Class for NavCard
// Feature for Dirty data management
// Can Close request

TJ.Admin.NavCardPanel = Ext.extend(Ext.Panel,{
	layout: 'fit',
	dirty: false,
	isDirty: function(){
		return this.dirty;
	},
	markDirty: function(dirty){
		this.dirty=dirty;
		this.fireEvent('dirty',this,dirty);
	}
});




// System Component

TJ.Admin.SystemPanel = Ext.extend(Ext.Panel,{
	title: 'System',
		initComponent: function(){
		this.tbar= [
				{
		            text:'Write Icon CSS',
					handler:function(btn, item){
						TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:WriteIconCSS'});
						}
			},{

		            text:'Reset Class Cache',
					handler:function(btn, item){
						TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:ClearClassCache'});
						}
			},{

		            text:'Reset Main Cache',
					handler:function(btn, item){
						TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:ClearMainCache'});
						}
			},{

		            text:'CHMOD Files Dir to 0777',
					handler:function(btn, item){
						TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:ChmodFiles'});
						}
			},{
				text: 'Load Permissions Table',
				handler: function(btn,item) {
					TJ.Admin.ValidateRequest({url: '/en/admin/system:LoadPermissions'});
					}


			},{
		            text:'Test Email',
					handler:function(btn, item){
						TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:TestEmail'});
						}
			},{

				text: 'Migrate App Configs',
				handler: function(btn,item) {
					TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:MigrateConfigs'});
//					TJ.Admin.GetRemoteComponent({url: TJ.LANGUAGESS + 'admin/system:MigrateConfigs', container: component});
					}


			},{

				text: 'Migrate Lang Configs',
				handler: function(btn,item) {
					TJ.Admin.ValidateRequest({url: TJ.LANGUAGESS + 'admin/system:MigrateLangConfigs'});
//					TJ.Admin.GetRemoteComponent({url: TJ.LANGUAGESS + 'admin/system:MigrateConfigs', container: component});
					}


			}
			
			];
			TJ.Admin.SystemPanel.superclass.initComponent.call(this);
	}




});

Ext.reg('tjadmin_systempanel',TJ.Admin.SystemPanel);

Ext.Ajax.on('requestcomplete', function(conn,res,opt){
//	console.log('All Ajax Requests',res);
	var json ={};
		try {
			json = Ext.decode(res.responseText);
		}
		catch(ex) {
		}
	if(json && json.AccessDenied){
		var message;
		if(json.AccessDenied=='Guest'){
			TJ.Admin.MainWindow.setUser({});
			return;
//			message='You are not logged in.  Please login again to continue';
		}
		else
			message='You do not have sufficient permissions for this operation';

			 Ext.MessageBox.show({
				   title: 'Access Denied',
				   msg: message,
				   buttons: Ext.MessageBox.OK,
				   icon: Ext.MessageBox.INFO
			   });

	}
});


TJ.comp.FontSizeButton=Ext.extend(Ext.CycleButton,{
	showText: true,
	stateful: true,
	stateId: 'TJ_Admin_FontSize',
    prependText: 'Text size: ',
	forceIcon:'icon_font',
	stateEvents: ['click','change'],
	itemIndex:0,
	getState: function(){
		
		return {itemIndex:this.itemIndex};

	},
	render: function(pos,ct){
		TJ.comp.FontSizeButton.superclass.render.call(this,pos,ct);
		this.setActiveItem(this.itemIndex);
	},
	items: [	
			{ text: 'Small', sheet: 'text-small.css', checked:true},
			{ text: 'Medium',sheet: 'text-medium.css'},
			{ text: 'Large', sheet: 'text-large.css' }
	],

	changeHandler: function(b,item){
		this.itemIndex=item.itemIndex;
		Ext.util.CSS.swapStyleSheet('fontsize', '/lib/base/css/' + item.sheet);
	}
});

TJ.AltiusBtn = Ext.extend(Ext.Button,{
	text: 'Altius',
	iconCls: 'icon_altius',
	altiusWindow: false,
	handler: function(){ 
		this.altiusWindow=window.open('http://www.altiussoftware.com','AltiusHome').focus();
	},
	scope: this
			
});
