/* File: base/script/tj_admin_pagemanager.js





*/

Ext.namespace('TJ.Admin.LM');


/* Page Manager Components */


TJ.Admin.LM.setXtype = function(info){
			if(info.xtype)
				return info.xtype;
			if (info.serverType=='cl_pm_row')
				return 'tjadmin_pm_row';
			if (info.serverType=='cl_pm_column')
				return 'tjadmin_pm_column';
			return 'tjadmin_pm_cell';

		};



TJ.Admin.LM.initDragZone = function(panel) {

	panel.dragZone = new Ext.dd.DragZone(panel.body, {

		ddGroup:'PMDDGroup',
//      On receipt of a mousedown event, see if it is within a draggable element.
//      Return a drag data object if so. The data object can contain arbitrary application
//      data, but it should also contain a DOM element in the ddel property to provide
//      a proxy to drag.
        getDragData: function(e) {
//			return false;
			var sourceEl= e.getTarget('.pm-dragsource',10,true);

			if(sourceEl) {
				sourceCmp=Ext.getCmp(sourceEl.id);

					proxyEl = sourceEl.child(sourceCmp.proxySelector,false);
					d= proxyEl.dom.cloneNode(true);
					d.id=Ext.id();
					Ext.fly(d).setWidth(proxyEl.getWidth());
					return {
						copy:e.ctrlKey,
						sourceCmp: sourceCmp,
						repairXY: proxyEl.getXY(),
						ddel: d
					};
				
			}

        },

//      Provide coordinates for the proxy to slide back to on failed drag.
//      This is the original XY coordinates of the draggable element.
        getRepairXY: function() {
            return this.dragData.repairXY;
        }
    });
};



TJ.Admin.LM.initDropZone = function(panel){
	Ext.dd.ScrollManager.register(panel.body);
	
    panel.dropZone = new Ext.dd.DropZone(panel.body, {
			ddGroup:'PMDDGroup',
//      If the mouse is over a target node, return that node. This is
//      provided as the "target" parameter in all "onNodeXXXX" node event handling functions
        getTargetFromEvent: function(e) {
            return e.getTarget('.pm-dropsource');
        },
//      On entry into a target node, setup data for node over.
        onNodeEnter : function(target, dd, e, data){ 
			// setup this information for use in onNodeOver
			this.targetCmp=Ext.getCmp(target.id);
	    },

//      On exit from a target node, unhighlight that node.
        onNodeOut : function(target, dd, e, data){ 
			this.targetCmp.ddPaintClear();
        },

		getSourceCmpFromNode: function(node){
			node.attributes.info.title=node.attributes.text;
			return {	 
				        xtype:TJ.Admin.LM.setXtype(node.attributes.info),// used for drag drop information
						// xtype information is included in node attributes after the Sep 2009 update.
						getServerConfig: function(){
							return node.attributes.info;
						}
				};
			},
        onNodeOver : function(target, dd, e, data){ 


			// setup tree node values if they don't exist.
			if(! data.sourceCmp){
				data.sourceCmp=this.getSourceCmpFromNode(data.node);
			}
//			ret1=this.checkCanDrop(targetEl,dd,e,data);
			ret=this.targetCmp.ddCanDrop(e,data,1);


			if(ret) {
				if (data.copy)
					return 'x-dd-drop-ok-add';
				else {
					if(this.targetCmp.dropIndex==-1)
						return 'x-dd-drop-ok-left';
					else
						return Ext.dd.DropZone.prototype.dropAllowed;

				}

			}
			return Ext.dd.DropZone.prototype.dropNotAllowed;
        },

//      On node drop, we can interrogate the target node to find the underlying
//      application object that is the real target of the dragged data.
//      In this case, it is a Record in the GridPanel's Store.
//      We can use the data set up by the DragZone's getDragData method to read
//      any data we decided to attach.
        onNodeDrop : function(target, dd, e, data){

			this.dropIndex=this.targetCmp.dropIndex;



			ret=this.targetCmp.ddCanDrop(e,data,false);  //no paint
			if(ret){
				config = data.sourceCmp.getServerConfig();
				config.xtype=data.sourceCmp.xtype;

				if(data.copy){		//  reset title for copies{

					config.title='Copy of ' + config.title;


				}
				if(this.dropIndex==-1) {  // append mode
					newCmp=	this.targetCmp.add(config);
					if(newCmp.getEl())
						newCmp.getEl().highlight();

					if(data.sourceCmp.ownerCt && ! data.copy)
						data.sourceCmp.ownerCt.remove(data.sourceCmp);
					this.targetCmp.doLayout();

				} else {
					newCmp = this.targetCmp.ownerCt.insert(this.dropIndex,config);
					if(newCmp.getEl())
						newCmp.getEl().highlight();
					if(data.sourceCmp.ownerCt  && ! data.copy)
						data.sourceCmp.ownerCt.remove(data.sourceCmp);
					this.targetCmp.ownerCt.doLayout();
				}
				return true;
			}
			return false;

        }
    });

};



TJ.Admin.LM.Designer = Ext.extend(Ext.Panel,{
//	title: 'Layout Designer',
	mode: 'page',
	layout: 'border',
	frame: false,
	border: false,
	// set and get both support Object only
	getValue: function(){
		return this.pm.getServerConfig();
	},
	setValue: function(value){
//		console.log('Designer Set Value',value, this.pm);
		if(this.pageSelector){
			if(value && value.values && value.values.pagelayout) {
				this.pageSelector.setValue(value.values.pagelayout);
			}
//			this.pageSelector.setValue(1);
//			console.log(value.values.pagelayout);
			


		}
		this.pm.setValue(value);
		this.setActiveItems(this.pm,true);
	},
	doRefresh: function() {
//		console.log('dorefresh', 'beta',this.tp.topToolbar.beta.pressed,'disc',this.tp.topToolbar.disc.pressed);

//		console.log(this.tp.getLoader(), this.tp.getLoader().baseParams);
		this.tp.getLoader().baseParams.beta=this.tp.topToolbar.beta.pressed?1:0;
		this.tp.getLoader().baseParams.disc=this.tp.topToolbar.disc.pressed?1:0;

		this.tp.getLoader().load(this.tp.getRootNode());
	},
	initComponent: function (){
		this.tp = new Ext.tree.TreePanel({
			ddGroup:'PMDDGroup',
			title: 'Content Cells',
			region: 'west',
			border: false,
			width:  160,
			split: true,
			autoScroll: true,
			collapsible: true,
			enableDrag: true,
			rootVisible: false,
			root : new Ext.tree.AsyncTreeNode({
					id: 'root',
					text: 'Home'
				}),
			loader: new Ext.tree.TreeLoader({
					dataUrl: '/en/admin/pagemanager:getnodes',
					baseParams: {mode: this.mode, beta:true,disc:false}
				}),
			tools: [ { id: 'refresh',
					   handler: this.doRefresh,
						scope: this
				}],
			tbar: new Ext.Toolbar( {
								items: [
									'Display',' ',
									new Ext.Button({
										ref: 'beta',
//										text: 'Beta',
										tooltip: 'Show Beta Cells',
										enableToggle: true,
										pressed: true,
										iconCls: 'icon_page_white_get',
										listeners : {
												'click' : {fn:this.doRefresh,scope:this}
										}
									}),' ', 
									new Ext.Button({
										ref: 'disc',
//										text: 'Discontinued',
										tooltip: 'Show Discontinued Cells',

										enableToggle: true,
										iconCls: 'icon_page_white_error',
										listeners : {
												'click' : {fn:this.doRefresh,scope:this}
										}

									})

									]
							})
				
		});
		
		this.tp.getSelectionModel().on('selectionchange',function(sm,node){
			if(node) {
			console.log('sm',node.attributes.info);
			if(node.attributes.info) {
				TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + 'admin/pagemanager:getConfigFields2?serverType='+ node.attributes.info.serverType, 
											callback: function(val){this.classConfigs[node.attributes.info.serverType]=val;},
											scope: this});
			}
			}
		},this);

		this.addSectionBtn = new Ext.Toolbar.Button({iconCls: 'icon_html_add',text: 'Add Section', disabled: false, handler: this.addSection, scope: this});
//		this.tbar=[this.addSectionBtn];


		this.ts = new Ext.TabPanel({
			region: 'center',
			activeTab: 0,
			border: false
//			items : [ new Ext.Panel( {layout: 'fit',title: 'Designer', items: [this.pm]})],
//			tbar: [this.addSectionBtn]
		});
		switch(this.mode){
			case 'multicontent':
				this.initMultiContent();
				break;
			case 'content':
				this.initContent();
				break;
			case 'page':
				this.initPage();
				break;
			default:
				this.initContent();
			break;
		}
		this.pg=this.getEditor();


		this.items = [this.tp,this.ts,this.pg
			];



 		TJ.Admin.LM.Designer.superclass.initComponent.call(this);
		activeItem=null;
	},
	initPage: function() {
		this.pm = Ext.ComponentMgr.create( {
				xtype:'tjadmin_pm_main',
				mode: this.mode,
				border: false
			});
		this.ts.add( new Ext.Panel( {layout: 'fit',title: 'Page Designer', items: [this.pm]}));

	},
	initContent: function() {
		this.pm = Ext.ComponentMgr.create( {
				xtype:'tjadmin_pm_main',
				mode: this.mode,
				border: false
			});
		this.ts.add( new Ext.Panel( {layout: 'fit',title: 'Designer', items: [this.pm]}));


	},
	initMultiContent: function() {

//		pageLayout

		var pageSelector = new TJ.comp.Object({table: 'CL_Site_PageLayout_Table', emptyText: '[Select a page layout]'});
	
		var pm=Ext.ComponentMgr.create( {
				xtype: 'tjadmin_pm_main',
				mode: 'page',
				readOnly: true
		});


		pageSelector.on('change', this.pageSelectorChange,this);

		this.ts.add( this.pageLayout=new Ext.Panel( { 
				layout: 'fit', 
				title: 'Page Layout', 
				iconCls:'icon_layout',
				items: pm,
				pm: pm,
				tbar:['Page Layout',pageSelector]

		
		
		}));

	},
	pageSelectorChange: function(f){
		TJ.CallbackManager.GetInfo({url: TJ.LANGUAGESS + f.tableinfo.baseurl + '-' + f.getValue() + ':getrecord2',
									callback: this.pageSelectorCallback,
										scope: this});

		console.log('change page selector',f.getValue(),f.tableinfo);



	},
	pageSelectorCallback:function(f){
		console.log('allback',f.layout);
		this.pageLayout.pm.setValue(Ext.util.JSON.decode(f.layout));
		this.addSection();

	},
	addSection: function(){

			this.ts.add( new Ext.Panel( {layout: 'fit',title: 'Designer222', items: [ Ext.ComponentMgr.create( {
				xtype:'tjadmin_pm_main',
				mode: this.mode,
				border: false
				
			})]}));


	},
	preview: function(panel){
		panel.setContent('&nbsp');
		panel.body.mask('Loading...','x-mask-loading');
				Ext.Ajax.request({  url: '/'+panel.lang+'/admin/pagemanager:preview',
									params: {info:  Ext.util.JSON.encode(this.pm.getServerConfig())},
									callback: function(options,success,response){
										panel.body.unmask();
										if(success)
											panel.setContent(response.responseText);
										else
											panel.body.mask('Preview Failed');
									},
									scope: this
				});
	},
	configChange: function(source,record, value,old){


		if(this.activeObj)
			this.activeObj.setConfigValue(record,value);
		console.log('config chagen', source,record,value,old);

	},
	onDestroy:function() {
		// destroy 
		if(this.pg) {
			this.pg.purgeListeners();
			this.pg.destroy();
			this.pg=null;
		}
		if(this.pm) {
			this.pm.purgeListeners();
			this.pm.destroy();
			this.pm=null;
		}
		if(this.tp) {
			this.tp.purgeListeners();
			this.tp.destroy();
			this.tp=null;
		}

 		TJ.Admin.LM.Designer.superclass.onDestroy.call(this);
	},
	classConfigs:[],
	editor: 'form',
	getEditor: function(){
		var editor;
		var common = {collapsible: true, region:'east',border: false, split: true, width: 280};
		if(this.editor=='form') {
			editor= new Ext.Panel(Ext.apply({
					title:'Properties', 
					layout:'fit',
					frame: false,
					border: false
					
			
			},common));
		}
		else {
	
			editor = new Ext.grid.PropertyGrid (
					Ext.apply(	
					{	title: 'Properties',propertyNames: {} }, 
					common));

					
			editor.store.sortInfo = null; 
			editor.on('propertychange',this.configChange,this);
		}
		return editor;

	},

	startForm: function(item) {
		console.log('start form',item);
		if(this.classConfigs[item.serverType]){
			this.loadForm(item);
		} else {
				if(this.pg.body)
					this.pg.body.mask('Loading...','x-mask-loading');
				Ext.Ajax.request({  url: '/en/admin/pagemanager:getConfigFields',
									item: item,
									params: {serverType: item.serverType},
									callback: function(options,success,response){
										if(this.pg.body)
											this.pg.body.unmask();
										ret = Ext.util.JSON.decode(response.responseText);
										this.classConfigs[item.serverType]=ret;
										this.loadForm(item);

	
									},
									scope: this
				});
		}

	},
	loadForm: function(item){
		var fields = TJ.clone(this.classConfigs[item.serverType].fields);
//		console.log('should save',this.form);
		TJ.Admin.ClearPanel(this.pg);
//		console.log('set',item.values);


		var field;
		var values={};
		for (var key=0;key < fields.length; key++){
			field=fields[key];
			if(! item.values) 
				item.values={};

			
			if(item.values[field.name]!==null && typeof(item.values[field.name])!=='undefined'){ // value exists in item
				field.value=item.values[field.name];
			}
			else if(item.values[field.basename]!==null && typeof(item.values[field.basename])!=='undefined'){ // value exists in item as a basename default
				field.value = item.values[field.name] = item.values[field.basename];
			}
			else{		// use the value that is default within the field
				item.values[field.name]=field.value;
			}
			values[field.name]=field.value;
		}

		fields.unshift({ xtype:'tjtext',name:'_name',allowBlank: false, value:item.title, fieldLabel:'<b>Name</b>'});

//		fields.unshift({ xtype:'hidden',name:'_version',value:this.classConfigs[item.serverType].version, fieldLabel:'<b>Version</b>', readOnly: true});

//	alert('must update tjadminform layout to allow for anchor');
		this.form = 	new Ext.FormPanel ({
				frame: true,
				border: false,
				autoScroll: true,
				layout: 'tjadminform',

				labelWidth: 100,
//				width: this.pg.getInnerWidth(),
				defaults: { 	anchor:'-35',
					            msgTarget: 'side',
								width: 100,
								formValues:values,
								
					listeners: { 
							collapse: { 
								fn:function(f){  
									this.fieldChange(f);
								},scope:this},
							keypress: {
									fn: function(f){
										console.log('keypress',f);
//										this.fieldChange(f);
									},scope:this},
							change: { 
								fn:function(f){  
									if(tinyMCE) tinyMCE.triggerSave();
									this.fieldChange(f);
								},scope:this}
					}},
				items: fields

			});
//		console.log('vals',values);
		var focusField=false;
		this.form.items.each(function(field){
			if(!focusField && field.focus){
				focusField=field;
			}
			if(field.disableField) {
				field.setDisabled(! values[field.disableField]);
			}
			field.form=this.form.getForm();
		}, this);

	this.pg.setTitle(String.format('Properties:  {0} (v{1})', this.classConfigs[item.serverType].name ,this.classConfigs[item.serverType].version) );	

	this.pg.add(this.form);
	this.pg.doLayout();

	if(focusField)
		focusField.focus(true);
	},
	fieldChange: function(f){

		this.form.items.each(function(i){
			if(i.siblingChange)
				i.siblingChange(f);
			if(i.disableField == f.name){
				i.setDisabled(! f.getValue());
			}
		});

//		console.log('change!!!',f.name,f.getValue());

		if(this.activeObj)
			this.activeObj.setConfigValue(f.name,f.getValue());

	},
	startPropertyGrid: function(item){
		if(this.classConfigs[item.serverType]){
			this.loadPropertyGrid(item);
		}else{
				if(this.pg.body)
					this.pg.body.mask('Loading...','x-mask-loading');
				Ext.Ajax.request({  url: '/en/admin/pagemanager:getConfigFields',
									item: item,
									params: {serverType: item.serverType},
									callback: function(options,success,response){
										if(this.pg.body)
											this.pg.body.unmask();
										ret = Ext.util.JSON.decode(response.responseText);
										this.classConfigs[item.serverType]=ret;
										this.loadPropertyGrid(item);

	
									},
									scope: this
				});
		}




	},
	renderMe: function(v,m,p,row,col,store,other,c){
			console.log('renderMe',v,m,p,row,col,store,other,c);


		return v;

	},
	loadPropertyGrid: function(item){
	
		fields=this.classConfigs[item.serverType].fields;
		
		// clean up old custom editors.
		if(this.pg.customEditors) {
			for (var key in this.pg.customEditors) {this.pg.customEditors[key].destroy();}
		}
		this.pg.customEditors={};
		this.pg.propertyNames={};

		var values=[];

		this.pg.propertyNames['_name']='<b>Name</b>';
		values['_name'] =  item.title;
		if(item.isReadOnly()){
						editor=Ext.ComponentMgr.create({xtype:'textfield', readOnly: true});
						editor.propertyGrid=this.pg;
						this.pg.customEditors['_name']	=	new Ext.grid.GridEditor(editor);

		}

		this.pg.getColumnModel().renderCellDelegate=this.renderMe;

		// setup new custom editors.
			if(fields) {
				for (key=0;key < fields.length; key++){
//					this.pg.customRenderers[fields[key].name]=this.renderMe;
					if(! item.isReadOnly()) {
						editor=Ext.ComponentMgr.create(fields[key]);
						editor.propertyGrid=this.pg;
						this.pg.customEditors[fields[key].name]	=	new Ext.grid.GridEditor(editor);
					} else {
						editor=Ext.ComponentMgr.create({xtype:'textfield', readOnly: true});
						editor.propertyGrid=this.pg;
						this.pg.customEditors[fields[key].name]	=	new Ext.grid.GridEditor(editor);
					}
					this.pg.propertyNames[fields[key].name] =	fields[key].fieldLabel || fields[key].name;
						if(! item.values)
							item.values={};
						if(item.values[fields[key].name]!==null && typeof(item.values[fields[key].name])!=='undefined'){ // value exists in item
							values[fields[key].name] = item.values[fields[key].name];
						}
						else if(item.values[fields[key].basename]!==null && typeof(item.values[fields[key].basename])!=='undefined'){ // value exists in item
							values[fields[key].name] = item.values[fields[key].name] = item.values[fields[key].basename];
						}
						else{
							values[fields[key].name] = item.values[fields[key].name] = fields[key].value;
						}


				}

			}


		this.pg.setTitle('Properties: ' + this.classConfigs[item.serverType].name);
		this.pg.setSource( values);

	},
    setActiveItems : function(item,force){
//		console.log(item);
//        item = Ext.get(item);
//		console.log(item);
        if(this.activeObj != item || force){

            if(this.activeObj){
				title=this.activeObj.getEl().child('.x-panel-header-text');
				if(title)
					title.setStyle({'font-weight': 'normal'});
               }
			if(this.pg.activeEditor && this.pg.activeEditor)
				this.pg.activeEditor.completeEdit();

			if(item.rendered) {
				this.activeObj=item;
//				this.activeObj.getEl().

				title=this.activeObj.getEl().child('.x-panel-header-text');
				if(title)
					title.setStyle({'font-weight':'bold'});
//				console.log('startpro', item);
				if(this.editor=='form') 
					this.startForm(item); 
				else 
					this.startPropertyGrid(item); 
			}


		}

	},
	activeObj: null,
	activateItem: function(item){
	
		this.setActiveItems(item);

	},
	render:function(ct,pos) { 
//		this.deferRender.defer(1000,this,[ct,pos]); return
		TJ.Admin.LM.Designer.superclass.render.call(this, ct,pos); 
		TJ.Admin.LM.initDragZone(this);
//		console.log('designer render');
//		this.setActiveItems.defer(10,this,[this.pm]);


	}, // eo function onRender 
	deferRender: function(ct,pos){

		TJ.Admin.LM.Designer.superclass.render.call(this, ct,pos); 
		TJ.Admin.LM.initDragZone(this);


	}

});

